diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000000..59695180d6 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,68 @@ + +[*.{appxmanifest,axml,build,c,c++,cc,cginc,compute,config,cp,cpp,csproj,cu,cuh,cxx,dbml,discomap,dtd,h,hh,hlsl,hlsli,hlslinc,hpp,hxx,inc,inl,ino,ipp,jsproj,lsproj,mpp,mq4,mq5,mqh,njsproj,nuspec,proj,props,proto,resw,resx,shader,StyleCop,targets,tasks,tpp,usf,ush,vbproj,xml,xsd}] +indent_style = space +indent_size = cs +tab_width = 4 + +[*.{asax,ascx,asmdef,aspx,axaml,cs,cshtml,css,htm,html,js,json,jsx,master,paml,razor,resjson,skin,ts,tsx,vb,xaml,xamlx,xoml}] +indent_style = space +indent_size = 4 +tab_width = 4 + +[*] + +# Microsoft .NET properties +csharp_new_line_before_members_in_object_initializers = false +csharp_preferred_modifier_order = public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion +csharp_style_var_elsewhere = true:suggestion +csharp_style_var_for_built_in_types = true:suggestion +csharp_style_var_when_type_is_apparent = true:suggestion +dotnet_naming_rule.private_constants_rule.severity = warning +dotnet_naming_rule.private_constants_rule.style = upper_camel_case_style +dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols +dotnet_naming_rule.private_instance_fields_rule.severity = warning +dotnet_naming_rule.private_instance_fields_rule.style = lower_camel_case_style +dotnet_naming_rule.private_instance_fields_rule.symbols = private_instance_fields_symbols +dotnet_naming_rule.private_static_fields_rule.severity = warning +dotnet_naming_rule.private_static_fields_rule.style = lower_camel_case_style_1 +dotnet_naming_rule.private_static_fields_rule.symbols = private_static_fields_symbols +dotnet_naming_rule.private_static_readonly_rule.severity = warning +dotnet_naming_rule.private_static_readonly_rule.style = upper_camel_case_style +dotnet_naming_rule.private_static_readonly_rule.symbols = private_static_readonly_symbols +dotnet_naming_style.lower_camel_case_style.capitalization = camel_case +dotnet_naming_style.lower_camel_case_style_1.capitalization = camel_case +dotnet_naming_style.lower_camel_case_style_1.required_prefix = _ +dotnet_naming_style.upper_camel_case_style.capitalization = pascal_case +dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field +dotnet_naming_symbols.private_constants_symbols.required_modifiers = const +dotnet_naming_symbols.private_instance_fields_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_instance_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_fields_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_static_fields_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_fields_symbols.required_modifiers = static +dotnet_naming_symbols.private_static_readonly_symbols.applicable_accessibilities = private +dotnet_naming_symbols.private_static_readonly_symbols.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_symbols.required_modifiers = static,readonly +dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none +dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none +dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none +dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion +dotnet_style_predefined_type_for_member_access = true:suggestion +dotnet_style_qualification_for_event = false:suggestion +dotnet_style_qualification_for_field = false:suggestion +dotnet_style_qualification_for_method = false:suggestion +dotnet_style_qualification_for_property = false:suggestion + +# ReSharper properties +resharper_default_private_modifier = implicit + +# ReSharper inspection severities +resharper_arrange_redundant_parentheses_highlighting = hint +resharper_arrange_this_qualifier_highlighting = hint +resharper_built_in_type_reference_style_for_member_access_highlighting = hint +resharper_built_in_type_reference_style_highlighting = hint +resharper_redundant_base_qualifier_highlighting = warning +resharper_suggest_var_or_type_built_in_types_highlighting = hint +resharper_suggest_var_or_type_elsewhere_highlighting = hint +resharper_suggest_var_or_type_simple_types_highlighting = hint diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..9068a80499 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,33 @@ +* text=auto + +*.cs text eol=crlf + +*.h text eol=crlf +*.c text eol=crlf +*.cpp text eol=crlf + +*.as text eol=crlf +*.hx text eol=crlf + +*.sln text eol=crlf +*.csproj text eol=crlf +*.vbproj text eol=crlf +*.vcxproj text eol=crlf +*.vcproj text eol=crlf +*.dbproj text eol=crlf +*.fsproj text eol=crlf +*.lsproj text eol=crlf +*.wixproj text eol=crlf +*.modelproj text eol=crlf +*.sqlproj text eol=crlf +*.wmaproj text eol=crlf + +*.xproj text eol=crlf +*.props text eol=crlf +*.filters text eol=crlf +*.vcxitems text eol=crlf + +*.bat text eol=crlf +*.cmd text eol=crlf + +*.sh text eol=lf diff --git a/.gitignore b/.gitignore index b1443c2c01..c868e0da44 100644 --- a/.gitignore +++ b/.gitignore @@ -1,22 +1,39 @@ Thumbs.db +*.config +*.fda +*.fdb +*.fdl +*.nupkg +*.obj +*.pdb *.suo *.user -*.pdb -*.obj +*.vs/ *.vshost.exe *.vshost.exe.manifest -*.config -*.fdb -*.fdl -*.fda -obj/ -FlashDevelop/Properties/AssemblyInfo.cs -FlashDevelop/Bin/Debug/FlashDevelop.* -FlashDevelop/Bin/Debug/PluginCore.* -FlashDevelop/Bin/Debug/Plugins/ -FlashDevelop/Bin/Debug/Data/ -FlashDevelop/Bin/Debug/Settings/FormStates/ -PluginCore/Bin -/FlashDevelop/Bin/Debug/Settings/FileStates -/FlashDevelop/Bin/Debug/Settings/Recovery +**/obj/ +**/NSubstitute.* +**/nunit.framework.* +**/Castle.Core.* +/FlashDevelop/Bin/Debug/Apps/ +/FlashDevelop/Bin/Debug/Data/ +/FlashDevelop/Bin/Debug/Plugins/ +/FlashDevelop/Bin/Debug/Settings/FileStates/ +/FlashDevelop/Bin/Debug/Settings/FormStates/ +/FlashDevelop/Bin/Debug/Settings/Recovery/ +/FlashDevelop/Bin/Debug/Settings/Themes/CURRENT +/FlashDevelop/Bin/Debug/Tools/fdbuild/fdbuild.exe +/FlashDevelop/Bin/Debug/*.Tests.dll /FlashDevelop/Bin/Debug/Exceptions.log +/FlashDevelop/Bin/Debug/FlashDevelop.* +/FlashDevelop/Bin/Debug/FlashDevelop64.* +/FlashDevelop/Bin/Debug/PluginCore.* +/FlashDevelop/Properties/AssemblyInfo.cs +/FlashDevelop/Scripting.* +/FlashDevelop/Bin/Debug/CSScriptLibrary.* +/FlashDevelop/Bin/Debug/Microsoft.* +/FlashDevelop/Bin/Debug/System.* +/FlashDevelop/Bin/Debug/Mono.* +/packages/ +/PluginCore/Bin +FlashDevelop/Bin/Debug/LitJSON.* diff --git a/CI/README.md b/CI/README.md new file mode 100644 index 0000000000..684e27f7d7 --- /dev/null +++ b/CI/README.md @@ -0,0 +1 @@ +Coming soon... diff --git a/CI/build.cmd b/CI/build.cmd index a68cfd19da..da152e4c7b 100644 --- a/CI/build.cmd +++ b/CI/build.cmd @@ -1,32 +1,58 @@ :: Builds the binary on the server for CI :: Set paths -set PATH=%PATH%;C:\Windows\Microsoft.NET\Framework\v4.0.30319\ -set PATH=%PATH%;C:\Program Files (x86)\Git\bin\ -set PATH=%PATH%;C:\Program Files\NSIS\ -set PATH=%PATH%;C:\Program Files\7-Zip\ +:: set PATH=%PATH%;C:\Windows\Microsoft.NET\Framework\v4.0.30319\ +:: set PATH=%PATH%;C:\Program Files (x86)\Git\bin\ +:: set PATH=%PATH%;C:\Program Files (x86)\NSIS +:: set PATH=%PATH%;C:\Program Files\7-Zip\ -:: Reset bin files -git clean -f -x -d FlashDevelop\Bin\Debug +:flashdevelop + +:: Extract version from HEAD +call SetVersion.bat + +:: Build the main solution and run tests +msbuild FlashDevelop.sln /p:Configuration=Release+Tests /p:Platform="x64" /t:Rebuild %MSBuildLogger% + +:: Check for build errors +if %errorlevel% neq 0 goto :error + +if "%AppVeyorCI%" neq "" powershell.exe -file ci\tests.ps1 + +:: Check for build errors +if %errorlevel% neq 0 goto :error + +:: Build the main solution and run tests +msbuild FlashDevelop.sln /p:Configuration=Release+Tests /p:Platform="x86" /t:Rebuild %MSBuildLogger% :: Check for build errors if %errorlevel% neq 0 goto :error -:: Build the PluginCore -msbuild PluginCore\PluginCore.csproj /p:Configuration=Release /p:Platform=x86 +if "%AppVeyorCI%" neq "" powershell.exe -file ci\tests.ps1 :: Check for build errors if %errorlevel% neq 0 goto :error +git clean -xfd FlashDevelop\Bin\Debug + :: Extract version from HEAD call SetVersion.bat -:: Build the solution -msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform=x86 +nuget restore FlashDevelop.sln + +:: Build the solutions +msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform="Any CPU" /t:Rebuild +ping -n 5 127.0.0.1 > nul +msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform=x86 /t:Rebuild :: Check for build errors if %errorlevel% neq 0 goto :error +:: Remove files after build +del "FlashDevelop\Bin/Debug\System.*" /Q +del "FlashDevelop\Bin/Debug\Microsoft.*" /Q +del "FlashDevelop\Bin/Debug\Mono.CSharp.*" /Q + :: Create the installer makensis FlashDevelop\Installer\Installer.nsi @@ -39,8 +65,60 @@ if %errorlevel% neq 0 goto :error :: Check for 7zip errors if %errorlevel% neq 0 goto :error +:haxedevelop + +:: Reset bin files +git clean -xfd FlashDevelop\Bin\Debug + +:: Remove unnecessary files +rd "FlashDevelop\Bin\Debug\Tools\flexpmd" /s /q +rd "FlashDevelop\Bin\Debug\Tools\flexlibs\frameworks\libs\player" /s /q +for /d %%G in ("FlashDevelop\Bin\Debug\Projects\*ActionScript 3*") do rd /s /q "%%~G" +del "FlashDevelop\Bin\Debug\StartPage\images\*.*" /q + +:: Copy distro files +xcopy Distros\HaxeDevelop /s /e /y + +:: Check for build errors +if %errorlevel% neq 0 goto :error + +:: Extract version from HEAD +call SetVersion.bat + +:: Build the solutions +msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform="Any CPU" /t:Rebuild +ping -n 5 127.0.0.1 > nul +msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform=x86 /t:Rebuild + +:: Check for build errors +if %errorlevel% neq 0 goto :error + +:: Remove files after build +del "FlashDevelop\Bin\Debug\Plugins\CodeAnalyzer.dll" /q +del "FlashDevelop\Bin/Debug\System.*" /Q +del "FlashDevelop\Bin/Debug\Microsoft.*" /Q +del "FlashDevelop\Bin/Debug\Mono.CSharp.*" /Q + +:: Rename binaries +ren FlashDevelop\Bin\Debug\FlashDevelop.exe HaxeDevelop.exe +ren FlashDevelop\Bin\Debug\FlashDevelop64.exe HaxeDevelop64.exe +ren FlashDevelop\Bin\Debug\FlashDevelop.exe.config HaxeDevelop.exe.config +ren FlashDevelop\Bin\Debug\FlashDevelop64.exe.config HaxeDevelop64.exe.config + +:: Check for build errors +if %errorlevel% neq 0 goto :error + +:: Create the installer +makensis FlashDevelop\Installer\Installer.nsi + +:: Check for nsis errors +if %errorlevel% neq 0 goto :error + +:: Create the archive +7z a -tzip FlashDevelop\Installer\Binary\HaxeDevelop.zip .\FlashDevelop\Bin\Debug\* -xr!.empty + :: Done -exit +exit 0 :error -exit -1 +exit -1 \ No newline at end of file diff --git a/CI/buildl.cmd b/CI/buildl.cmd index 272551c06c..877a1a6ada 100644 --- a/CI/buildl.cmd +++ b/CI/buildl.cmd @@ -1,22 +1,30 @@ :: Builds the binary locally and launches the installer :: Set paths -set PATH=%PATH%;C:\Windows\Microsoft.NET\Framework\v4.0.30319\ -set PATH=%PATH%;C:\Program Files (x86)\Git\bin\ -set PATH=%PATH%;C:\Program Files (x86)\NSIS -set PATH=%PATH%;C:\Program Files\7-Zip\ +:: set PATH=%PATH%;C:\Program Files (x86)\MSBuild\15.0\Bin\ +:: set PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin +:: set PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\MSBuild\Current\Bin +:: set PATH=%PATH%;C:\Program Files\Git\bin\ +:: set PATH=%PATH%;C:\Program Files (x86)\Git\bin\ +:: set PATH=%PATH%;C:\Program Files\7-Zip\ +:: set PATH=%PATH%;C:\Program Files (x86)\7-Zip\ +:: set PATH=%PATH%;C:\Program Files (x86)\NSIS :: Need path up cd .. +:flashdevelop + :: Reset bin files git clean -f -x -d FlashDevelop\Bin\Debug +del FlashDevelop\Installer\Binary\*.exe /Q +del FlashDevelop\Installer\Binary\*.zip /Q :: Check for build errors if %errorlevel% neq 0 goto :error :: Build the PluginCore -msbuild PluginCore\PluginCore.csproj /p:Configuration=Release /p:Platform=x86 /t:Rebuild +msbuild PluginCore\PluginCore.csproj /p:Configuration=Release /p:Platform="AnyCPU" /t:Rebuild :: Check for build errors if %errorlevel% neq 0 goto :error @@ -24,7 +32,9 @@ if %errorlevel% neq 0 goto :error :: Extract version from HEAD call SetVersion.bat -:: Build the solution +:: Build the solutions +msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform="Any CPU" /t:Rebuild +ping -n 5 127.0.0.1 > nul msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform=x86 /t:Rebuild :: Check for build errors @@ -36,16 +46,73 @@ makensis FlashDevelop\Installer\Installer.nsi :: Check for nsis errors if %errorlevel% neq 0 goto :error -:: Delete old and create an new archive -del FlashDevelop\Installer\Binary\FlashDevelop.zip +:: Create the archive 7z a -tzip FlashDevelop\Installer\Binary\FlashDevelop.zip .\FlashDevelop\Bin\Debug\* -xr!.empty :: Check for 7zip errors if %errorlevel% neq 0 goto :error -:: Done +:haxedevelop + +:: Reset bin files +git clean -f -x -d FlashDevelop\Bin\Debug + +:: Remove unnecessary files +rd "FlashDevelop\Bin\Debug\Tools\flexpmd" /s /q +rd "FlashDevelop\Bin\Debug\Tools\flexlibs\frameworks\libs\player" /s /q +for /d %%G in ("FlashDevelop\Bin\Debug\Projects\*ActionScript 3*") do rd /s /q "%%~G" +del "FlashDevelop\Bin\Debug\StartPage\images\*.*" /q + +:: Copy distro files +xcopy Distros\HaxeDevelop /s /e /y + +:: Build the PluginCore +msbuild PluginCore\PluginCore.csproj /p:Configuration=Release /p:Platform="AnyCPU" /t:Rebuild + +:: Check for build errors +if %errorlevel% neq 0 goto :error + +:: Extract version from HEAD +call SetVersion.bat + +:: Build the solutions +msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform="Any CPU" /t:Rebuild +ping -n 5 127.0.0.1 > nul +msbuild FlashDevelop.sln /p:Configuration=Release /p:Platform=x86 /t:Rebuild + +:: Check for build errors +if %errorlevel% neq 0 goto :error + +:: Rename binaries +ren FlashDevelop\Bin\Debug\FlashDevelop.exe HaxeDevelop.exe +ren FlashDevelop\Bin\Debug\FlashDevelop64.exe HaxeDevelop64.exe +ren FlashDevelop\Bin\Debug\FlashDevelop.exe.config HaxeDevelop.exe.config +ren FlashDevelop\Bin\Debug\FlashDevelop64.exe.config HaxeDevelop64.exe.config + +: Remove files after build +del "FlashDevelop\Bin\Debug\Plugins\CodeAnalyzer.dll" /q + +:: Check for build errors +if %errorlevel% neq 0 goto :error + +:: Create the installer +makensis FlashDevelop\Installer\Installer.nsi + +:: Check for nsis errors +if %errorlevel% neq 0 goto :error + +:: Create the archive +7z a -tzip FlashDevelop\Installer\Binary\HaxeDevelop.zip .\FlashDevelop\Bin\Debug\* -xr!.empty + +:finish + +:: Revert distro changes with backup +git stash save "Local CI Backup..." + +:: Done, Run FD start FlashDevelop\Installer\Binary\FlashDevelop.exe -exit +exit 0 :error +pause exit -1 diff --git a/CI/deploy.ps1 b/CI/deploy.ps1 index 3b4df435ef..1c28c40d6b 100644 --- a/CI/deploy.ps1 +++ b/CI/deploy.ps1 @@ -13,6 +13,9 @@ Param ( $projectBuildNumber ) +$fd = $false; +$hd = $false; +$fdpr = $false; # Unused at the moment $login = $variables["SecureLogin"] $pass = $variables["SecurePass"] @@ -21,13 +24,33 @@ foreach($artifact in $artifacts.values) Write-Output "Upload artifact: $($artifact.name)" $ext = [System.IO.Path]::GetExtension($artifact.name) $name = [System.IO.Path]::GetFileNameWithoutExtension($artifact.name) - ncftpput.exe -u "$login" -p "$pass" -C ftp.flashdevelop.org "$($artifact.path)" "downloads/builds/$name$ext"; + + IF ($name -like "FlashDevelopPR_*") { $fdpr = $true; } + ELSEIF ($name -like "FlashDevelop*") { $fd = $true; } + ELSEIF ($name -like "HaxeDevelop*") { $hd = $true; } + + IF ($ext -eq ".xml") + { + # Upload appman.xml file + ncftpput.exe -u "$login" -p "$pass" -C ftp.flashdevelop.org "$($artifact.path)" "$name$ext"; + } + ELSE + { + # Upload the installer and the zip archive + ncftpput.exe -u "$login" -p "$pass" -C ftp.flashdevelop.org "$($artifact.path)" "downloads/builds/$name$ext"; + } } -Write-Output "Create and upload LATEST_BUILD.txt" +Write-Output "Create and upload build info." $date = Get-Date $file = [System.IO.Path]::GetTempFileName() -$name = [System.IO.Path]::GetFileNameWithoutExtension($artifact.name) $data = "Build: $projectVersion`r`nTime: " + $date.ToUniversalTime() + " GMT" $data | Set-Content $file -ncftpput.exe -u "$login" -p "$pass" -C ftp.flashdevelop.org "$file" "downloads/builds/$name.txt"; +IF ($fd) +{ + ncftpput.exe -u "$login" -p "$pass" -C ftp.flashdevelop.org "$file" "downloads/builds/FlashDevelop-$env:APPVEYOR_REPO_BRANCH.txt"; +} +IF ($hd) +{ + ncftpput.exe -u "$login" -p "$pass" -C ftp.flashdevelop.org "$file" "downloads/builds/HaxeDevelop-$env:APPVEYOR_REPO_BRANCH.txt"; +} \ No newline at end of file diff --git a/CI/deploya.ps1 b/CI/deploya.ps1 deleted file mode 100644 index 3e8413fbd7..0000000000 --- a/CI/deploya.ps1 +++ /dev/null @@ -1,25 +0,0 @@ -# Deploys the appman.xml config to the FD.org server - -Param ( - $variables = @{}, - $artifacts = @{}, - $scriptPath, - $buildFolder, - $srcFolder, - $outFolder, - $tempFolder, - $projectName, - $projectVersion, - $projectBuildNumber -) - -$login = $variables["SecureLogin"] -$pass = $variables["SecurePass"] - -foreach($artifact in $artifacts.values) -{ - Write-Output "Upload artifact: $($artifact.name)" - $ext = [System.IO.Path]::GetExtension($artifact.name) - $name = [System.IO.Path]::GetFileNameWithoutExtension($artifact.name) - ncftpput.exe -u "$login" -p "$pass" -C ftp.flashdevelop.org "$($artifact.path)" "$name$ext"; -} diff --git a/CI/tests.ps1 b/CI/tests.ps1 new file mode 100644 index 0000000000..047c27f0db --- /dev/null +++ b/CI/tests.ps1 @@ -0,0 +1,57 @@ +# Runs the unit tests, and uploads them to the CI server + +Param ( + $variables = @{}, + $scriptPath, + $buildFolder, + $srcFolder, + $outFolder, + $tempFolder, + $projectName, + $projectVersion, + $projectBuildNumber +) + +If ($env:HAXEPATH -eq $null) +{ + cinst.exe haxe --version 4.1.4 -y --no-progress + $env:HAXEPATH = [System.IO.Directory]::GetDirectories("C:\ProgramData\chocolatey\lib\haxe", "haxe_*")[0]; + If ($env:HAXEPATH -eq $null) + { + Write-Output "HAXEPATH is invalid" + exit 1 + } +} + +If ((Get-Command "nunit3-console.exe" -ErrorAction SilentlyContinue) -ne $null) +{ + $path = [System.IO.Directory]::GetCurrentDirectory() + "\FlashDevelop\Bin\Debug" + $testFiles = [System.IO.Directory]::GetFiles($path, "*.Tests.dll") + IF ($testFiles.Count -eq 0) + { + Write-Output "No test assemblies found" + exit 1 + } + + cd $path + #nunit3-console.exe $testFiles --result=myresults.xml;format=AppVeyor + #nunit3-console.exe $testFiles --x86 + nunit3-console.exe $testFiles + + #It turns out it's not needed to upload the file + #if ((Test-Path env:\APPVEYOR_JOB_ID) -And (Test-Path TestResult.xml)) + #{ + # $wc = New-Object 'System.Net.WebClient' + # $wc.UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path .\TestResult.xml)) + #} + + if ($LASTEXITCODE -ne 0) + { + exit 1 + } +} +ELSE +{ + Write-Output "NUnit runner not found" + exit 1 +} \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000000..d0d8379463 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,208 @@ +# AppMan entries + +If you want to add your plugin, theme or extension to AppMan, you need to do a pull request to the `appman.xml` file adding a new entry inside the FD5 comments. Requirements for the offered plugins, themes or extensions are: + +* Code needs to be open source and reviewable in a public repository +* The item needs to be packaged into a `.fdz` file and provide a MD5 checksum for verification +* The `.fdz` needs to extract the files to the automated plugin directory: `$(BaseDir)/Plugins` + +# Coding style + +##### Use spaces instead of tabs with a width of 4 + +```c# +public bool IsMember() +{ + if (this.value > 2) + { + return false; + } + else return true; +} +``` + +##### Naming should be in English and clear + +```c# +private int memberProperty = 0; +``` + +##### Use camelCase for private members and uppercase for public properties, methods and types: + +```c# +private int memberProperty = 0; + +public string MemberName = "MemberName"; + +public bool IsMember() +{ + return true; +} +``` + +##### Use types without explicit path: + +```c# +private void OnFormActivate(object sender, /*System.*/EventArgs e) +{ + // Do something... +} +``` + +##### Do not use extensive extra empty lines and keep the code clean, not like: + +```c# +// Comment... +private int MemberMethod(int value) +{ + + + + // Comment for something... + + + if (value > 2)) + { + + //this.oldCode = 0; + + + // Random notes here + + + + return -1; + } + + + + // Something here too... + else return value; + + + + + //Little bit here too... +} +``` + +##### Use brackets and parenthesis for easier readability: + +```c# +if ((val1 > val2) && (val1 > val3)) +{ + if (val2 > val3) + { + doThing(); + } +} +``` + +##### Do not nest expressions without brackets: + +```c# +if (val1 > val2 && val1 > val3) + + if (val2 > val3) + + doThing(); + +``` + +##### Use can use one liners to shorten the code: + +```c# +if (val1 > val2 && val1 > val3) +{ + if (val2 > val3) doThing(); +} +``` + +##### Use explicit types: + +```c# +int myValue = 0; +Point[] myPoints = new Point[] +{ + new Point(1, 1), + new Point(2, 2) +} +``` + +##### Code example: + +```c# +using System; + +namespace MyNameSpace +{ + class MyClass + { + // Comment here... + private int memberProperty = 0; + private int memberProperty2 = 1; + private int memberProperty3 = 2; + + // Comment here... + public string MemberName = "MemberName"; + + // Comment here... + public static bool IsMemberProperty = false; + + // Comment here... + public const int CONSTANT = 1; + + /// + /// Comment here... + /// + public bool IsMember() + { + return true; + } + + /// + /// Comment here... + /// + public void MemberMethod(int value) + { + int temp = CONSTANT; + if (value > 2) + { + this.memberProperty2 = temp; + this.memberProperty3 = temp; + } + else this.memberProperty3 = value; + } + + /// + /// Comment here... + /// + private int MemberMethodEx(int value) + { + int temp = CONSTANT; + this.memberProperty3 = temp; + switch (value) + { + case 1: return 1; + case 2: + { + return -1; + } + default: return value; + } + } + + /// + /// Comment here... + /// + private void OnFormActivate(object sender, EventArgs e) + { + this.MemberMethod(null, null); + } + + } + +} +``` + +##### More generally, be consistent and keep the code clean! diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Docs/index.html b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Docs/index.html new file mode 100644 index 0000000000..40c76b8a41 --- /dev/null +++ b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Docs/index.html @@ -0,0 +1,73 @@ + + + + HaxeDevelop + + + + + + +
+
+ +

Description

+

HaxeDevelop is a highly customizable lightweight script editor with extended support for class + based languages. Altought the program is designed mostly for Haxe, other languages can + be implemented quite easily too. HaxeDevelop requires the Microsoft.NET 4.0 Framework. You can support us by + donating for the project via PayPal. Any donation, even 1$, is good for the project. Code contributions are also welcome.

+

You can find more info about HaxeDevelop from the project website haxedevelop.org. + +

HaxeDevelop is a custom distribution of FlashDevelop.

+ +

Used Icons

+

Current smooth HaxeDevelop icons are free icons downloaded from + famfamfam.com, visualfarm.com and fatcow.com. + The icons are released under Creative Commons Attribution 2.5 and 3 Licenses. Some of the used icons are modified from the original ones.

+ +

Used Tools

+

HaxeDevelop includes few third party tools by default. The listed tools are copyright of their respective owners.

+ + +

Components

+

HaxeDevelop is programmed with C# and it includes misc. modified and unmodified components. DockPanel + Suite is used for docking windows and ScintillaNET wrapper is used for providing the Scintilla editor control for C#. + The listed components are copyright of their respective owners.

+ + +

Licence

+

Copyright (c) 2018 Haxe Foundation - HaxeDevelop.org

+

Portions copyright Mika Palmu, Philippe Elsass and all helpful contributors.

+

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and + to permit persons to whom the Software is furnished to do so, subject to the following conditions:

+

The above copyright notice and this permission notice shall be included in all copies or portions of the Software.

+

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED + TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+
+
+ + + + diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Docs/styles.css b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Docs/styles.css new file mode 100644 index 0000000000..f858f058a1 --- /dev/null +++ b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Docs/styles.css @@ -0,0 +1,65 @@ +body, html +{ + font-size:14px; + font-family:"Segoe UI", "Trebuchet MS", Georgia, Arial, sans-serif; + padding:0; + margin:0; +} +h4 +{ + font-size: 24px; +} +ul +{ + margin: 0px; + padding: 0px; + margin-left: 3px; +} +a +{ + color:#257fc2; + text-decoration:none; +} + +a:hover +{ + color:#257fc2; + text-decoration:underline; +} +#header +{ + width: 100%; + text-align:center; + background:#257fc2 url('../StartPage/images/pattern.png') center top; + margin:0; +} +#header h3 +{ + color: #eea21a; +} +#header h3 img +{ + margin-right: 5px; + margin-bottom: -3px; +} +.innerContent +{ + padding: 20px; +} +#content +{ + width: 100%; +} +#content ul +{ + padding: 5px; + padding-bottom: 0px; + padding-left: 15px; +} +#footer +{ + width: 100%; + border-top: 1px dotted grey; + padding-top: 11px; + margin-top: 11px; +} diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/images/haxedevelop.gif b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/images/haxedevelop.gif new file mode 100644 index 0000000000..81189df9a9 Binary files /dev/null and b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/images/haxedevelop.gif differ diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/images/pattern.png b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/images/pattern.png new file mode 100644 index 0000000000..ff5ee01a4f Binary files /dev/null and b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/images/pattern.png differ diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/index.html b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/index.html new file mode 100644 index 0000000000..a8c2d25d1c --- /dev/null +++ b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/index.html @@ -0,0 +1,71 @@ + + + + Start Page + + + + + + + +
+
+
+ + +
+ +
+
+

+ +

+ + + +
+

+
+ +
+
+ +
+
+ +
+
+
+ +
+
+
+ +
+
+
+

+
+ +
+
+
+
+ + + + diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/javascript/startpage.js b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/javascript/startpage.js new file mode 100644 index 0000000000..686ad54df1 --- /dev/null +++ b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/javascript/startpage.js @@ -0,0 +1,197 @@ +/** +* Templates used by the start page. +*/ +var rssFeedItemTemplate = "

{0}

{2}"; +var projectItemTemplate = "
  • {0}
  • "; +var tooltipTextTemplate = "{0}
    " + getLocaleString("tooltipTextType") + " {1}
    " + getLocaleString("tooltipTextCreated") + " {2}
    " + getLocaleString("tooltipTextModified") + " {3}"; +var versionAvailableTemplate = ""; +var versionOutOfDateTemplate = "

    " + getLocaleString("yourVersionIsOutOfDate") + "

    "; +var versionNotAvailableTemplate = "

    " + getLocaleString("versionInfoNotAvailable") + "

    "; + +/** +* Parses XML document from string. +*/ +function parseXmlDocument(xml) +{ + var parser = new ActiveXObject("Microsoft.XMLDOM"); + parser.async = "false"; + parser.loadXML(xml); + return parser; +} + +/** +* Downloads text document from url. +*/ +function loadTextDocument(url, callback) +{ + var loader = new ActiveXObject("Microsoft.XMLHTTP"); + loader.onreadystatechange = function() + { + if (loader.readyState == 4) + { + callback(loader.responseText, loader.status); + } + }; + loader.open("GET", url, true); + loader.send(null); +} + +/** +* Parses the recent project xml document. +*/ +function handleProjectXml(xml) +{ + var html = ""; + var projects = new Array(); + var nodes = xml.getElementsByTagName("RecentProject"); + if (nodes.length === 0) html = getLocaleString("recentProjectsNotFound"); + for (var i = 0; i < nodes.length; i++) + { + var name = getNodeText(nodes[i].getElementsByTagName("Name")); + var type = getNodeText(nodes[i].getElementsByTagName("Type")); + var path = getNodeText(nodes[i].getElementsByTagName("Path")).replace(/\\/g, "\\\\"); + var created = getNodeText(nodes[i].getElementsByTagName("Created")); + var modified = getNodeText(nodes[i].getElementsByTagName("Modified")); + var typeDesc = getProjectType(type); // Description of project file type... + html += formatString(projectItemTemplate, name, addSlashes(path), typeDesc); + } + var element = document.getElementById("projectsContent"); + element.innerHTML = ""; +} + +function addSlashes(s) +{ + return s.split("'").join("\\'"); +} + +/** +* Parses the rss feed xml document. +*/ +function handleRssFeedXml(text, status) +{ + var html = ""; + var xml = parseXmlDocument(text); + if (status == 200) + { + var items = new Array(); + var xmlItems = xml.getElementsByTagName("item"); + var xmlTitle = getNodeText(xml.getElementsByTagName("title")); + document.getElementById("rssTitle").innerHTML = xmlTitle; + for (var i = 0; i < xmlItems.length; i++) + { + var title = getNodeText(xmlItems[i].getElementsByTagName("title")); + var link = getNodeText(xmlItems[i].getElementsByTagName("link")).replace(/\\/g, "\\\\"); + var desc = getNodeText(xmlItems[i].getElementsByTagName("description")); + html += formatString(rssFeedItemTemplate, title, link, desc); + //if (i != xmlItems.length - 1) html += "
    "; + } + } + else + { + html = getLocaleString("rssFeedNotAvailable"); + } + var element = document.getElementById("rssContent"); + element.innerHTML = html; +} + +/** +* Safe text extraction +*/ +function getNodeText(nodes) +{ + if (nodes == null) return ""; //"#ERR#1"; + if (nodes.length == 0) return ""; //"#ERR#2"; + if (nodes[0].firstChild == null) return ""; //"#ERR#3"; + return nodes[0].firstChild.nodeValue; +} + +/** +* Handles the downloaded version info. +*/ +function handleVersionInfo(text, status) +{ + var html = ""; + if (status == 200) + { + var info = text.split(/[\r\n]+/g); + var version = decodeURIComponent(getUrlParameter("v")); + html = formatString(versionAvailableTemplate, info[0], info[1]); + if (version && ((info[0] < version) - (version < info[0])) == -1) + { + html += formatString(versionOutOfDateTemplate, version); + } + } + else html = versionNotAvailableTemplate; + var element = document.getElementById("versionContent"); + element.innerHTML = html; +} + +/** +* Gets the localized text for the id. +*/ +function getLocaleString(id) +{ + var lang = getUrlParameter("l") || "en_US"; + return locale[lang + "." + id] || id; +} + +/** +* Gets the type of the project file. +*/ +function getProjectType(extension) +{ + switch (extension) + { + case ".fdp" : return getLocaleString("projectTypeFDP"); + case ".as2proj" : return getLocaleString("projectTypeAS2"); + case ".as3proj" : return getLocaleString("projectTypeAS3"); + case ".fdproj" : return getLocaleString("projectTypeGeneric"); + case ".hxproj" : return getLocaleString("projectTypeHaxe"); + case ".lsproj" : return getLocaleString("projectTypeLoom"); + default : return getLocaleString("projectTypeUnknown"); + } +} + +/** +* Gets the value of the specified url parameter. +*/ +function getUrlParameter(id) +{ + id = id.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]"); + var regex = new RegExp("[?&]" + id + "=([^&#]*)"); + var results = regex.exec(unescape(window.location.href)); + if (results == null) return ""; + else return results[1]; +} + +/** +* Formats the string with the specified arguments. +*/ +function formatString(text) +{ + var result = text; + for (var i = 1; i < arguments.length; i++) + { + var pattern = "{" + (i - 1) + "}"; + while (result.indexOf(pattern) >= 0) + { + result = result.replace(pattern, arguments[i]); + } + } + return result; +} + +/** +* Handles the data sent by FlashDevelop. +*/ +function handleXmlData(projectXml, rssUrl) +{ + if (rssUrl != null) + { + var hdUrl = "https://haxedevelop.org/latest.txt"; + loadTextDocument(hdUrl, handleVersionInfo); + loadTextDocument(rssUrl, handleRssFeedXml); + } + var xml = parseXmlDocument(projectXml); + handleProjectXml(xml); +} diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/styles.css b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/styles.css new file mode 100644 index 0000000000..290883eea3 --- /dev/null +++ b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/StartPage/styles.css @@ -0,0 +1,239 @@ +html,body +{ + width:100%; + height:100%; +} + +body +{ + background:#257fc2 url(images/pattern.png) center top; + font-size:14px; + font-family:"Segoe UI", "Trebuchet MS", Georgia, Arial, sans-serif; + color:#fff; + box-shadow:inset 0 0 50px rgba(0,0,0,0.35); + margin:0; + padding:0; +} + +.clearfix:after { + visibility: hidden; + display: block; + font-size: 0; + content: " "; + clear: both; + height: 0; +} + +* html .clearfix { zoom: 1; } /* IE6 */ +*:first-child+html .clearfix { zoom: 1; } /* IE7 */ + +h1,h2,h3 +{ + border-bottom:1px dashed rgba(255,255,255,.5); + font-weight:400; + padding:10px; + margin:0 0 0 0; +} + +#header +{ + text-align:center; +} + +#links +{ + background:#333; + padding:10px; + text-align:right; +} + +#links a +{ + color:#fff; + font:normal 14px "Segoe UI", arial, sans-serif; + margin-right:5px; +} + +#news +{ + background:#fbfbfb; + color:#333; +} + +.button +{ + font-size:14px; + display:inline-block; + margin-right:5px; + margin-bottom:5px; + border-radius:3px; + text-decoration:none; + padding:7px 7px; +} +#projects .button { + width:48%; +} + +#version .button { + width:99%; +} + +img,a img +{ + border:none; + outline:none; +} + +a +{ + color:#ff9; + text-decoration:none; + display:inline-block; +} + +a:hover +{ + color:#ee6; + text-decoration:underline; +} + +div#tooltip +{ + top:0; + left:0; + z-index:2; + visibility:hidden; + position:absolute; + background-color:#333; + border:1px solid #999; + padding:4px 7px 3px; + color:#fff; + font-size:14px; +} + +table#holder +{ + text-align:left; + position:absolute; + width:100%; + top:115px; + padding:1px; +} + +td.holderSpacer +{ + width:15px; +} + +td.smallWindowHolder +{ + width:280px; +} + +div#tasksContent +{ + padding-bottom:10px; + padding-left:5px; +} + +#projectsContent li +{ + background:#257fc2 url(images/iconProject.gif) no-repeat 9px center; + display:block; + padding: 5px 5px 5px 32px; + margin-bottom:2px; + border:1px solid #7db3db; + border-radius:3px; + cursor:pointer; +} +#projectsContent li:hover { + background-color:#333; + border:1px solid #b2d1e8; +} + +#rssContent li +{ + margin:0; + padding:0; +} + +.rssItemTitle +{ + display:block; +} + +.rssItemContent +{ + color:#111; +} + +.rssItemContent a +{ + font-weight:700; +} + +#rssContent a +{ + color:#257fc2; + text-decoration:none; +} + +#rssContent a:hover +{ + color:#257fc2; + text-decoration:underline; +} + + +#social a:hover img +{ + opacity:.8; +} + +.greyedOut +{ + color:#ccc; +} + +.alertRed +{ + color:red; +} + +.section-gray +{ + background:#141419; + background:#257fc2 url(images/pattern.png) center top; +} + +#header +{ + width:33%; +} + +#projects +{ + width:33%; +} + +#projectslist +{ + width:33%; +} + +#projectslist, #projects, #header +{ + float:left; +} + +.innerContent +{ + padding:20px 10px 20px 20px; +} + +div#projectsContent ul,li,div#rssContent ul,li +{ + list-style-type:none; + margin:0; + padding:0; +} \ No newline at end of file diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Tools/appman/Config.xml b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Tools/appman/Config.xml new file mode 100644 index 0000000000..d21e43be5f --- /dev/null +++ b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Tools/appman/Config.xml @@ -0,0 +1,19 @@ + + + + HaxeDevelop + + FD5,HD5,Haxelib + + $(BaseDir)\Apps + + http://www.flashdevelop.org/appman.xml + + http://www.flashdevelop.org/wikidocs/ + + $(BaseDir) + + $(BaseDir)\Data\AppMan + + en_US + \ No newline at end of file diff --git a/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Tools/winres/winres.exe b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Tools/winres/winres.exe new file mode 100755 index 0000000000..21f3476540 Binary files /dev/null and b/Distros/HaxeDevelop/FlashDevelop/Bin/Debug/Tools/winres/winres.exe differ diff --git a/Distros/HaxeDevelop/FlashDevelop/Installer/Config.nsh b/Distros/HaxeDevelop/FlashDevelop/Installer/Config.nsh new file mode 100644 index 0000000000..2f2f8b634e --- /dev/null +++ b/Distros/HaxeDevelop/FlashDevelop/Installer/Config.nsh @@ -0,0 +1,7 @@ +; Define distro config +!define DIST_NAME "HaxeDevelop" +!define DIST_COMP "HaxeDevelop.org" +!define DIST_COPY "HaxeDevelop.org 2005-2018" +!define DIST_README "http://haxedevelop.org" +!define DIST_COMMUNITY "https://haxedevelop.org/blog/" +!define DIST_DOCS "https://haxedevelop.org"; diff --git a/Distros/HaxeDevelop/FlashDevelop/Installer/Graphics/Banner.bmp b/Distros/HaxeDevelop/FlashDevelop/Installer/Graphics/Banner.bmp new file mode 100644 index 0000000000..9c56ddcbb2 Binary files /dev/null and b/Distros/HaxeDevelop/FlashDevelop/Installer/Graphics/Banner.bmp differ diff --git a/Distros/HaxeDevelop/FlashDevelop/Installer/Graphics/Wizard.bmp b/Distros/HaxeDevelop/FlashDevelop/Installer/Graphics/Wizard.bmp new file mode 100644 index 0000000000..1c0bb2dd15 Binary files /dev/null and b/Distros/HaxeDevelop/FlashDevelop/Installer/Graphics/Wizard.bmp differ diff --git a/Distros/HaxeDevelop/FlashDevelop/Resources/AboutDialog.jpg b/Distros/HaxeDevelop/FlashDevelop/Resources/AboutDialog.jpg new file mode 100644 index 0000000000..04ed513e42 Binary files /dev/null and b/Distros/HaxeDevelop/FlashDevelop/Resources/AboutDialog.jpg differ diff --git a/Distros/HaxeDevelop/FlashDevelop/Resources/FlashDevelopIcon.ico b/Distros/HaxeDevelop/FlashDevelop/Resources/FlashDevelopIcon.ico new file mode 100644 index 0000000000..d019c1e5c8 Binary files /dev/null and b/Distros/HaxeDevelop/FlashDevelop/Resources/FlashDevelopIcon.ico differ diff --git a/Distros/HaxeDevelop/PluginCore/PluginCore/DistroConfig.cs b/Distros/HaxeDevelop/PluginCore/PluginCore/DistroConfig.cs new file mode 100644 index 0000000000..5cd871dd5e --- /dev/null +++ b/Distros/HaxeDevelop/PluginCore/PluginCore/DistroConfig.cs @@ -0,0 +1,20 @@ +using System; + +namespace PluginCore +{ + public class DistroConfig + { + public const string DISTRIBUTION_NAME = "HaxeDevelop"; + public const string DISTRIBUTION_DESC = "HaxeDevelop is an open source script editor."; + public const string DISTRIBUTION_HOME = "https://haxedevelop.org/"; + public const string DISTRIBUTION_HELP = "https://haxedevelop.org/system-requirements.html"; + public const string DISTRIBUTION_VERSION = "https://haxedevelop.org/latest.txt"; + public const string DISTRIBUTION_ABOUT = "HaxeDevelop logo, domain and the name are copyright of Haxe Foundation.\r\nHaxeDevelop is a custom distribution of FlashDevelop.\r\nDevelopment: Mika Palmu, Philippe Elsass and all helpful contributors."; + public const string DISTRIBUTION_COPYRIGHT = "HaxeDevelop.org 2015-2020"; + public const string DISTRIBUTION_COMPANY = "HaxeDevelop.org"; + public const string DISTRIBUTION_RSS = "https://haxedevelop.org/rss.xml"; + public const string DISTRIBUTION_EXT = "hx"; + public const string DISTRIBUTION_DEV_VERSION = "https://flashdevelop.org/downloads/builds/HaxeDevelop-development.txt"; + public const string DISTRIBUTION_DEV_BUILD = "https://flashdevelop.org/downloads/builds/HaxeDevelop-development.exe"; + } +} \ No newline at end of file diff --git a/Distros/README.md b/Distros/README.md new file mode 100644 index 0000000000..5287a78ecd --- /dev/null +++ b/Distros/README.md @@ -0,0 +1,7 @@ +# FlashDevelop distros + +## Haxedevelop + +HaxeDevelop a custom distribution of FlashDevelop where editor configuration is focussed on [Haxe](https://haxe.org/). + +* More info: diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Aga.Controls.csproj b/External/3rdParty/Aga-1.7/Aga.Controls/Aga.Controls.csproj index 614dde903c..de5b13bbf6 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Aga.Controls.csproj +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Aga.Controls.csproj @@ -1,10 +1,8 @@  - + Debug AnyCPU - 9.0.21022 - 2.0 {E73BB233-D88B-44A7-A98F-D71EE158381D} Library Properties @@ -22,25 +20,14 @@ key.snk - 3.5 - v2.0 - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true + net48 + true + false + false + false + true @@ -104,6 +91,9 @@ + + + @@ -238,7 +228,6 @@ TreeViewAdv.cs - Designer @@ -250,29 +239,4 @@ - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - \ No newline at end of file diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Properties/AssemblyInfo.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Properties/AssemblyInfo.cs index 34f94db926..d7205aee26 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Properties/AssemblyInfo.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Properties/AssemblyInfo.cs @@ -12,4 +12,4 @@ [assembly: AssemblyCopyright("Copyright © Andrey Gliznetsov 2006 - 2009")] [assembly: AssemblyDescription("http://sourceforge.net/projects/treeviewadv/")] -[assembly: AssemblyVersion("1.7.0.0")] +[assembly: AssemblyVersion("1.7.0.1")] diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Properties/Resources.Designer.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Properties/Resources.Designer.cs index 1968ffbfbf..cbfdbd0b10 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Properties/Resources.Designer.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Properties/Resources.Designer.cs @@ -1,7 +1,7 @@ //------------------------------------------------------------------------------ // // This code was generated by a tool. -// Runtime Version:4.0.30319.296 +// Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -60,6 +60,9 @@ internal Resources() { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// internal static System.Drawing.Bitmap check { get { object obj = ResourceManager.GetObject("check", resourceCulture); @@ -67,6 +70,9 @@ internal static System.Drawing.Bitmap check { } } + /// + /// Looks up a localized resource of type System.Byte[]. + /// internal static byte[] DVSplit { get { object obj = ResourceManager.GetObject("DVSplit", resourceCulture); @@ -74,6 +80,9 @@ internal static byte[] DVSplit { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// internal static System.Drawing.Bitmap Folder { get { object obj = ResourceManager.GetObject("Folder", resourceCulture); @@ -81,6 +90,9 @@ internal static System.Drawing.Bitmap Folder { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// internal static System.Drawing.Bitmap FolderClosed { get { object obj = ResourceManager.GetObject("FolderClosed", resourceCulture); @@ -88,6 +100,9 @@ internal static System.Drawing.Bitmap FolderClosed { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// internal static System.Drawing.Bitmap Leaf { get { object obj = ResourceManager.GetObject("Leaf", resourceCulture); @@ -95,6 +110,9 @@ internal static System.Drawing.Bitmap Leaf { } } + /// + /// Looks up a localized resource of type System.Byte[]. + /// internal static byte[] loading_icon { get { object obj = ResourceManager.GetObject("loading_icon", resourceCulture); @@ -102,6 +120,9 @@ internal static byte[] loading_icon { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// internal static System.Drawing.Bitmap minus { get { object obj = ResourceManager.GetObject("minus", resourceCulture); @@ -109,6 +130,9 @@ internal static System.Drawing.Bitmap minus { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// internal static System.Drawing.Bitmap plus { get { object obj = ResourceManager.GetObject("plus", resourceCulture); @@ -116,6 +140,9 @@ internal static System.Drawing.Bitmap plus { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// internal static System.Drawing.Bitmap uncheck { get { object obj = ResourceManager.GetObject("uncheck", resourceCulture); @@ -123,6 +150,9 @@ internal static System.Drawing.Bitmap uncheck { } } + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// internal static System.Drawing.Bitmap unknown { get { object obj = ResourceManager.GetObject("unknown", resourceCulture); diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Threading/AbortableThreadPool.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Threading/AbortableThreadPool.cs index 5424e8974d..24a77c7e10 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Threading/AbortableThreadPool.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Threading/AbortableThreadPool.cs @@ -111,6 +111,7 @@ public void CancelAll(bool allowAbort) { foreach (Thread t in _threads.Values) t.Abort(); + _threads.Clear(); } } } diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/AutoHeaderHeightLayout.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/AutoHeaderHeightLayout.cs new file mode 100644 index 0000000000..0cebc0c831 --- /dev/null +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/AutoHeaderHeightLayout.cs @@ -0,0 +1,64 @@ +using System; +using System.ComponentModel; +using System.Windows.Forms; + +namespace Aga.Controls.Tree +{ + using System.Drawing; + + public class AutoHeaderHeightLayout : IHeaderLayout + { + DrawContext _measureContext; + TreeViewAdv _treeView; + + public AutoHeaderHeightLayout(TreeViewAdv treeView, int headerHeight) + { + _treeView = treeView; + PreferredHeaderHeight = headerHeight; + _measureContext = new DrawContext(); + _measureContext.Graphics = Graphics.FromImage(new Bitmap(1, 1)); + } + + int? _headerHeight; + + bool _computed; + + #region Implementation of IHeaderLayout + + public int PreferredHeaderHeight + { + get { return GetHeaderHeight(); } + set + { + _headerHeight = value; + _computed = false; + } + } + + public void ClearCache() + { + _computed = false; + } + + int GetHeaderHeight() + { + if (!_computed) + { + int res = 0; + _measureContext.Font = _treeView.Font; + foreach (TreeColumn nc in _treeView.Columns) + { + int h = nc.GetActualSize(_measureContext).Height; + if (h > res) res = h; + } + _headerHeight = res; + + _computed = true; + } + + return _headerHeight.Value; + } + + #endregion + } +} diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/AutoRowHeightLayout.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/AutoRowHeightLayout.cs index 953df024e4..8b8d7e4cdc 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/AutoRowHeightLayout.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/AutoRowHeightLayout.cs @@ -37,7 +37,7 @@ public int PageRowCount return 0; else { - int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; + int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ActualColumnHeaderHeight; int y = 0; for (int i = _treeView.RowCount - 1; i >= 0; i--) { @@ -58,7 +58,7 @@ public int CurrentPageSize return 0; else { - int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; + int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ActualColumnHeaderHeight; int y = 0; for (int i = _treeView.FirstVisibleRow; i < _treeView.RowCount; i++) { @@ -117,7 +117,7 @@ private int GetRowHeight(int rowNo) public int GetRowAt(Point point) { - int py = point.Y - _treeView.ColumnHeaderHeight; + int py = point.Y - _treeView.ActualColumnHeaderHeight; int y = 0; for (int i = _treeView.FirstVisibleRow; i < _treeView.RowCount; i++) { @@ -132,7 +132,7 @@ public int GetRowAt(Point point) public int GetFirstRow(int lastPageRow) { - int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight; + int pageHeight = _treeView.DisplayRectangle.Height - _treeView.ActualColumnHeaderHeight; int y = 0; for (int i = lastPageRow; i >= 0; i--) { diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Enums.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Enums.cs index 3a83e9a7cf..abf52168af 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Enums.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Enums.cs @@ -4,6 +4,12 @@ namespace Aga.Controls.Tree { + + public enum BackgroundPaintMode + { + Default,Gradiant + } + public enum DrawSelectionMode { None, Active, Inactive, FullRowSelect diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/FixedHeaderHeightLayout.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/FixedHeaderHeightLayout.cs new file mode 100644 index 0000000000..6f557d852d --- /dev/null +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/FixedHeaderHeightLayout.cs @@ -0,0 +1,28 @@ +namespace Aga.Controls.Tree +{ + class FixedHeaderHeightLayout : IHeaderLayout + { + TreeViewAdv _treeView; + int _headerHeight; + + public FixedHeaderHeightLayout(TreeViewAdv treeView, int headerHeight) + { + _treeView = treeView; + PreferredHeaderHeight = headerHeight; + } + + #region Implementation of IHeaderLayout + + public int PreferredHeaderHeight + { + get { return _headerHeight; } + set { _headerHeight = value; } + } + + public void ClearCache() + { + } + + #endregion + } +} diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/FixedRowHeightLayout.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/FixedRowHeightLayout.cs index 316b3dc7d5..3fdc399564 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/FixedRowHeightLayout.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/FixedRowHeightLayout.cs @@ -31,7 +31,7 @@ public int PageRowCount { get { - return Math.Max((_treeView.DisplayRectangle.Height - _treeView.ColumnHeaderHeight) / _rowHeight, 0); + return Math.Max((_treeView.DisplayRectangle.Height - _treeView.ActualColumnHeaderHeight) / _rowHeight, 0); } } @@ -45,7 +45,7 @@ public int CurrentPageSize public int GetRowAt(Point point) { - point = new Point(point.X, point.Y + (_treeView.FirstVisibleRow * _rowHeight) - _treeView.ColumnHeaderHeight); + point = new Point(point.X, point.Y + (_treeView.FirstVisibleRow * _rowHeight) - _treeView.ActualColumnHeaderHeight); return point.Y / _rowHeight; } diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/IHeaderLayout.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/IHeaderLayout.cs new file mode 100644 index 0000000000..9289762d3c --- /dev/null +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/IHeaderLayout.cs @@ -0,0 +1,13 @@ +namespace Aga.Controls.Tree +{ + internal interface IHeaderLayout + { + int PreferredHeaderHeight + { + get; + set; + } + + void ClearCache(); + } +} diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Input/ReorderColumnState.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Input/ReorderColumnState.cs index 181cca51b3..0fc3bd2743 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Input/ReorderColumnState.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Input/ReorderColumnState.cs @@ -41,7 +41,7 @@ public ReorderColumnState(TreeViewAdv tree, TreeColumn column, Point initialMous { _location = new Point(initialMouseLocation.X + Tree.OffsetX, 0); _dragOffset = tree.GetColumnX(column) - initialMouseLocation.X; - _ghostImage = column.CreateGhostImage(new Rectangle(0, 0, column.Width, tree.ColumnHeaderHeight), tree.Font); + _ghostImage = column.CreateGhostImage(new Rectangle(0, 0, column.Width, tree.ActualColumnHeaderHeight), tree.Font, tree.ForeColor); } public override void KeyDown(KeyEventArgs args) diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Input/ResizeColumnState.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Input/ResizeColumnState.cs index e4d8653f60..87ad05b555 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Input/ResizeColumnState.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/Input/ResizeColumnState.cs @@ -40,6 +40,7 @@ private void FinishResize() Tree.ChangeInput(); Tree.FullUpdate(); Tree.OnColumnWidthChanged(Column); + Tree.OnColumnHeightChanged(Column); } public override bool MouseMove(MouseEventArgs args) diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/BaseTextControl.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/BaseTextControl.cs index cbe36a2ad7..d94a74e561 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/BaseTextControl.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/BaseTextControl.cs @@ -128,7 +128,7 @@ protected Size GetLabelSize(TreeNodeAdv node, DrawContext context, string label) CheckThread(); Font font = GetDrawingFont(node, context, label); Size s = Size.Empty; - if (UseCompatibleTextRendering) + if (!UseCompatibleTextRendering) s = TextRenderer.MeasureText(label, font); else { @@ -170,18 +170,16 @@ public override void Draw(TreeNodeAdv node, DrawContext context) return; PerformanceAnalyzer.Start("BaseTextControl.Draw"); - string label = GetLabel(node); + Rectangle bounds = GetBounds(node, context); Rectangle focusRect = new Rectangle(bounds.X, context.Bounds.Y, bounds.Width, context.Bounds.Height); + + DrawEventArgs args; + CreateBrushes(node, context, out args); - Brush backgroundBrush; - Color textColor; - Font font; - CreateBrushes(node, context, label, out backgroundBrush, out textColor, out font, ref label); - - if (backgroundBrush != null) - context.Graphics.FillRectangle(backgroundBrush, focusRect); + if (args.BackgroundBrush != null) + context.Graphics.FillRectangle(args.BackgroundBrush, focusRect); if (context.DrawFocus) { focusRect.Width--; @@ -194,15 +192,50 @@ public override void Draw(TreeNodeAdv node, DrawContext context) } PerformanceAnalyzer.Start("BaseTextControl.DrawText"); - if (UseCompatibleTextRendering) - TextRenderer.DrawText(context.Graphics, label, font, bounds, textColor, _formatFlags); - else - context.Graphics.DrawString(label, font, GetFrush(textColor), bounds, _format); - PerformanceAnalyzer.Finish("BaseTextControl.DrawText"); + + DrawHighLight(context, bounds, args); + + if (!UseCompatibleTextRendering) + TextRenderer.DrawText(context.Graphics, args.Text, args.Font, bounds, args.TextColor, _formatFlags); + else + context.Graphics.DrawString(args.Text, args.Font, GetFrush(args.TextColor), bounds, _format); + + PerformanceAnalyzer.Finish("BaseTextControl.DrawText"); PerformanceAnalyzer.Finish("BaseTextControl.Draw"); } + private void DrawHighLight(DrawContext context, Rectangle bounds, DrawEventArgs args) + { + string label = args.Text; + if (!String.IsNullOrEmpty(args.HighLightToken) && label.ToLower().Contains(args.HighLightToken.ToLower())) + { + Graphics g = context.Graphics; + int numChars = label.Length; + CharacterRange[] characterRanges = new CharacterRange[1]; + int idx = label.ToLower().IndexOf(args.HighLightToken.ToLower()); + //Get the max width.. for the complete length + SizeF size = g.MeasureString(label, args.Font); + + //Assume the string is in a stratight line, just to work out the + //regions. We will adjust the containing rectangles later. + RectangleF layoutRect = + new RectangleF(0.0f, 0.0f, size.Width, size.Height); + + // + // Set up the array to accept the regions. + Region[] stringRegions = new Region[numChars]; + for (int i = 0; i < 1; i++) + characterRanges[i] = new CharacterRange(idx, args.HighLightToken.Length); + + _format.SetMeasurableCharacterRanges(characterRanges); + + stringRegions = context.Graphics.MeasureCharacterRanges(label, args.Font, bounds, _format); + RectangleF highLightedBounds = stringRegions[0].GetBounds(g); + g.FillRectangle(GetFrush(args.HighLightColor), Rectangle.Round(highLightedBounds)); + } + } + private static Dictionary _brushes = new Dictionary(); private static Brush GetFrush(Color color) { @@ -217,42 +250,30 @@ private static Brush GetFrush(Color color) return br; } - private void CreateBrushes(TreeNodeAdv node, DrawContext context, string text, out Brush backgroundBrush, out Color textColor, out Font font, ref string label) + private void CreateBrushes(TreeNodeAdv node, DrawContext context, out DrawEventArgs args) { - textColor = SystemColors.ControlText; - backgroundBrush = null; - font = context.Font; + args = new DrawEventArgs(node, this, context, GetLabel(node)); + args.TextColor = SystemColors.ControlText; + args.BackgroundBrush = null; + args.Font = context.Font; if (context.DrawSelection == DrawSelectionMode.Active) { - textColor = SystemColors.HighlightText; - backgroundBrush = SystemBrushes.Highlight; + args.TextColor = SystemColors.HighlightText; + args.BackgroundBrush = Parent._highlightColorActiveBrush; } else if (context.DrawSelection == DrawSelectionMode.Inactive) { - textColor = SystemColors.ControlText; - backgroundBrush = SystemBrushes.InactiveBorder; + args.TextColor = SystemColors.ControlText; + args.BackgroundBrush = Parent._highlightColorInactiveBrush; } else if (context.DrawSelection == DrawSelectionMode.FullRowSelect) - textColor = SystemColors.HighlightText; + args.TextColor = SystemColors.HighlightText; if (!context.Enabled) - textColor = SystemColors.GrayText; + args.TextColor = SystemColors.GrayText; if (DrawTextMustBeFired(node)) - { - DrawEventArgs args = new DrawEventArgs(node, this, context, text); - args.Text = label; - args.TextColor = textColor; - args.BackgroundBrush = backgroundBrush; - args.Font = font; - - OnDrawText(args); - - textColor = args.TextColor; - backgroundBrush = args.BackgroundBrush; - font = args.Font; - label = args.Text; - } + OnDrawText(args); } public string GetLabel(TreeNodeAdv node) diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs index 8333c1f24c..a54788f551 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/DrawEventArgs.cs @@ -56,6 +56,22 @@ public EditableControl Control get { return _control; } } + private string _highLightToken; + + public string HighLightToken + { + get { return _highLightToken; } + set { _highLightToken = value; } + } + + private Color _highLightColor = Color.Yellow; + public Color HighLightColor + { + get { return _highLightColor; } + set { _highLightColor = value; } + } + + public DrawEventArgs(TreeNodeAdv node, EditableControl control, DrawContext context, string text) : base(node) { diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs index bd2c34cd2e..fecc124aef 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/ExpandingIcon.cs @@ -64,10 +64,13 @@ private static void IterateIcons() { while (_animatingThread != null) { - if (_index < _gif.FrameCount - 1) - _index++; - else - _index = 0; + lock (_lock) + { + if (_index < _gif.FrameCount - 1) + _index++; + else + _index = 0; + } if (IconChanged != null) IconChanged(null, EventArgs.Empty); diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs index d0aec6459d..de4c1ebe1c 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/NodeCheckBox.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Drawing; using Aga.Controls.Properties; -using System.Reflection; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; using System.ComponentModel; @@ -28,6 +25,18 @@ public bool ThreeState set { _threeState = value; } } + bool _reverseCheckOrder; + /// + /// Reverses the Order. + /// From Indeterminate, Unchecked, Checked to Indeterminate, Checked, Unchecked. + /// + [DefaultValue(false)] + public bool ReverseCheckOrder + { + get { return _reverseCheckOrder; } + set { _reverseCheckOrder = value; } + } + #endregion public NodeCheckBox() @@ -134,14 +143,26 @@ public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args) args.Handled = true; } - private CheckState GetNewState(CheckState state) + protected virtual CheckState GetNewState(CheckState state) { - if (state == CheckState.Indeterminate) - return CheckState.Unchecked; - else if(state == CheckState.Unchecked) - return CheckState.Checked; - else - return ThreeState ? CheckState.Indeterminate : CheckState.Unchecked; + if (ReverseCheckOrder) + { + if (state == CheckState.Indeterminate) + return CheckState.Checked; + else if (state == CheckState.Checked) + return CheckState.Unchecked; + else + return ThreeState ? CheckState.Indeterminate : CheckState.Checked; + } + else + { + if (state == CheckState.Indeterminate) + return CheckState.Unchecked; + else if (state == CheckState.Unchecked) + return CheckState.Checked; + else + return ThreeState ? CheckState.Indeterminate : CheckState.Unchecked; + } } public override void KeyDown(KeyEventArgs args) diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/NodeTextBox.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/NodeTextBox.cs index 81065d8ee0..5a1ebf867d 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/NodeTextBox.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/NodeControls/NodeTextBox.cs @@ -47,9 +47,21 @@ protected override Control CreateEditor(TreeNodeAdv node) textBox.KeyDown += EditorKeyDown; _label = textBox.Text; SetEditControlProperties(textBox, node); + textBox.PreviewKeyDown += new PreviewKeyDownEventHandler(textBox_PreviewKeyDown); return textBox; } + void textBox_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) + { + switch (e.KeyCode) + { + case Keys.Enter: + case Keys.Escape: + e.IsInputKey = true; + break; + } + } + protected virtual TextBox CreateTextBox() { return new TextBox(); diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeColumn.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeColumn.cs index fcaf03d63e..713b5e4d38 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeColumn.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeColumn.cs @@ -27,6 +27,8 @@ public override bool GetPropertiesSupported(ITypeDescriptorContext context) private const int HeaderLeftMargin = 5; private const int HeaderRightMargin = 5; + private const int HeaderTopMargin = 3; + private const int HeaderBottomMargin = 3; private const int SortOrderMarkMargin = 8; private TextFormatFlags _headerFlags; @@ -215,6 +217,61 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } + internal Size GetActualSize(DrawContext context) + { + if (IsVisible) + { + Size s = MeasureSize(context); + return new Size(s.Width + HeaderLeftMargin, HeaderTopMargin + s.Height + HeaderBottomMargin); + } + return Size.Empty; + } + + public Size MeasureSize(DrawContext context) + { + return GetLabelSize(context); + } + + protected Size GetLabelSize(DrawContext context) + { + return GetLabelSize(context, Header); + } + + protected Size GetLabelSize(DrawContext context, string label) + { + PerformanceAnalyzer.Start("GetLabelSize"); + + Font font = GetDrawingFont(context, label); + Size s = Size.Empty; + if (!UseCompatibleTextRendering) + s = TextRenderer.MeasureText(label, font); + else + { + SizeF sf = context.Graphics.MeasureString(label, font); + s = new Size((int)Math.Ceiling(sf.Width), (int)Math.Ceiling(sf.Height)); + } + + PerformanceAnalyzer.Finish("GetLabelSize"); + + if (!s.IsEmpty) + return s; + else + return new Size(10, font.Height); + } + + protected Font GetDrawingFont(DrawContext context, string label) + { + return context.Font; + } + + private bool _useCompatibleTextRendering = false; + [DefaultValue(false)] + public bool UseCompatibleTextRendering + { + get { return _useCompatibleTextRendering; } + set { _useCompatibleTextRendering = value; } + } + #region Draw private static VisualStyleRenderer _normalRenderer; @@ -231,23 +288,22 @@ private static void CreateRenderers() } } - internal Bitmap CreateGhostImage(Rectangle bounds, Font font) + internal Bitmap CreateGhostImage(Rectangle bounds, Font font, Color color) { Bitmap b = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); Graphics gr = Graphics.FromImage(b); gr.FillRectangle(SystemBrushes.ControlDark, bounds); - DrawContent(gr, bounds, font); + DrawContent(gr, bounds, font, color); BitmapHelper.SetAlphaChanelValue(b, 150); return b; } - internal void Draw(Graphics gr, Rectangle bounds, Font font, bool pressed, bool hot) + internal void Draw(Graphics gr, Rectangle bounds, Font font, bool pressed, bool hot, Color color) { - DrawBackground(gr, bounds, pressed, hot); - DrawContent(gr, bounds, font); + DrawContent(gr, bounds, font, color); } - private void DrawContent(Graphics gr, Rectangle bounds, Font font) + private void DrawContent(Graphics gr, Rectangle bounds, Font font, Color color) { Rectangle innerBounds = new Rectangle(bounds.X + HeaderLeftMargin, bounds.Y, bounds.Width - HeaderLeftMargin - HeaderRightMargin, @@ -274,9 +330,9 @@ private void DrawContent(Graphics gr, Rectangle bounds, Font font) } if (textSize.Width < maxTextSize.Width) - TextRenderer.DrawText(gr, Header, font, innerBounds, SystemColors.ControlText, _baseHeaderFlags | TextFormatFlags.Left); + TextRenderer.DrawText(gr, Header, font, innerBounds, color, _baseHeaderFlags | TextFormatFlags.Left); else - TextRenderer.DrawText(gr, Header, font, innerBounds, SystemColors.ControlText, _headerFlags); + TextRenderer.DrawText(gr, Header, font, innerBounds, color, _headerFlags); } private void DrawSortMark(Graphics gr, Rectangle bounds, int x) @@ -334,11 +390,20 @@ internal static void DrawBackground(Graphics gr, Rectangle bounds, bool pressed, } } - #endregion + internal static void DrawCustomBackground(Graphics gr, Color back, Color fore, Rectangle bounds, bool pressed, bool hot) + { + gr.FillRectangle(new SolidBrush(back), bounds); + Pen p1 = new Pen(fore); + gr.DrawLine(p1, bounds.X, bounds.Y - 1, bounds.Right, bounds.Y - 1); + gr.DrawLine(p1, bounds.Right - 1, bounds.Y + 3, bounds.Right - 1, bounds.Bottom - 4); + gr.DrawLine(p1, bounds.X, bounds.Bottom, bounds.Right, bounds.Bottom); + } + + #endregion - #region Events + #region Events - public event EventHandler HeaderChanged; + public event EventHandler HeaderChanged; private void OnHeaderChanged() { if (HeaderChanged != null) diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeColumnCollection.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeColumnCollection.cs index 2368ec65d3..3c38b2af49 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeColumnCollection.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeColumnCollection.cs @@ -1,8 +1,5 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Collections.ObjectModel; -using System.ComponentModel; using System.Windows.Forms; namespace Aga.Controls.Tree diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeNodeAdv.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeNodeAdv.cs index 609587b9fd..b5fa50fa15 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeNodeAdv.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeNodeAdv.cs @@ -158,6 +158,12 @@ public bool IsSelected } } + + internal void SetSelectedInternal(bool value) + { + _isSelected = value; + } + /// /// Returns true if all parent nodes of this node are expanded. /// @@ -269,6 +275,16 @@ internal TreeNodeAdv BottomNode } } + internal bool IsVisibleOverride {get + { + bool visible = true; + if (Tree.OnVisibleOverride != null) + Tree.OnVisibleOverride(this.Tag, ref visible); + return visible; + }} + + + internal TreeNodeAdv NextVisibleNode { get diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Designer.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Designer.cs index b08e6410ba..44aee1a057 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Designer.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Designer.cs @@ -6,19 +6,6 @@ partial class TreeViewAdv { private System.ComponentModel.IContainer components = null; - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - if (_dragBitmap != null) _dragBitmap.Dispose(); - if (_dragTimer != null) _dragTimer.Dispose(); - if (_linePen != null) _linePen.Dispose(); - if (_markPen != null) _markPen.Dispose(); - } - base.Dispose(disposing); - } - #region Component Designer generated code private void InitializeComponent() { diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Draw.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Draw.cs index 75391c302e..9a1007f9e5 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Draw.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Draw.cs @@ -40,7 +40,8 @@ public void AutoSizeColumn(TreeColumn column) private void CreatePens() { CreateLinePen(); - CreateMarkPen(); + CreateMarkPen(); + CreateLine2Pen(); } private void CreateMarkPen() @@ -61,6 +62,25 @@ private void CreateLinePen() _linePen.DashStyle = DashStyle.Dot; } + private void CreateLine2Pen() + { + _line2Pen = new Pen(_lineColor); + } + + protected override void OnPaintBackground(PaintEventArgs pevent) + { + if (this.BackgroundPaintMode == Tree.BackgroundPaintMode.Gradiant) + { + Rectangle rc = new Rectangle(0, 0, this.ClientSize.Width, this.ClientSize.Height); + using (LinearGradientBrush brush = new LinearGradientBrush(rc, BackColor, BackColor2, 90.0f)) + { + pevent.Graphics.FillRectangle(brush, rc); + } + } + else + base.OnPaintBackground(pevent); + + } protected override void OnPaint(PaintEventArgs e) { BeginPerformanceCount(); @@ -76,9 +96,9 @@ protected override void OnPaint(PaintEventArgs e) if (UseColumns) { - DrawColumnHeaders(e.Graphics); - y += ColumnHeaderHeight; - if (Columns.Count == 0 || e.ClipRectangle.Height <= y) + DrawColumnHeaders(e.Graphics, this.ColumnHeaderBackColor, this.ColumnHeaderBorderColor, this.ColumnHeaderTextColor); + y += ActualColumnHeaderHeight; + if (Columns.Count == 0 || e.ClipRectangle.Height + e.ClipRectangle.Top <= y) return; } @@ -126,7 +146,7 @@ private void DrawRow(PaintEventArgs e, ref DrawContext context, int row, Rectang } else { - if (node.IsSelected && Focused) + if (node.IsSelected && (Focused || !InactiveSelection)) context.DrawSelection = DrawSelectionMode.Active; else if (node.IsSelected && !Focused && !HideSelection) context.DrawSelection = DrawSelectionMode.Inactive; @@ -143,19 +163,19 @@ private void DrawRow(PaintEventArgs e, ref DrawContext context, int row, Rectang Rectangle focusRect = new Rectangle(OffsetX, rowRect.Y, ClientRectangle.Width, rowRect.Height); if (context.DrawSelection == DrawSelectionMode.Active) { - e.Graphics.FillRectangle(SystemBrushes.Highlight, focusRect); + e.Graphics.FillRectangle(_highlightColorActiveBrush, focusRect); context.DrawSelection = DrawSelectionMode.FullRowSelect; } else { - e.Graphics.FillRectangle(SystemBrushes.InactiveBorder, focusRect); + e.Graphics.FillRectangle(_highlightColorInactiveBrush, focusRect); context.DrawSelection = DrawSelectionMode.None; } } } if ((GridLineStyle & GridLineStyle.Horizontal) == GridLineStyle.Horizontal) - e.Graphics.DrawLine(SystemPens.InactiveBorder, 0, rowRect.Bottom, e.Graphics.ClipBounds.Right, rowRect.Bottom); + e.Graphics.DrawLine(_line2Pen, 0, rowRect.Bottom, e.Graphics.ClipBounds.Right, rowRect.Bottom); if (ShowLines) DrawLines(e.Graphics, node, rowRect); @@ -171,28 +191,36 @@ private void DrawVerticalGridLines(Graphics gr, int y) if (c.IsVisible) { x += c.Width; - gr.DrawLine(SystemPens.InactiveBorder, x - 1, y, x - 1, gr.ClipBounds.Bottom); + gr.DrawLine(_line2Pen, x - 1, y, x - 1, gr.ClipBounds.Bottom); } } } - private void DrawColumnHeaders(Graphics gr) + private void DrawColumnHeaders(Graphics gr, Color back, Color fore, Color text) { PerformanceAnalyzer.Start("DrawColumnHeaders"); ReorderColumnState reorder = Input as ReorderColumnState; int x = 0; - TreeColumn.DrawBackground(gr, new Rectangle(0, 0, ClientRectangle.Width + 2, ColumnHeaderHeight - 1), false, false); - gr.TranslateTransform(-OffsetX, 0); + + if (this.CustomDrawHeaders) TreeColumn.DrawCustomBackground(gr, back, fore, new Rectangle(0, 0, ClientRectangle.Width + 2, ActualColumnHeaderHeight - 1), false, false); + else TreeColumn.DrawBackground(gr, new Rectangle(0, 0, ClientRectangle.Width + 2, ActualColumnHeaderHeight - 1), false, false); + + gr.TranslateTransform(-OffsetX, 0); foreach (TreeColumn c in Columns) { if (c.IsVisible) { if (x >= OffsetX && x - OffsetX < this.Bounds.Width)// skip invisible columns { - Rectangle rect = new Rectangle(x, 0, c.Width, ColumnHeaderHeight - 1); + Rectangle rect = new Rectangle(x, 0, c.Width, ActualColumnHeaderHeight - 1); gr.SetClip(rect); bool pressed = ((Input is ClickColumnState || reorder != null) && ((Input as ColumnState).Column == c)); - c.Draw(gr, rect, Font, pressed, _hotColumn == c); + + if (this.CustomDrawHeaders) TreeColumn.DrawCustomBackground(gr, back, fore, rect, pressed, _hotColumn == c); + else TreeColumn.DrawBackground(gr, rect, pressed, _hotColumn == c); + + c.Draw(gr, rect, Font, pressed, _hotColumn == c, text); + gr.ResetClip(); if (reorder != null && reorder.DropColumn == c) @@ -205,7 +233,7 @@ private void DrawColumnHeaders(Graphics gr) if (reorder != null) { if (reorder.DropColumn == null) - TreeColumn.DrawDropMark(gr, new Rectangle(x, 0, 0, ColumnHeaderHeight)); + TreeColumn.DrawDropMark(gr, new Rectangle(x, 0, 0, ActualColumnHeaderHeight)); gr.DrawImage(reorder.GhostImage, new Point(reorder.Location.X + + reorder.DragOffset, reorder.Location.Y)); } PerformanceAnalyzer.Finish("DrawColumnHeaders"); diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Editor.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Editor.cs index b65aca0446..71e20ceb77 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Editor.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Editor.cs @@ -32,6 +32,8 @@ internal void DisplayEditor(Control editor, EditableControl owner) _editingNode = CurrentNode; editor.Validating += EditorValidating; + editor.Leave += EditorLeave; + editor.LostFocus += EditorLeave; UpdateEditorBounds(); UpdateView(); editor.Parent = this; @@ -39,6 +41,11 @@ internal void DisplayEditor(Control editor, EditableControl owner) owner.UpdateEditor(editor); } + void EditorLeave(object sender, EventArgs e) + { + HideEditor(true); + } + internal bool HideEditor(bool applyChanges) { if (CurrentEditor != null) @@ -53,6 +60,8 @@ internal bool HideEditor(bool applyChanges) if (CurrentEditor != null) { CurrentEditor.Validating -= EditorValidating; + CurrentEditor.Leave -= EditorLeave; + CurrentEditor.LostFocus -= EditorLeave; CurrentEditorOwner.DoDisposeEditor(CurrentEditor); CurrentEditor.Parent = null; @@ -112,7 +121,7 @@ private void SetEditorBounds(EditorContext context) Point p = info.Bounds.Location; p.X += info.Control.LeftMargin; p.X -= OffsetX; - p.Y -= (_rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); + p.Y -= (_rowLayout.GetRowBounds(FirstVisibleRow).Y - ActualColumnHeaderHeight); int width = DisplayRectangle.Width - p.X; if (UseColumns && info.Control.ParentColumn != null && Columns.Contains(info.Control.ParentColumn)) { diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Input.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Input.cs index 57d1ecfbc4..6e0a270664 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Input.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Input.cs @@ -102,7 +102,7 @@ private TreeNodeAdvMouseEventArgs CreateMouseArgs(MouseEventArgs e) { TreeNodeAdvMouseEventArgs args = new TreeNodeAdvMouseEventArgs(e); args.ViewLocation = new Point(e.X + OffsetX, - e.Y + _rowLayout.GetRowBounds(FirstVisibleRow).Y - ColumnHeaderHeight); + e.Y + _rowLayout.GetRowBounds(FirstVisibleRow).Y - ActualColumnHeaderHeight); args.ModifierKeys = ModifierKeys; args.Node = GetNodeAt(e.Location); NodeControlInfo info = GetNodeControlInfoAt(args.Node, e.Location); @@ -111,19 +111,24 @@ private TreeNodeAdvMouseEventArgs CreateMouseArgs(MouseEventArgs e) return args; } - protected override void OnMouseWheel(MouseEventArgs e) - { - _search.EndSearch(); - if (SystemInformation.MouseWheelScrollLines > 0) - { - int lines = e.Delta / 120 * SystemInformation.MouseWheelScrollLines; - int newValue = _vScrollBar.Value - lines; - newValue = Math.Min(_vScrollBar.Maximum - _vScrollBar.LargeChange + 1, newValue); - newValue = Math.Min(_vScrollBar.Maximum, newValue); - _vScrollBar.Value = Math.Max(_vScrollBar.Minimum, newValue); - } - base.OnMouseWheel(e); - } + protected override void OnMouseWheel(MouseEventArgs e) + { + // e.Delta is no longer fixed to the value 120. + const double ScrollBaseFactor = 120; + _search.EndSearch(); + int linesToScroll = SystemInformation.MouseWheelScrollLines; + + if (linesToScroll == -1) + linesToScroll = _vScrollBar.LargeChange; + + int lines = (int)(e.Delta / ScrollBaseFactor) * linesToScroll; + int newValue = _vScrollBar.Value - lines; + newValue = Math.Min(_vScrollBar.Maximum - _vScrollBar.LargeChange + 1, newValue); + newValue = Math.Min(_vScrollBar.Maximum, newValue); + _vScrollBar.Value = Math.Max(_vScrollBar.Minimum, newValue); + + base.OnMouseWheel(e); + } protected override void OnMouseDown(MouseEventArgs e) { @@ -265,7 +270,7 @@ private void SetCursor(MouseEventArgs e) internal TreeColumn GetColumnAt(Point p) { - if (p.Y > ColumnHeaderHeight) + if (p.Y > ActualColumnHeaderHeight) return null; int x = -OffsetX; @@ -273,7 +278,7 @@ internal TreeColumn GetColumnAt(Point p) { if (col.IsVisible) { - Rectangle rect = new Rectangle(x, 0, col.Width, ColumnHeaderHeight); + Rectangle rect = new Rectangle(x, 0, col.Width, ActualColumnHeaderHeight); x += col.Width; if (rect.Contains(p)) return col; @@ -300,7 +305,7 @@ internal int GetColumnX(TreeColumn column) internal TreeColumn GetColumnDividerAt(Point p) { - if (p.Y > ColumnHeaderHeight) + if (p.Y > ActualColumnHeaderHeight) return null; int x = -OffsetX; @@ -312,8 +317,8 @@ internal TreeColumn GetColumnDividerAt(Point p) { if (col.Width > 0) { - left = new Rectangle(x, 0, DividerWidth / 2, ColumnHeaderHeight); - right = new Rectangle(x + col.Width - (DividerWidth / 2), 0, DividerWidth / 2, ColumnHeaderHeight); + left = new Rectangle(x, 0, DividerWidth / 2, ActualColumnHeaderHeight); + right = new Rectangle(x + col.Width - (DividerWidth / 2), 0, DividerWidth / 2, ActualColumnHeaderHeight); if (left.Contains(p) && prevCol != null) return prevCol; else if (right.Contains(p)) @@ -324,7 +329,7 @@ internal TreeColumn GetColumnDividerAt(Point p) } } - left = new Rectangle(x, 0, DividerWidth / 2, ColumnHeaderHeight); + left = new Rectangle(x, 0, DividerWidth / 2, ActualColumnHeaderHeight); if (left.Contains(p) && prevCol != null) return prevCol; @@ -430,7 +435,7 @@ private void SetDropPosition(Point pt) { Rectangle first = _rowLayout.GetRowBounds(FirstVisibleRow); Rectangle bounds = _rowLayout.GetRowBounds(node.Row); - float pos = (pt.Y + first.Y - ColumnHeaderHeight - bounds.Y) / (float)bounds.Height; + float pos = (pt.Y + first.Y - ActualColumnHeaderHeight - bounds.Y) / (float)bounds.Height; if (pos < TopEdgeSensivity) _dropPosition.Position = NodePosition.Before; else if (pos > (1 - BottomEdgeSensivity)) diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Properties.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Properties.cs index 44a8a30c4f..1dfb349a8c 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Properties.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.Properties.cs @@ -13,8 +13,9 @@ namespace Aga.Controls.Tree public partial class TreeViewAdv { private Cursor _innerCursor = null; + public bool CustomDrawHeaders = false; - public override Cursor Cursor + public override Cursor Cursor { get { @@ -32,6 +33,7 @@ public override Cursor Cursor #region Internal Properties private IRowLayout _rowLayout; + private IHeaderLayout _headerLayout; private bool _dragMode; private bool DragMode @@ -52,18 +54,10 @@ private bool DragMode } } - // HACK: Made public - public int ColumnHeaderHeight - { - get - { - if (UseColumns) - return _columnHeaderHeight; - else - return 0; - } - } - + internal int ActualColumnHeaderHeight + { + get { return UseColumns ? ColumnHeaderHeight : 0; } + } /// /// returns all nodes, which parent is expanded /// @@ -75,7 +69,7 @@ private IEnumerable VisibleNodes while (node != null) { node = node.NextVisibleNode; - if (node != null) + if (node != null && node.IsVisibleOverride) yield return node; } } @@ -177,6 +171,27 @@ internal int FirstVisibleRow } } + public TreeNodeAdv FirstVisibleNode + { + get + { + if (_firstVisibleRow >= 0 && _firstVisibleRow < RowMap.Count) + return RowMap[_firstVisibleRow]; + return null; + } + } + + public TreeNodeAdv LastVisibleNode + { + get + { + int lastVisibleRow = _firstVisibleRow + CurrentPageSize - 1; + if (lastVisibleRow >= 0 && lastVisibleRow < RowMap.Count) + return RowMap[lastVisibleRow]; + return null; + } + } + private int _offsetX; public int OffsetX { @@ -194,8 +209,8 @@ public override Rectangle DisplayRectangle get { Rectangle r = ClientRectangle; - //r.Y += ColumnHeaderHeight; - //r.Height -= ColumnHeaderHeight; + //r.Y += ActualColumnHeaderHeight; + //r.Height -= ActualColumnHeaderHeight; int w = _vScrollBar.Visible ? _vScrollBar.Width : 0; int h = _hScrollBar.Visible ? _hScrollBar.Height : 0; return new Rectangle(r.X, r.Y, r.Width - w, r.Height - h); @@ -213,6 +228,85 @@ internal List Selection #region Public Properties #region DesignTime + private BackgroundPaintMode _backgroundPaintMode = BackgroundPaintMode.Default; + [Category("Appearance")] + public BackgroundPaintMode BackgroundPaintMode + { + get + { + return _backgroundPaintMode; + } + set + { + _backgroundPaintMode = value; + } + } + + + + private Color _backgroundColor2 = SystemColors.Window; + [Category("Appearance")] + public Color BackColor2 + { + get + { + return _backgroundColor2; + } + set + { + _backgroundColor2 = value; + } + } + + + private Color _highlightColorActive = SystemColors.Highlight; + internal SolidBrush _highlightColorActiveBrush = (SolidBrush)SystemBrushes.Highlight; + [Category("Appearance")] + public Color HighlightColorActive + { + get + { + return _highlightColorActive; + } + set + { + _highlightColorActive = value; + _highlightColorActiveBrush = new SolidBrush(_highlightColorActive); + } + } + + private Color _highlightColorInactive = SystemColors.InactiveBorder; + internal SolidBrush _highlightColorInactiveBrush = (SolidBrush)SystemBrushes.InactiveBorder; + + [Category("Appearance")] + public Color HighlightColorInactive + { + get + { + return _highlightColorInactive; + } + set + { + _highlightColorInactive = value; + _highlightColorInactiveBrush = new SolidBrush(_highlightColorInactive); + + } + } + + + private bool _AutoSpanColumns = false; + [DefaultValue(false), Category("Appearance")] + public bool AutoSpanColumns + { + get + { + return _AutoSpanColumns; + } + set + { + _AutoSpanColumns = value; + } + } private bool _shiftFirstNode; [DefaultValue(false), Category("Behavior")] @@ -373,12 +467,12 @@ public override Font Font set { base.Font = value; - _columnHeaderHeight = base.Font.Height + 9; + ColumnHeaderHeight = base.Font.Height + 9; } } // End font property - private BorderStyle _borderStyle = BorderStyle.Fixed3D; + private BorderStyle _borderStyle = BorderStyle.Fixed3D; [DefaultValue(BorderStyle.Fixed3D), Category("Appearance")] public BorderStyle BorderStyle { @@ -418,6 +512,28 @@ public bool AutoRowHeight } } + private bool _autoHeaderHeight = false; + /// + /// Set to true to expand header height to fit the text of it's largest column. + /// + [DefaultValue(false), Category("Appearance"), Description("Expand each header height to fit the text of it's largest column.")] + public bool AutoHeaderHeight + { + get + { + return _autoHeaderHeight; + } + set + { + _autoHeaderHeight = value; + if (value) + _headerLayout = new AutoHeaderHeightLayout(this, ActualColumnHeaderHeight); + else + _headerLayout = new FixedHeaderHeightLayout(this, ActualColumnHeaderHeight); + FullUpdate(); + } + } + private GridLineStyle _gridLineStyle = GridLineStyle.None; [DefaultValue(GridLineStyle.None), Category("Appearance")] public GridLineStyle GridLineStyle @@ -476,6 +592,18 @@ public bool HideSelection } } + bool _inactiveSelection = true; + [DefaultValue(true), Category("Behavior")] + public bool InactiveSelection + { + get { return _inactiveSelection; } + set + { + _inactiveSelection = value; + UpdateView(); + } + } + private float _topEdgeSensivity = 0.3f; [DefaultValue(0.3f), Category("Behavior")] public float TopEdgeSensivity @@ -530,7 +658,43 @@ public int Indent } } - private Color _lineColor = SystemColors.ControlDark; + private Color _columnTextColor = SystemColors.ControlText; + [Category("Behavior")] + public Color ColumnHeaderTextColor + { + get { return _columnTextColor; } + set + { + _columnTextColor = value; + UpdateView(); + } + } + + private Color _columnBackColor = SystemColors.Control; + [Category("Behavior")] + public Color ColumnHeaderBackColor + { + get { return _columnBackColor; } + set + { + _columnBackColor = value; + UpdateView(); + } + } + + private Color _columnBorderColor = SystemColors.ActiveBorder; + [Category("Behavior")] + public Color ColumnHeaderBorderColor + { + get { return _columnBorderColor; } + set + { + _columnBorderColor = value; + UpdateView(); + } + } + + private Color _lineColor = SystemColors.ControlDark; [Category("Behavior")] public Color LineColor { @@ -543,7 +707,20 @@ public Color LineColor } } - private Color _dragDropMarkColor = Color.Black; + private Color _lineColor2 = SystemColors.ControlDark; + [Category("Behavior")] + public Color LineColor2 + { + get { return _lineColor2; } + set + { + _lineColor2 = value; + CreateLine2Pen(); + UpdateView(); + } + } + + private Color _dragDropMarkColor = Color.Black; [Category("Behavior")] public Color DragDropMarkColor { @@ -604,10 +781,40 @@ public bool AsyncExpanding set { _asyncExpanding = value; } } + [DefaultValue(20), Category("Appearance")] + public int ColumnHeaderHeight + { + get + { + return _headerLayout.PreferredHeaderHeight; + } + set + { + if (value < 0) + throw new ArgumentOutOfRangeException("value"); + _headerLayout.PreferredHeaderHeight = value; + FullUpdate(); + } + } + + #endregion #region RunTime + public delegate void VisibleOverride(object node, ref bool visible); + + private VisibleOverride _onVisibleOverride; + public VisibleOverride OnVisibleOverride + { + get { return _onVisibleOverride; } + set + { + _onVisibleOverride = value; + FullUpdate(); + } + } + private IToolTipProvider _defaultToolTipProvider = null; [Browsable(false)] public IToolTipProvider DefaultToolTipProvider diff --git a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.cs b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.cs index d68e910c2a..40748e6026 100644 --- a/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.cs +++ b/External/3rdParty/Aga-1.7/Aga.Controls/Tree/TreeViewAdv.cs @@ -25,13 +25,12 @@ public partial class TreeViewAdv : Control { private const int LeftMargin = 7; internal const int ItemDragSensivity = 4; - // HACK: removed readonly - private int _columnHeaderHeight; private const int DividerWidth = 9; private const int DividerCorrectionGap = -2; private Pen _linePen; - private Pen _markPen; + private Pen _line2Pen; + private Pen _markPen; private bool _suspendUpdate; private bool _needFullUpdate; private bool _fireSelectionEvent; @@ -77,6 +76,14 @@ internal void OnColumnWidthChanged(TreeColumn column) ColumnWidthChanged(this, new TreeColumnEventArgs(column)); } + [Category("Behavior")] + public event EventHandler ColumnHeightChanged; + internal void OnColumnHeightChanged(TreeColumn column) + { + if (ColumnHeightChanged != null) + ColumnHeightChanged(this, new TreeColumnEventArgs(column)); + } + [Category("Behavior")] public event EventHandler ColumnReordered; internal void OnColumnReordered(TreeColumn column) @@ -212,11 +219,7 @@ public TreeViewAdv() | ControlStyles.Selectable , true); - - if (Application.RenderWithVisualStyles) - _columnHeaderHeight = 20; - else - _columnHeaderHeight = 17; + _headerLayout = new FixedHeaderHeightLayout(this, Application.RenderWithVisualStyles ? 20: 17); //BorderStyle = BorderStyle.Fixed3D; _hScrollBar.Height = SystemInformation.HorizontalScrollBarHeight; @@ -241,9 +244,9 @@ public TreeViewAdv() _plusMinus = new NodePlusMinus(); _controls = new NodeControlsCollection(this); - - // HACK: commented out - // Font = _font; + + //HACK: Commented out + //Font = _font; ExpandingIcon.IconChanged += ExpandingIconChanged; } @@ -261,7 +264,7 @@ private void DrawIcons() int y = 0; if (UseColumns) { - y += ColumnHeaderHeight; + y += ActualColumnHeaderHeight; if (Columns.Count == 0) return; } @@ -272,18 +275,21 @@ private void DrawIcons() DrawContext context = new DrawContext(); context.Graphics = gr; - for (int i = 0; i < _expandingNodes.Count; i++) + lock (_expandingNodes) { - foreach (NodeControlInfo item in GetNodeControls(_expandingNodes[i])) + for (int i = 0; i < _expandingNodes.Count; i++) { - if (item.Control is ExpandingIcon) + foreach (NodeControlInfo item in GetNodeControls(_expandingNodes[i])) { - Rectangle bounds = item.Bounds; - if (item.Node.Parent == null && UseColumns) - bounds.Location = Point.Empty; // display root expanding icon at 0,0 + if (item.Control is ExpandingIcon) + { + Rectangle bounds = item.Bounds; + if (item.Node.Parent == null && UseColumns) + bounds.Location = Point.Empty; // display root expanding icon at 0,0 - context.Bounds = bounds; - item.Control.Draw(item.Node, context); + context.Bounds = bounds; + item.Control.Draw(item.Node, context); + } } } } @@ -329,7 +335,7 @@ public NodeControlInfo GetNodeControlInfoAt(Point point) private NodeControlInfo GetNodeControlInfoAt(TreeNodeAdv node, Point point) { Rectangle rect = _rowLayout.GetRowBounds(FirstVisibleRow); - point.Y += (rect.Y - ColumnHeaderHeight); + point.Y += (rect.Y - ActualColumnHeaderHeight); point.X += OffsetX; foreach (NodeControlInfo info in GetNodeControls(node)) if (info.Bounds.Contains(point)) @@ -378,13 +384,16 @@ public void EnsureVisible(TreeNodeAdv node) if (!IsMyNode(node)) throw new ArgumentException(); - TreeNodeAdv parent = node.Parent; - while (parent != _root) + if (node != _root) { - parent.IsExpanded = true; - parent = parent.Parent; + TreeNodeAdv parent = node.Parent; + while (parent != _root) + { + parent.IsExpanded = true; + parent = parent.Parent; + } + ScrollTo(node); } - ScrollTo(node); } /// @@ -410,7 +419,7 @@ public void ScrollTo(TreeNodeAdv node) { int pageStart = _rowLayout.GetRowBounds(FirstVisibleRow).Top; int rowBottom = _rowLayout.GetRowBounds(node.Row).Bottom; - if (rowBottom > pageStart + DisplayRectangle.Height - ColumnHeaderHeight) + if (rowBottom > pageStart + DisplayRectangle.Height - ActualColumnHeaderHeight) row = _rowLayout.GetFirstRow(node.Row); } @@ -441,11 +450,59 @@ internal void ClearSelectionInternal() } } + public void SpanColumns() + { + int totalColumns = Columns.Count; + int workingWidth = DisplayRectangle.Width - totalColumns; + if (totalColumns > 0 && workingWidth > 0) + { + + BeginUpdate(); + int totalColumnsWidth = 0; + + foreach (TreeColumn column in Columns) + totalColumnsWidth += column.Width; + + foreach (TreeColumn column in Columns) + { + int newWidth = (int)Math.Ceiling(workingWidth * (double)column.Width / totalColumnsWidth); + + newWidth = Math.Max(newWidth, column.MinColumnWidth); + if (column.MaxColumnWidth != 0) + newWidth = Math.Min(newWidth, column.MaxColumnWidth); + + column.Width = newWidth; + } + EndUpdate(); + } + } + #endregion + protected override void Dispose(bool disposing) + { + if (disposing) + { + AbortBackgroundExpandingThreads(); + if (_model != null) + UnbindModelEvents(); + ExpandingIcon.IconChanged -= ExpandingIconChanged; + if (components != null) + components.Dispose(); + if (_dragBitmap != null) _dragBitmap.Dispose(); + if (_dragTimer != null) _dragTimer.Dispose(); + if (_linePen != null) _linePen.Dispose(); + if (_line2Pen != null) _linePen.Dispose(); + if (_markPen != null) _markPen.Dispose(); + } + base.Dispose(disposing); + } + protected override void OnSizeChanged(EventArgs e) { ArrangeControls(); + if (AutoSpanColumns) + SpanColumns(); SafeUpdateScrollBars(); base.OnSizeChanged(e); } @@ -524,6 +581,12 @@ protected override void OnGotFocus(EventArgs e) base.OnGotFocus(e); } + protected override void OnLostFocus(EventArgs e) + { + UpdateView(); + base.OnLostFocus(e); + } + protected override void OnFontChanged(EventArgs e) { base.OnFontChanged(e); @@ -531,7 +594,7 @@ protected override void OnFontChanged(EventArgs e) FullUpdate(); } - // HACK: Made public + //HACK: Made public public IEnumerable GetNodeControls(TreeNodeAdv node) { if (node == null) @@ -541,8 +604,8 @@ public IEnumerable GetNodeControls(TreeNodeAdv node) yield return n; } - // HACK: Made public - public IEnumerable GetNodeControls(TreeNodeAdv node, Rectangle rowRect) + //HACK: Made public + public IEnumerable GetNodeControls(TreeNodeAdv node, Rectangle rowRect) { if (node == null) yield break; @@ -635,6 +698,7 @@ public void FullUpdate() private void UnsafeFullUpdate() { + _headerLayout.ClearCache(); _rowLayout.ClearCache(); CreateRowMap(); SafeUpdateScrollBars(); @@ -650,7 +714,7 @@ internal void UpdateView() internal void UpdateHeaders() { - Invalidate(new Rectangle(0, 0, Width, ColumnHeaderHeight)); + Invalidate(new Rectangle(0, 0, Width, ActualColumnHeaderHeight)); } internal void UpdateColumns() @@ -677,11 +741,10 @@ internal void ReadChilds(TreeNodeAdv parentNode) internal void ReadChilds(TreeNodeAdv parentNode, bool performFullUpdate) { + parentNode.Nodes.Clear(); if (!parentNode.IsLeaf) { parentNode.IsExpandedOnce = true; - parentNode.Nodes.Clear(); - if (Model != null) { IEnumerable items = Model.GetChildren(GetPath(parentNode)); @@ -711,7 +774,6 @@ private void AddNode(TreeNodeAdv parent, int index, TreeNodeAdv node) parent.Nodes.Insert(index, node); else parent.Nodes.Add(node); - node.IsLeaf = Model.IsLeaf(GetPath(node)); if (node.IsLeaf) node.Nodes.Clear(); @@ -728,10 +790,13 @@ private struct ExpandArgs public void AbortBackgroundExpandingThreads() { - _threadPool.CancelAll(true); - for (int i = 0; i < _expandingNodes.Count; i++) - _expandingNodes[i].IsExpandingNow = false; - _expandingNodes.Clear(); + lock (_expandingNodes) + { + _threadPool.CancelAll(true); + for (int i = 0; i < _expandingNodes.Count; i++) + _expandingNodes[i].IsExpandingNow = false; + _expandingNodes.Clear(); + } Invalidate(); } @@ -815,17 +880,23 @@ internal void SetIsExpanded(TreeNodeAdv node, bool value) private void RemoveExpandingNode(TreeNodeAdv node) { - node.IsExpandingNow = false; - _expandingNodes.Remove(node); - if (_expandingNodes.Count <= 0) - ExpandingIcon.Stop(); + lock (_expandingNodes) + { + node.IsExpandingNow = false; + _expandingNodes.Remove(node); + if (_expandingNodes.Count <= 0) + ExpandingIcon.Stop(); + } } private void AddExpandingNode(TreeNodeAdv node) { - node.IsExpandingNow = true; - _expandingNodes.Add(node); - ExpandingIcon.Start(); + lock (_expandingNodes) + { + node.IsExpandingNow = true; + _expandingNodes.Add(node); + ExpandingIcon.Start(); + } } internal void SetIsExpandedRecursive(TreeNodeAdv root, bool value) @@ -956,11 +1027,20 @@ internal void ChangeColumnWidth(TreeColumn column) { if (!(_input is ResizeColumnState)) { - FullUpdate(); + SmartFullUpdate(); OnColumnWidthChanged(column); } } + internal void ChangeColumnHeight(TreeColumn column) + { + if (!(_input is ResizeColumnState)) + { + SmartFullUpdate(); + OnColumnHeightChanged(column); + } + } + public TreeNodeAdv FindNode(TreePath path) { return FindNode(path, false); @@ -1062,6 +1142,54 @@ private void UnbindModelEvents() _model.StructureChanged -= new EventHandler(_model_StructureChanged); } + private static object[] GetRelativePath(TreeNodeAdv root, TreeNodeAdv node) + { + int level = 0; + TreeNodeAdv current = node; + while (current != root && current != null) + { + current = current.Parent; + level++; + } + if (current != null) + { + object[] result = new object[level]; + current = node; + while (current != root && current != null) + { + level--; + result[level] = current.Tag; + current = current.Parent; + } + return result; + } + return null; + } + + private TreeNodeAdv FindChildNode(TreeNodeAdv root, object[] relativePath, int level, bool readChilds) + { + if (relativePath == null) + return null; + if (level == relativePath.Length) + return root; + + if (!root.IsExpandedOnce && readChilds) + ReadChilds(root); + + for (int i = 0; i < root.Nodes.Count; i++) + { + TreeNodeAdv node = root.Nodes[i]; + if (node.Tag == relativePath[level]) + { + if (level == relativePath.Length - 1) + return node; + else + return FindChildNode(node, relativePath, level + 1, readChilds); + } + } + return null; + } + private void _model_StructureChanged(object sender, TreePathEventArgs e) { if (e.Path == null) @@ -1073,11 +1201,57 @@ private void _model_StructureChanged(object sender, TreePathEventArgs e) if (node != Root) node.IsLeaf = Model.IsLeaf(GetPath(node)); + object[] currentPath = GetRelativePath(node, _currentNode); + object[] selectionStartPath = GetRelativePath(node, _selectionStart); + List selectionPaths = new List(); + List preservedSelection = new List(); + foreach (var selectionNode in Selection) + { + object[] selectionPath = GetRelativePath(node, selectionNode); + if (selectionPath != null) + selectionPaths.Add(selectionPath); + else //preserve selection because this selectionNode is not a child of node + preservedSelection.Add(selectionNode); + } + var list = new Dictionary(); SaveExpandedNodes(node, list); ReadChilds(node); + + bool suspendSelectionEventBefore = SuspendSelectionEvent; + bool suspendUpdateBefore = _suspendUpdate; + bool fireSelectionBefore = _fireSelectionEvent; + + SuspendSelectionEvent = true; + _suspendUpdate = true; + RestoreExpandedNodes(node, list); + //Restore Selection: + _selection.Clear(); + //restore preserved selection. + _selection.AddRange(preservedSelection); + //restore selection for child nodes. + foreach ( var selectionPath in selectionPaths) + { + TreeNodeAdv selectionNode = FindChildNode(node, selectionPath, 0, false); + if (selectionNode != null) + { + selectionNode.SetSelectedInternal(true); + _selection.Add(selectionNode); + } + else + fireSelectionBefore = true; // selection changed. + } + if (currentPath != null) + _currentNode = FindChildNode(node, currentPath, 0, false); + if (selectionStartPath != null) + _selectionStart = FindChildNode(node, selectionStartPath, 0, false); + + _fireSelectionEvent = fireSelectionBefore; + _suspendUpdate = suspendUpdateBefore; + SuspendSelectionEvent = suspendSelectionEventBefore; + UpdateSelection(); SmartFullUpdate(); } @@ -1087,7 +1261,7 @@ private void _model_StructureChanged(object sender, TreePathEventArgs e) private void RestoreExpandedNodes(TreeNodeAdv node, Dictionary list) { - if (node.Tag != null && list.ContainsKey(node.Tag)) + if (node == Root || (node.Tag != null && list.ContainsKey(node.Tag))) //Root.Tag always is null, and Root always expanded { node.IsExpanded = true; foreach (var child in node.Children) @@ -1097,11 +1271,14 @@ private void RestoreExpandedNodes(TreeNodeAdv node, Dictionary l private void SaveExpandedNodes(TreeNodeAdv node, Dictionary list) { - if (node.IsExpanded && node.Tag != null) + var isRoot = node == Root; + if (isRoot || (node.IsExpanded && node.Tag != null)) //Root.Tag always is null, and Root always expanded { - list.Add(node.Tag, null); - foreach (var child in node.Children) - SaveExpandedNodes(child, list); + if (!isRoot) + list.Add(node.Tag, null); + + foreach (var child in node.Children) + SaveExpandedNodes(child, list); } } @@ -1110,31 +1287,38 @@ private void _model_NodesRemoved(object sender, TreeModelEventArgs e) TreeNodeAdv parent = FindNode(e.Path); if (parent != null) { - if (e.Indices != null) + if (parent.IsExpandedOnce) { - List list = new List(e.Indices); - list.Sort(); - for (int n = list.Count - 1; n >= 0; n--) + if (e.Indices != null) { - int index = list[n]; - if (index >= 0 && index <= parent.Nodes.Count) - parent.Nodes.RemoveAt(index); - else - throw new ArgumentOutOfRangeException("Index out of range"); + List list = new List(e.Indices); + list.Sort(); + for (int n = list.Count - 1; n >= 0; n--) + { + int index = list[n]; + if (index >= 0 && index <= parent.Nodes.Count) + parent.Nodes.RemoveAt(index); + else + throw new ArgumentOutOfRangeException("Index out of range"); + } } - } - else - { - for (int i = parent.Nodes.Count - 1; i >= 0; i--) + else { - for (int n = 0; n < e.Children.Length; n++) - if (parent.Nodes[i].Tag == e.Children[n]) - { - parent.Nodes.RemoveAt(i); - break; - } + for (int i = parent.Nodes.Count - 1; i >= 0; i--) + { + for (int n = 0; n < e.Children.Length; n++) + if (parent.Nodes[i].Tag == e.Children[n]) + { + parent.Nodes.RemoveAt(i); + break; + } + } } + if (parent.Nodes.Count == 0) + parent.IsLeaf = Model.IsLeaf(e.Path); } + else + parent.IsLeaf = Model.IsLeaf(e.Path); } UpdateSelection(); SmartFullUpdate(); @@ -1148,8 +1332,13 @@ private void _model_NodesInserted(object sender, TreeModelEventArgs e) TreeNodeAdv parent = FindNode(e.Path); if (parent != null) { - for (int i = 0; i < e.Children.Length; i++) - AddNewNode(parent, e.Children[i], e.Indices[i]); + if (parent.IsExpandedOnce) + { + for (int i = 0; i < e.Children.Length; i++) + AddNewNode(parent, e.Children[i], e.Indices[i]); + } + else if (parent.IsLeaf) + parent.IsLeaf = Model.IsLeaf(e.Path); } SmartFullUpdate(); } diff --git a/External/3rdParty/Aga-1.7/ReleaseNotes.txt b/External/3rdParty/Aga-1.7/ReleaseNotes.txt index c947deae07..2c103f2f32 100644 --- a/External/3rdParty/Aga-1.7/ReleaseNotes.txt +++ b/External/3rdParty/Aga-1.7/ReleaseNotes.txt @@ -1,3 +1,34 @@ +1.7.0.1 (r98) +[r98] Fixed: Issue #44 - tree nodes are now properly saved and restored when 'ITreeModel.StructureChanged' event is raised. +[r97] Fixed: Issue #23, added support for whole page mouse scrolling +[r96] Added: Option to choose custom highlight colors +[r95] Fixed: Issue #48 UseCompatibleTextRendering is backwards +[r94] Added: Option to auto span columns +[r93] Fixed: TreeView control sometimes not being updated when using columns +[r92] Added: Option to Highlight text for BaseTextControl +[r91] Added: custom background paint mode +[r90] Fixed: Incorrect behavior of TreeViewAdv.ColumnHeaderHeight property, logic and design is now separated. +[r89] Option to modify node visibility via callback +[r88] NodeTextBox: Process Enter, Escape Key as Input Key. +[r87] NodesInserted and NodesRemoved events now supports the case, when the parent has not been loaded. +[r86] added ColumnHeaderHeight, AutoHeaderHeight Property. + Used default for AutoHeaderHeight False (not as in patch used). +[r85] When the last child of an item is removed it becomes to be a leaf. in this case, parentNode.Nodes.Clear() was not called and the child is not removed from Nodes list. (bug in ReadChilds method). +[r84] bugfix of bugfix +[r83] Bug while restoring the Selection after StructureChange is now fixed (hopefully definitely). Laurent Nicot, thanks for the detailed feedback and the Test-Case. +[r82] Fixed a bug: selected nodes were not correctly restored after structure change event. +[r81] EnsureVisible(TreeNodeAdv node) does not fail in case the node parameter is the root node. +[r80] Bugfix: StructureChange missed to clear _selection on restore (causing invalid SelectedNode in case the selection path is not found anymore). +[r79] prevent unneeded selection change event on structure change +[r78] Don't reset scroll position on structure change. +[r77] Fix threading problem with _expandingNodes related to AbortBackgroundExpandingThreads() +[r76] - FIX: Redraw when Focus Lost ( to update selection color from active to inactive). +- NEW: Property InactiveSelection on TreeViewAdv to choose if selection gets inactive or not when unfocused. + - FIX: Try to Restore Selection when StructureChanged +[r75] NodeCheckBox has a new Property ReverseCheckOrder: changes the order from Indeterminate, Unchecked, Checked to Indeterminate, Checked, Unchecked. +[r74] TreeViewAdv.cs, TreeViewAdv.Designer.cs: moved and completed Dispose method. Unregister events on dispose to prevent memory-leaks: ExpandingIcon.IconChanged event to static Object was never unregistered -> tree view was not collected by garbage collection until application quits. +[r73] node edit bug + 1.7.0 + EditableNodeControl imroved + NodeCombobox improved diff --git a/External/3rdParty/Aga-1.7/TreeViewAdv.sln b/External/3rdParty/Aga-1.7/TreeViewAdv.sln index 28c2a2e0ce..6e653ae427 100644 --- a/External/3rdParty/Aga-1.7/TreeViewAdv.sln +++ b/External/3rdParty/Aga-1.7/TreeViewAdv.sln @@ -1,6 +1,8 @@  -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C# Express 2008 +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Aga.Controls", "Aga.Controls\Aga.Controls.csproj", "{E73BB233-D88B-44A7-A98F-D71EE158381D}" EndProject Global diff --git a/External/3rdParty/Duplicate/Duplicate.csproj b/External/3rdParty/Duplicate/Duplicate.csproj index 8ac191a7aa..38a487b43e 100644 --- a/External/3rdParty/Duplicate/Duplicate.csproj +++ b/External/3rdParty/Duplicate/Duplicate.csproj @@ -3,8 +3,6 @@ Debug AnyCPU - 9.0.30729 - 2.0 {7AF50A69-26D3-400B-9DFF-96CB36E1A871} Library Properties @@ -14,8 +12,11 @@ - 2.0 - v2.0 + net48 + true + false + false + false @@ -50,14 +51,6 @@ TRACE true - - False diff --git a/External/3rdParty/Scintilla/additional_keywords.patch b/External/3rdParty/Scintilla/additional_keywords.patch index fbf1381ab0..afa80d85ad 100644 --- a/External/3rdParty/Scintilla/additional_keywords.patch +++ b/External/3rdParty/Scintilla/additional_keywords.patch @@ -1,65 +1,65 @@ -diff -r 1092d3d24959 include/SciLexer.h ---- a/include/SciLexer.h Tue Jan 15 09:51:15 2013 +1100 -+++ b/include/SciLexer.h Wed Feb 06 22:13:27 2013 +0100 -@@ -161,6 +161,9 @@ - #define SCE_C_TRIPLEVERBATIM 21 - #define SCE_C_HASHQUOTEDSTRING 22 - #define SCE_C_PREPROCESSORCOMMENT 23 -+#define SCE_C_WORD3 24 -+#define SCE_C_WORD4 25 -+#define SCE_C_WORD5 26 +diff --git a/include/SciLexer.h b/include/SciLexer.h +--- a/include/SciLexer.h ++++ b/include/SciLexer.h +@@ -177,6 +177,9 @@ + #define SCE_C_USERLITERAL 25 + #define SCE_C_TASKMARKER 26 + #define SCE_C_ESCAPESEQUENCE 27 ++#define SCE_C_WORD3 100 ++#define SCE_C_WORD4 101 ++#define SCE_C_WORD5 102 #define SCE_D_DEFAULT 0 #define SCE_D_COMMENT 1 #define SCE_D_COMMENTLINE 2 -diff -r 1092d3d24959 lexers/LexCPP.cxx ---- a/lexers/LexCPP.cxx Tue Jan 15 09:51:15 2013 +1100 -+++ b/lexers/LexCPP.cxx Wed Feb 06 22:13:27 2013 +0100 -@@ -247,6 +247,9 @@ - "Documentation comment keywords", +diff --git a/lexers/LexCPP.cxx b/lexers/LexCPP.cxx +--- a/lexers/LexCPP.cxx ++++ b/lexers/LexCPP.cxx +@@ -353,6 +353,9 @@ "Global classes and typedefs", "Preprocessor definitions", + "Task marker and error marker keywords", + "Extended(1) keywords and identifiers", + "Extended(2) keywords and identifiers", + "Extended(3) keywords and identifiers", 0, }; -@@ -323,6 +326,9 @@ +@@ -443,6 +446,9 @@ WordList keywords2; WordList keywords3; WordList keywords4; -+ WordList keywords5; -+ WordList keywords6; -+ WordList keywords7; ++ WordList keywords5; ++ WordList keywords6; ++ WordList keywords7; WordList ppDefinitions; - std::map preprocessorDefinitionsStart; - OptionsCPP options; -@@ -411,6 +417,15 @@ - case 4: + WordList markerList; + struct SymbolValue { +@@ -587,6 +593,15 @@ wordListN = &ppDefinitions; break; -+ case 5: -+ wordListN = &keywords5; -+ break; -+ case 6: -+ wordListN = &keywords6; -+ break; -+ case 7: -+ wordListN = &keywords7; -+ break; + case 5: ++ wordListN = &keywords5; ++ break; ++ case 6: ++ wordListN = &keywords6; ++ break; ++ case 7: ++ wordListN = &keywords7; ++ break; ++ case 8: + wordListN = &markerList; + break; } - int firstModification = -1; - if (wordListN) { -@@ -605,6 +620,12 @@ +@@ -809,6 +824,12 @@ sc.ChangeState(SCE_C_WORD2|activitySet); } else if (keywords4.InList(s)) { sc.ChangeState(SCE_C_GLOBALCLASS|activitySet); + } else if (keywords5.InList(s)) { -+ sc.ChangeState(SCE_C_WORD3|activitySet); -+ } else if (keywords6.InList(s)) { -+ sc.ChangeState(SCE_C_WORD4|activitySet); -+ } else if (keywords7.InList(s)) { -+ sc.ChangeState(SCE_C_WORD5|activitySet); - } - const bool literalString = sc.ch == '\"'; - if (literalString || sc.ch == '\'') { ++ sc.ChangeState(SCE_C_WORD3|activitySet); ++ } else if (keywords6.InList(s)) { ++ sc.ChangeState(SCE_C_WORD4|activitySet); ++ } else if (keywords7.InList(s)) { ++ sc.ChangeState(SCE_C_WORD5|activitySet); + } else { + int subStyle = classifierIdentifiers.ValueFor(s); + if (subStyle >= 0) { diff --git a/External/3rdParty/Trace/Resources/en_US.resX b/External/3rdParty/Trace/Resources/en_US.resx similarity index 100% rename from External/3rdParty/Trace/Resources/en_US.resX rename to External/3rdParty/Trace/Resources/en_US.resx diff --git a/External/3rdParty/Trace/Trace.csproj b/External/3rdParty/Trace/Trace.csproj index 1ea23c58a1..831f7aa5a3 100644 --- a/External/3rdParty/Trace/Trace.csproj +++ b/External/3rdParty/Trace/Trace.csproj @@ -3,8 +3,6 @@ Debug AnyCPU - 9.0.30729 - 2.0 {78101C01-E186-4954-B1DD-DEBB7905FAD8} Library Properties @@ -14,8 +12,11 @@ - 2.0 - v2.0 + net48 + true + false + false + false @@ -65,14 +66,6 @@ TRACE true - - False @@ -98,7 +91,7 @@ - + Designer diff --git a/External/Archive/FlashDebugger/FlashDebugger.csproj b/External/Archive/FlashDebugger/FlashDebugger.csproj index ae664a224a..27731fd483 100644 --- a/External/Archive/FlashDebugger/FlashDebugger.csproj +++ b/External/Archive/FlashDebugger/FlashDebugger.csproj @@ -3,8 +3,6 @@ Debug AnyCPU - 9.0.30729 - 2.0 {194B58C9-9D2B-4D5E-9256-773FD3222582} Library Properties @@ -14,8 +12,11 @@ - 2.0 - v2.0 + net48 + true + false + false + false @@ -49,14 +50,6 @@ TRACE true - - False @@ -400,7 +393,7 @@ - + Designer diff --git a/External/Archive/FlashDebugger/FlexSDK/FlashDbg/FlashDbg.resX b/External/Archive/FlashDebugger/FlexSDK/FlashDbg/FlashDbg.resx similarity index 100% rename from External/Archive/FlashDebugger/FlexSDK/FlashDbg/FlashDbg.resX rename to External/Archive/FlashDebugger/FlexSDK/FlashDbg/FlashDbg.resx diff --git a/External/Archive/FlashDebugger/FlexSDK/SwfUtils/flash/swf/NotUsed/TagEncoder.cs b/External/Archive/FlashDebugger/FlexSDK/SwfUtils/flash/swf/NotUsed/TagEncoder.cs index f73290ca23..61fa2ef8cb 100644 --- a/External/Archive/FlashDebugger/FlexSDK/SwfUtils/flash/swf/NotUsed/TagEncoder.cs +++ b/External/Archive/FlashDebugger/FlexSDK/SwfUtils/flash/swf/NotUsed/TagEncoder.cs @@ -1,2314 +1,2314 @@ -//////////////////////////////////////////////////////////////////////////////// -// -// ADOBE SYSTEMS INCORPORATED -// Copyright 2003-2007 Adobe Systems Incorporated -// All Rights Reserved. -// -// NOTICE: Adobe permits you to use, modify, and distribute this file -// in accordance with the terms of the license agreement accompanying it. -// -//////////////////////////////////////////////////////////////////////////////// -using System; -using flash.swf.tags; -using ButtonCondAction = flash.swf.types.ButtonCondAction; -using ButtonRecord = flash.swf.types.ButtonRecord; -using CXForm = flash.swf.types.CXForm; -using CXFormWithAlpha = flash.swf.types.CXFormWithAlpha; -using CurvedEdgeRecord = flash.swf.types.CurvedEdgeRecord; -using EdgeRecord = flash.swf.types.EdgeRecord; -using FillStyle = flash.swf.types.FillStyle; -using GlyphEntry = flash.swf.types.GlyphEntry; -using GradRecord = flash.swf.types.GradRecord; -using ImportRecord = flash.swf.types.ImportRecord; -using KerningRecord = flash.swf.types.KerningRecord; -using LineStyle = flash.swf.types.LineStyle; -using MD5 = flash.swf.types.MD5; -using Matrix = flash.swf.types.Matrix; -using MorphFillStyle = flash.swf.types.MorphFillStyle; -using MorphGradRecord = flash.swf.types.MorphGradRecord; -using MorphLineStyle = flash.swf.types.MorphLineStyle; -using Rect = flash.swf.types.Rect; -using Shape = flash.swf.types.Shape; -using ShapeRecord = flash.swf.types.ShapeRecord; -using ShapeWithStyle = flash.swf.types.ShapeWithStyle; -using SoundInfo = flash.swf.types.SoundInfo; -using StraightEdgeRecord = flash.swf.types.StraightEdgeRecord; -using StyleChangeRecord = flash.swf.types.StyleChangeRecord; -using TextRecord = flash.swf.types.TextRecord; -using Filter = flash.swf.types.Filter; -using DropShadowFilter = flash.swf.types.DropShadowFilter; -using BlurFilter = flash.swf.types.BlurFilter; -using ColorMatrixFilter = flash.swf.types.ColorMatrixFilter; -using GlowFilter = flash.swf.types.GlowFilter; -using ConvolutionFilter = flash.swf.types.ConvolutionFilter; -using BevelFilter = flash.swf.types.BevelFilter; -using GradientGlowFilter = flash.swf.types.GradientGlowFilter; -using GradientBevelFilter = flash.swf.types.GradientBevelFilter; -using Gradient = flash.swf.types.Gradient; -using FocalGradient = flash.swf.types.FocalGradient; -namespace flash.swf -{ - - public class TagEncoder:TagHandler, TagValues - { - virtual public int Pos - { - get - { - return writer.Pos; - } - - } - virtual protected internal int SwfVersion - { - get - { - return header_Renamed_Field.version; - } - - } - virtual protected internal int FrameRate - { - get - { - return header_Renamed_Field.rate; - } - - } - virtual public Dictionary EncoderDictionary - { - set - { - assert((this.dict == null) || (this.dict.ids.Count == 0)); - this.dict = value; - } - - } - virtual public Dictionary Dictionary - { - get - { - return dict; - } - - } - virtual public bool Debug - { - get - { - return debug != null; - } - - } - virtual public int Width - { - get - { - return width / 20; - } - - } - virtual public int Height - { - get - { - return height / 20; - } - - } - virtual public System.String MainDebugScript - { - set - { - debug.MainDebugScript = value; - } - - } - override public SetBackgroundColor BackgroundColor - { - set - { - encodeTagHeader(value.code, 3, false); - encodeRGB(value.color, writer); - } - - } - override public SetTabIndex TabIndex - { - set - { - tagw.writeUI16(value.depth); - tagw.writeUI16(value.index); - encodeTag(value); - } - - } - // changed from private to protected to support Flash Authoring - jkamerer 2007.07.30 - protected internal SwfEncoder writer; - private SwfEncoder tagw; - private int width; - private int height; - private int frames; - private int framecountPos; - private DebugEncoder debug; - private Header header_Renamed_Field; - - protected internal Dictionary dict; - private int uuidOffset; - - public TagEncoder() - { - dict = new Dictionary(); - } - - public TagEncoder(Dictionary dict) - { - this.dict = dict; - } - - public override void productInfo(ProductInfo tag) - { - tagw.write32(tag.Product); - tagw.write32(tag.Edition); - tagw.write(new sbyte[]{tag.MajorVersion, tag.MinorVersion}); - tagw.write64(tag.Build); - tagw.write64(tag.CompileDate); - encodeTag(tag); - } - - public override void fileAttributes(FileAttributes tag) - { - tagw.writeUBits(0, 3); - tagw.writeBit(tag.hasMetadata); - tagw.writeBit(tag.actionScript3); - tagw.writeBit(tag.suppressCrossDomainCaching); - tagw.writeBit(tag.swfRelativeUrls); - tagw.writeBit(tag.useNetwork); - tagw.writeUBits(0, 24); - encodeTag(tag); - } - - public override void metadata(Metadata tag) - { - tagw.writeString(tag.xml); - encodeTag(tag); - } - - protected internal virtual SwfEncoder createEncoder(int swfVersion) - { - return new SwfEncoder(swfVersion); - } - - public override void header(Header header) - { - // get some header properties we need to know - int swfVersion = header.version; - this.header_Renamed_Field = header; - this.writer = createEncoder(swfVersion); - this.tagw = createEncoder(swfVersion); - width = header.size.Width; - height = header.size.Height; - frames = 0; - - // write the header - writer.writeUI8(header.compressed?'C':'F'); - writer.writeUI8('W'); - writer.writeUI8('S'); - writer.writeUI8(header.version); - writer.write32((int) header.length); - if (header.compressed) - { - writer.markComp(); - } - encodeRect(header.size, writer); - writer.writeUI8(header.rate >> 8); - writer.writeUI8(header.rate & 255); - framecountPos = writer.Pos; - writer.writeUI16(header.framecount); - } - - public override void finish() - { - // write end marker - writer.writeUI16(0); - - // update the length - writer.write32at(4, writer.Pos); - - // update the frame count - writer.writeUI16at(framecountPos, frames); - - if (debug != null) - { - // compute a crc and use it for the debug id. that way it - // is wholly dependent on the bytes in the SWF and not some - // outside value. If any of the bytes are different, - // then the UUID will be different. - sbyte[] md5 = MD5.getDigest(writer.ByteArray, writer.Length); - writer.writeAt(uuidOffset, md5); - debug.updateUUID(md5); - } - } - - public virtual void writeTo(System.IO.Stream out_Renamed) - { - writer.WriteTo(out_Renamed); - } - - - public virtual void writeDebugTo(System.IO.Stream out_Renamed) - { - debug.writeTo(out_Renamed); - } - - public virtual void encodeRect(Rect r, SwfEncoder w) - { - int nBits = r.nbits(); - w.writeUBits(nBits, 5); - w.writeSBits(r.xMin, nBits); - w.writeSBits(r.xMax, nBits); - w.writeSBits(r.yMin, nBits); - w.writeSBits(r.yMax, nBits); - w.flushBits(); - } - - public override void debugID(DebugID tag) - { - encodeTagHeader(tag.code, tag.uuid.bytes.Length, false); - uuidOffset = writer.Pos; - writer.write(tag.uuid.bytes); - - debug = new DebugEncoder(); - debug.header(SwfVersion); - debug.uuid(tag.uuid); - } - - private void encodeTag(Tag tag) - { - try - { - tagw.compress(); - encodeTagHeader(tag.code, tagw.Pos, isLongHeader(tag)); - tagw.WriteTo(writer); - tagw.reset(); - } - catch (System.IO.IOException e) - { - assert(false); - } - } - - private bool isLongHeader(Tag t) - { - switch (t.code) - { - - // [preilly] In the player code, ScriptThread::DefineBits() assumes all DefineBits - // tags use a long header. See "ch->data = AttachData(pos-8);". If the player - // also supported a short header, it would use "pos-4". - case flash.swf.TagValues_Fields.stagDefineBits: - case flash.swf.TagValues_Fields.stagDefineBitsJPEG2: - case flash.swf.TagValues_Fields.stagDefineBitsJPEG3: - case flash.swf.TagValues_Fields.stagDefineBitsLossless: - case flash.swf.TagValues_Fields.stagDefineBitsLossless2: - return true; - - // [ed] the FlashPaper codebase also indicates that stagSoundStreamBlock must use - // a long format header. todo - verify by looking at the player code. - - case flash.swf.TagValues_Fields.stagSoundStreamBlock: - return true; - - // [edsmith] these tags have code in them. When we're writing a SWD, we use long headers - // so we can predict SWF offsets correctly when writing SWD line/offset records. - - case flash.swf.TagValues_Fields.stagDefineButton: - case flash.swf.TagValues_Fields.stagDefineButton2: - case flash.swf.TagValues_Fields.stagDefineSprite: - case flash.swf.TagValues_Fields.stagDoInitAction: - case flash.swf.TagValues_Fields.stagDoAction: - return Debug; - - - case flash.swf.TagValues_Fields.stagPlaceObject2: - return Debug && ((PlaceObject) t).hasClipAction(); - - // all other tags will use short/long headers depending on their length - - default: - return false; - - } - } - - private void encodeTagHeader(int code, int length, bool longHeader) - { - if (longHeader || length >= 63) - { - writer.writeUI16((code << 6) | 63); - writer.write32(length); - } - else - { - writer.writeUI16((code << 6) | length); - } - } - - public override void defineScalingGrid(DefineScalingGrid tag) - { - int idref = dict.getId(tag.scalingTarget); - tagw.writeUI16(idref); - encodeRect(tag.rect, tagw); - encodeTag(tag); - } - - public override void defineBinaryData(DefineBinaryData tag) - { - encodeTagHeader(tag.code, 6 + tag.data.Length, false); - int id = dict.add(tag); - writer.writeUI16(id); - writer.write32(tag.reserved); - writer.write(tag.data); - } - - public override void defineBits(DefineBits tag) - { - encodeTagHeader(tag.code, 2 + tag.data.Length, true); - int id = dict.add(tag); - writer.writeUI16(id); - writer.write(tag.data); - } - - public override void defineBitsJPEG2(DefineBits tag) - { - defineBits(tag); - } - - public override void defineBitsJPEG3(DefineBitsJPEG3 tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - tagw.write32(tag.data.Length); - tagw.write(tag.data); - tagw.markComp(); - tagw.write(tag.alphaData); - encodeTag(tag); - } - - public override void defineBitsLossless(DefineBitsLossless tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - tagw.writeUI8(tag.format); - tagw.writeUI16(tag.width); - tagw.writeUI16(tag.height); - switch (tag.format) - { - - case 3: - tagw.writeUI8(tag.colorData.Length - 1); - tagw.markComp(); - encodeColorMapData(tag.colorData, tag.data, tagw); - break; - - case 4: - case 5: - tagw.markComp(); - encodeBitmapData(tag.data, tagw); - break; - } - encodeTag(tag); - } - - private void encodeBitmapData(sbyte[] data, SwfEncoder w) - { - w.write(data); - } - - private void encodeColorMapData(int[] colorData, sbyte[] pixelData, SwfEncoder w) - { - for (int i = 0; i < colorData.Length; i++) - { - encodeRGB(colorData[i], w); - } - w.write(pixelData); - } - - /// as 0x00RRGGBB - /// - /// - /// - private void encodeRGB(int rgb, SwfEncoder w) - { - w.writeUI8(SupportClass.URShift(rgb, 16)); // red. we don't mask this because if rgb has an Alpha value, something's wrong - w.writeUI8((SupportClass.URShift(rgb, 8)) & 255); - w.writeUI8(rgb & 255); // blue - } - - public override void defineBitsLossless2(DefineBitsLossless tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - tagw.writeUI8(tag.format); - tagw.writeUI16(tag.width); - tagw.writeUI16(tag.height); - switch (tag.format) - { - - case 3: - tagw.writeUI8(tag.colorData.Length - 1); - tagw.markComp(); - encodeAlphaColorMapData(tag.colorData, tag.data, tagw); - break; - - case 4: - case 5: - tagw.markComp(); - encodeBitmapData(tag.data, tagw); - break; - } - encodeTag(tag); - } - - private void encodeAlphaColorMapData(int[] colorData, sbyte[] pixelData, SwfEncoder w) - { - for (int i = 0; i < colorData.Length; i++) - { - encodeRGBA(colorData[i], w); - } - w.write(pixelData); - } - - /// as 0xAARRGGBB - /// - /// - /// - private void encodeRGBA(int rgba, SwfEncoder w) - { - w.writeUI8((SupportClass.URShift(rgba, 16)) & 255); // red - w.writeUI8((SupportClass.URShift(rgba, 8)) & 255); // green - w.writeUI8(rgba & 255); // blue - w.writeUI8(SupportClass.URShift(rgba, 24)); // alpha - } - - public override void defineButton(DefineButton tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - - if (Debug) - { - debug.adjust = writer.Pos + 6; - } - - for (int i = 0; i < tag.buttonRecords.Length; i++) - { - encodeButtonRecord(tag.buttonRecords[i], tagw, tag.code); - } - tagw.writeUI8(0); // no more button records - - // assume there is only one condition we will handle - new ActionEncoder(tagw, debug).encode(tag.condActions[0].actionList); - tagw.writeUI8(0); // write action end flag, must be zero - encodeTag(tag); - - if (Debug) - { - debug.adjust = 0; - } - } - - private void encodeButtonRecord(ButtonRecord record, SwfEncoder w, int defineButton) - { - if (defineButton == flash.swf.TagValues_Fields.stagDefineButton2) - { - w.writeUBits(0, 2); - w.writeBit(record.blendMode != - 1); - w.writeBit(record.filters != null); - } - else - { - w.writeUBits(0, 4); - } - w.writeBit(record.hitTest); - w.writeBit(record.down); - w.writeBit(record.over); - w.writeBit(record.up); - - w.writeUI16(dict.getId(record.characterRef)); - w.writeUI16(record.placeDepth); - encodeMatrix(record.placeMatrix, w); - - if (defineButton == flash.swf.TagValues_Fields.stagDefineButton2) - { - encodeCxforma(record.colorTransform, w); - if (record.filters != null) - { - this.encodeFilterList(record.filters, w); - } - if (record.blendMode != - 1) - { - w.writeUI8(record.blendMode); - } - } - } - - private void encodeCxforma(CXFormWithAlpha cxforma, SwfEncoder w) - { - w.writeBit(cxforma.hasAdd); - w.writeBit(cxforma.hasMult); - - int nbits = cxforma.nbits(); - w.writeUBits(nbits, 4); - - if (cxforma.hasMult) - { - w.writeSBits(cxforma.redMultTerm, nbits); - w.writeSBits(cxforma.greenMultTerm, nbits); - w.writeSBits(cxforma.blueMultTerm, nbits); - w.writeSBits(cxforma.alphaMultTerm, nbits); - } - - if (cxforma.hasAdd) - { - w.writeSBits(cxforma.redAddTerm, nbits); - w.writeSBits(cxforma.greenAddTerm, nbits); - w.writeSBits(cxforma.blueAddTerm, nbits); - w.writeSBits(cxforma.alphaAddTerm, nbits); - } - - w.flushBits(); - } - - private void encodeMatrix(Matrix matrix, SwfEncoder w) - { - w.writeBit(matrix.hasScale); - if (matrix.hasScale) - { - int nScaleBits = matrix.nScaleBits(); - w.writeUBits(nScaleBits, 5); - w.writeSBits(matrix.scaleX, nScaleBits); - w.writeSBits(matrix.scaleY, nScaleBits); - } - - w.writeBit(matrix.hasRotate); - if (matrix.hasRotate) - { - int nRotateBits = matrix.nRotateBits(); - w.writeUBits(nRotateBits, 5); - w.writeSBits(matrix.rotateSkew0, nRotateBits); - w.writeSBits(matrix.rotateSkew1, nRotateBits); - } - - int nTranslateBits = matrix.nTranslateBits(); - w.writeUBits(nTranslateBits, 5); - w.writeSBits(matrix.translateX, nTranslateBits); - w.writeSBits(matrix.translateY, nTranslateBits); - - w.flushBits(); - } - - public override void defineButton2(DefineButton tag) - { - if (Debug) - { - debug.adjust = writer.Pos + 6; - } - - int id = dict.add(tag); - tagw.writeUI16(id); - tagw.writeUBits(0, 7); // reserved - tagw.writeBit(tag.trackAsMenu); - int offsetPos = tagw.Pos; - tagw.writeUI16(0); // actionOffset - - for (int i = 0; i < tag.buttonRecords.Length; i++) - { - encodeButtonRecord(tag.buttonRecords[i], tagw, tag.code); - } - - tagw.writeUI8(0); // charEndFlag - - if (tag.condActions.Length > 0) - { - tagw.writeUI16at(offsetPos, tagw.Pos - offsetPos); - - for (int i = 0; i < tag.condActions.Length; i++) - { - bool isLast = i + 1 == tag.condActions.Length; - encodeButtonCondAction(tag.condActions[i], tagw, isLast); - } - } - encodeTag(tag); - - if (Debug) - { - debug.adjust = 0; - } - } - - private void encodeButtonCondAction(ButtonCondAction condAction, SwfEncoder w, bool last) - { - int pos = w.Pos; - w.writeUI16(0); - - w.writeUBits(condAction.keyPress, 7); - w.writeBit(condAction.overDownToIdle); - - w.writeBit(condAction.idleToOverDown); - w.writeBit(condAction.outDownToIdle); - w.writeBit(condAction.outDownToOverDown); - w.writeBit(condAction.overDownToOutDown); - w.writeBit(condAction.overDownToOverUp); - w.writeBit(condAction.overUpToOverDown); - w.writeBit(condAction.overUpToIdle); - w.writeBit(condAction.idleToOverUp); - - new ActionEncoder(w, debug).encode(condAction.actionList); - w.writeUI8(0); // end action byte - - if (!last) - { - w.writeUI16at(pos, w.Pos - pos); - } - } - - public override void defineButtonCxform(DefineButtonCxform tag) - { - int idref = dict.getId(tag.button); - tagw.writeUI16(idref); - encodeCxform(tag.colorTransform, tagw); - encodeTag(tag); - } - - private void encodeCxform(CXForm cxform, SwfEncoder w) - { - - w.writeBit(cxform.hasAdd); - w.writeBit(cxform.hasMult); - - int nbits = cxform.nbits(); - w.writeUBits(nbits, 4); - - if (cxform.hasMult) - { - w.writeSBits(cxform.redMultTerm, nbits); - w.writeSBits(cxform.greenMultTerm, nbits); - w.writeSBits(cxform.blueMultTerm, nbits); - } - - if (cxform.hasAdd) - { - w.writeSBits(cxform.redAddTerm, nbits); - w.writeSBits(cxform.greenAddTerm, nbits); - w.writeSBits(cxform.blueAddTerm, nbits); - } - - w.flushBits(); - } - - public override void defineButtonSound(DefineButtonSound tag) - { - int idref = dict.getId(tag.button); - tagw.writeUI16(idref); - if (tag.sound0 != null) - { - tagw.writeUI16(dict.getId(tag.sound0)); - encodeSoundInfo(tag.info0, tagw); - } - else - { - tagw.writeUI16(0); - } - if (tag.sound1 != null) - { - tagw.writeUI16(dict.getId(tag.sound1)); - encodeSoundInfo(tag.info1, tagw); - } - else - { - tagw.writeUI16(0); - } - if (tag.sound2 != null) - { - tagw.writeUI16(dict.getId(tag.sound2)); - encodeSoundInfo(tag.info2, tagw); - } - else - { - tagw.writeUI16(0); - } - if (tag.sound3 != null) - { - tagw.writeUI16(dict.getId(tag.sound3)); - encodeSoundInfo(tag.info3, tagw); - } - else - { - tagw.writeUI16(0); - } - encodeTag(tag); - } - - private void encodeSoundInfo(SoundInfo info, SwfEncoder w) - { - w.writeUBits(0, 2); // reserved - w.writeBit(info.syncStop); - w.writeBit(info.syncNoMultiple); - w.writeBit(info.records != null); - w.writeBit(info.loopCount != SoundInfo.UNINITIALIZED); - w.writeBit(info.outPoint != SoundInfo.UNINITIALIZED); - w.writeBit(info.inPoint != SoundInfo.UNINITIALIZED); - - if (info.inPoint != SoundInfo.UNINITIALIZED) - { - w.write32((int) info.inPoint); - } - if (info.outPoint != SoundInfo.UNINITIALIZED) - { - w.write32((int) info.outPoint); - } - if (info.loopCount != SoundInfo.UNINITIALIZED) - { - w.writeUI16(info.loopCount); - } - if (info.records != null) - { - w.writeUI8(info.records.Length); - for (int k = 0; k < info.records.Length; k++) - { - w.write64(info.records[k]); - } - } - } - - public override void defineEditText(DefineEditText tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - encodeRect(tag.bounds, tagw); - - tagw.writeBit(tag.hasText); - tagw.writeBit(tag.wordWrap); - tagw.writeBit(tag.multiline); - tagw.writeBit(tag.password); - tagw.writeBit(tag.readOnly); - tagw.writeBit(tag.hasTextColor); - tagw.writeBit(tag.hasMaxLength); - tagw.writeBit(tag.hasFont); - - tagw.writeBit(false); // reserved - tagw.writeBit(tag.autoSize); - tagw.writeBit(tag.hasLayout); - tagw.writeBit(tag.noSelect); - tagw.writeBit(tag.border); - tagw.writeBit(tag.wasStatic); - tagw.writeBit(tag.html); - tagw.writeBit(tag.useOutlines); - - tagw.flushBits(); - - if (tag.hasFont) - { - int idref = dict.getId(tag.font); - tagw.writeUI16(idref); - tagw.writeUI16(tag.height); - } - - if (tag.hasTextColor) - { - encodeRGBA(tag.color, tagw); - } - - if (tag.hasMaxLength) - { - tagw.writeUI16(tag.maxLength); - } - - if (tag.hasLayout) - { - tagw.writeUI8(tag.align); - tagw.writeUI16(tag.leftMargin); - tagw.writeUI16(tag.rightMargin); - tagw.writeUI16(tag.ident); - tagw.writeSI16(tag.leading); // see errata, leading is signed - } - - tagw.writeString(tag.varName); - if (tag.hasText) - { - tagw.writeString(tag.initialText); - } - encodeTag(tag); - } - - public override void defineFont(DefineFont1 tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - - int count = tag.glyphShapeTable.Length; - - int offsetPos = tagw.Pos; - - // write offset placeholders - for (int i = 0; i < count; i++) - { - tagw.writeUI16(0); - } - - // now write glyphs and update the encoded offset table - for (int i = 0; i < count; i++) - { - tagw.writeUI16at(offsetPos + 2 * i, tagw.Pos - offsetPos); - encodeShape(tag.glyphShapeTable[i], tagw, flash.swf.TagValues_Fields.stagDefineShape3, 1, 0); - } - - encodeTag(tag); - } - - public virtual void encodeShape(Shape s, SwfEncoder w, int shape, int nFillStyles, int nLineStyles) - { - int[] numFillBits = new int[]{SwfEncoder.minBits(nFillStyles, 0)}; - int[] numLineBits = new int[]{SwfEncoder.minBits(nLineStyles, 0)}; - - w.writeUBits(numFillBits[0], 4); - w.writeUBits(numLineBits[0], 4); - - System.Collections.IEnumerator it = s.shapeRecords.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" - while (it.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" - ShapeRecord record = (ShapeRecord) it.Current; - if (record is StyleChangeRecord) - { - // style change - w.writeBit(false); - StyleChangeRecord change = (StyleChangeRecord) record; - encodeStyleChangeRecord(w, change, numFillBits, numLineBits, shape); - } - else - { - // edge - w.writeBit(true); - EdgeRecord e = (EdgeRecord) record; - bool straight = e is StraightEdgeRecord; - w.writeBit(straight); - int nbits = straight?calcBits((StraightEdgeRecord) e):calcBits((CurvedEdgeRecord) e); - if (nbits < 2) - nbits = 2; - w.writeUBits(nbits - 2, 4); - if (straight) - { - // line - StraightEdgeRecord line = (StraightEdgeRecord) e; - encodeStraightEdgeRecord(line, w, nbits); - } - else - { - // curve - CurvedEdgeRecord curve = (CurvedEdgeRecord) e; - w.writeSBits(curve.controlDeltaX, nbits); - w.writeSBits(curve.controlDeltaY, nbits); - w.writeSBits(curve.anchorDeltaX, nbits); - w.writeSBits(curve.anchorDeltaY, nbits); - } - } - } - - // endshaperecord - w.writeUBits(0, 6); - - w.flushBits(); - } - - private int calcBits(StraightEdgeRecord edge) - { - return SwfEncoder.minBits(SwfEncoder.maxNum(edge.deltaX, edge.deltaY, 0, 0), 1); - } - - private int calcBits(CurvedEdgeRecord edge) - { - return SwfEncoder.minBits(SwfEncoder.maxNum(edge.controlDeltaX, edge.controlDeltaY, edge.anchorDeltaX, edge.anchorDeltaY), 1); - } - - private void encodeStraightEdgeRecord(StraightEdgeRecord line, SwfEncoder w, int nbits) - { - if (line.deltaX == 0) - { - w.writeUBits(1, 2); // vertical line - w.writeSBits(line.deltaY, nbits); - } - else if (line.deltaY == 0) - { - w.writeUBits(0, 2); // horizontal line - w.writeSBits(line.deltaX, nbits); - } - else - { - w.writeBit(true); // general line - w.writeSBits(line.deltaX, nbits); - w.writeSBits(line.deltaY, nbits); - } - } - - private void encodeStyleChangeRecord(SwfEncoder w, StyleChangeRecord s, int[] numFillBits, int[] numLineBits, int shape) - { - w.writeBit(s.stateNewStyles); - w.writeBit(s.stateLineStyle); - w.writeBit(s.stateFillStyle1); - w.writeBit(s.stateFillStyle0); - w.writeBit(s.stateMoveTo); - - if (s.stateMoveTo) - { - int moveBits = s.nMoveBits(); - w.writeUBits(moveBits, 5); - w.writeSBits(s.moveDeltaX, moveBits); - w.writeSBits(s.moveDeltaY, moveBits); - } - - if (s.stateFillStyle0) - { - w.writeUBits(s.fillstyle0, numFillBits[0]); - } - - if (s.stateFillStyle1) - { - w.writeUBits(s.fillstyle1, numFillBits[0]); - } - - if (s.stateLineStyle) - { - w.writeUBits(s.linestyle, numLineBits[0]); - } - - if (s.stateNewStyles) - { - w.flushBits(); - - encodeFillstyles(s.fillstyles, w, shape); - encodeLinestyles(s.linestyles, w, shape); - - numFillBits[0] = SwfEncoder.minBits(s.fillstyles.Count, 0); - numLineBits[0] = SwfEncoder.minBits(s.linestyles.Count, 0); - w.writeUBits(numFillBits[0], 4); - w.writeUBits(numLineBits[0], 4); - } - } - - private void encodeLinestyles(System.Collections.ArrayList linestyles, SwfEncoder w, int shape) - { - int count = linestyles.Count; - if (count > 0xFF) - { - w.writeUI8(0xFF); - w.writeUI16(count); - } - else - { - w.writeUI8(count); - } - - for (int i = 0; i < count; i++) - { - encodeLineStyle((LineStyle) linestyles[i], w, shape); - } - } - - private void encodeLineStyle(LineStyle lineStyle, SwfEncoder w, int shape) - { - w.writeUI16(lineStyle.width); - - if (shape == flash.swf.TagValues_Fields.stagDefineShape6) - { - w.writeUI16(lineStyle.flags); - if (lineStyle.hasMiterJoint()) - w.writeUI16(lineStyle.miterLimit); - } - - if (shape == flash.swf.TagValues_Fields.stagDefineShape6 && lineStyle.hasFillStyle()) - { - encodeFillStyle(lineStyle.fillStyle, w, shape); - } - else if ((shape == flash.swf.TagValues_Fields.stagDefineShape3) || (shape == flash.swf.TagValues_Fields.stagDefineShape6)) - { - encodeRGBA(lineStyle.color, w); - } - else - { - encodeRGB(lineStyle.color, w); - } - } - - private void encodeFillstyles(System.Collections.ArrayList fillstyles, SwfEncoder w, int shape) - { - int count = fillstyles.Count; - if (count >= 0xFF) - { - w.writeUI8(0xFF); - w.writeUI16(count); - } - else - { - w.writeUI8(count); - } - - System.Collections.IEnumerator it = fillstyles.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" - while (it.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" - FillStyle style = (FillStyle) it.Current; - encodeFillStyle(style, w, shape); - } - } - - private void encodeFillStyle(FillStyle style, SwfEncoder w, int shape) - { - w.writeUI8(style.type); - switch (style.type) - { - - case FillStyle.FILL_SOLID: // 0x00 - if ((shape == flash.swf.TagValues_Fields.stagDefineShape3) || (shape == flash.swf.TagValues_Fields.stagDefineShape6)) - encodeRGBA(style.color, w); - else - encodeRGB(style.color, w); - break; - - case FillStyle.FILL_GRADIENT: - // 0x10 linear gradient fill - case FillStyle.FILL_RADIAL_GRADIENT: - // 0x12 radial gradient fill - case FillStyle.FILL_FOCAL_RADIAL_GRADIENT: // 0x13 focal radial gradient fill - encodeMatrix(style.matrix, w); - encodeGradient(style.gradient, w, shape); - break; - - case FillStyle.FILL_BITS: - // 0x40 tiled bitmap fill - case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP): - // 0x41 clipped bitmap fill - case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_NOSMOOTH): - // 0x42 tiled non-smoothed fill - case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP | FillStyle.FILL_BITS_NOSMOOTH): // 0x43 clipped non-smoothed fill - w.writeUI16(dict.getId(style.bitmap)); - encodeMatrix(style.matrix, w); - break; - } - } - - private void encodeGradient(Gradient gradient, SwfEncoder w, int shape) - { - w.writeUBits(gradient.spreadMode, 2); - w.writeUBits(gradient.interpolationMode, 2); - w.writeUBits(gradient.records.Length, 4); - for (int i = 0; i < gradient.records.Length; i++) - { - encodeGradRecord(gradient.records[i], w, shape); - } - if (gradient is FocalGradient) - { - w.writeFixed8(((FocalGradient) gradient).focalPoint); - } - } - - private void encodeGradRecord(GradRecord record, SwfEncoder w, int shape) - { - w.writeUI8(record.ratio); - if ((shape == flash.swf.TagValues_Fields.stagDefineShape3) || (shape == flash.swf.TagValues_Fields.stagDefineShape6)) - encodeRGBA(record.color, w); - else - encodeRGB(record.color, w); - } - - public override void defineFont2(DefineFont2 tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - int startPos = tagw.Pos; - bool again; - - if (tag.code == flash.swf.TagValues_Fields.stagDefineFont3) - { - tag.wideCodes = true; - } - - if (!tag.wideCodes) - { - for (int i = 0; i < tag.codeTable.Length; i++) - { - if (tag.codeTable[i] > 255) - { - tag.wideCodes = true; - break; - } - } - } - - //UPGRADE_NOTE: Label 'loop' was moved. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1014'" - do - { - again = false; - tagw.writeBit(tag.hasLayout); - tagw.writeBit(tag.shiftJIS); - tagw.writeBit(tag.smallText); - tagw.writeBit(tag.ansi); - tagw.writeBit(tag.wideOffsets); - tagw.writeBit(tag.wideCodes); - tagw.writeBit(tag.italic); - tagw.writeBit(tag.bold); - tagw.flushBits(); - - tagw.writeUI8(tag.langCode); - - tagw.writeLengthString(tag.fontName); - int count = tag.glyphShapeTable.Length; - - tagw.writeUI16(count); - int offsetPos = tagw.Pos; - - // save space for the offset table - if (tag.wideOffsets) - { - for (int i = 0; i < count; i++) - { - tagw.write32(0); - } - } - else - { - for (int i = 0; i < count; i++) - { - tagw.writeUI16(0); - } - } - - //PJF: write placeholder for codeTableOffset, this will be changed after shapes encoded - if (count > 0) - { - if (tag.wideOffsets) - { - tagw.write32(0); - } - else - { - tagw.writeUI16(0); - } - } - - for (int i = 0; i < count; i++) - { - // save offset to this glyph - int offset = tagw.Pos - offsetPos; - if (!tag.wideOffsets && offset > 65535) - { - again = true; - tag.wideOffsets = true; - tagw.Pos = startPos; - //UPGRADE_NOTE: Labeled continue statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1015'" - goto loop; - } - if (tag.wideOffsets) - tagw.write32at(offsetPos + 4 * i, offset); - else - tagw.writeUI16at(offsetPos + 2 * i, offset); - - encodeShape(tag.glyphShapeTable[i], tagw, flash.swf.TagValues_Fields.stagDefineShape3, 1, 0); - } - - // update codeTableOffset - int offset2 = tagw.Pos - offsetPos; - if (!tag.wideOffsets && offset2 > 65535) - { - again = true; - tag.wideOffsets = true; - tagw.Pos = startPos; - //UPGRADE_NOTE: Labeled continue statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1015'" - goto loop; - } - if (tag.wideOffsets) - { - tagw.write32at(offsetPos + 4 * count, offset2); - } - else - { - tagw.writeUI16at(offsetPos + 2 * count, offset2); - } - - // now write the codetable - - if (tag.wideCodes) - { - for (int i = 0; i < tag.codeTable.Length; i++) - { - tagw.writeUI16(tag.codeTable[i]); - } - } - else - { - for (int i = 0; i < tag.codeTable.Length; i++) - { - tagw.writeUI8(tag.codeTable[i]); - } - } - - if (tag.hasLayout) - { - tagw.writeSI16(tag.ascent); - tagw.writeSI16(tag.descent); - tagw.writeSI16(tag.leading); - - for (int i = 0; i < tag.advanceTable.Length; i++) - { - tagw.writeSI16(tag.advanceTable[i]); - } - - for (int i = 0; i < tag.boundsTable.Length; i++) - { - encodeRect(tag.boundsTable[i], tagw); - } - - tagw.writeUI16(tag.kerningTable.Length); - - for (int i = 0; i < tag.kerningTable.Length; i++) - { - if (!tag.wideCodes && ((tag.kerningTable[i].code1 > 255) || (tag.kerningTable[i].code2 > 255))) - { - again = true; - tag.wideCodes = true; - tagw.Pos = startPos; - //UPGRADE_NOTE: Labeled continue statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1015'" - goto loop; - } - - encodeKerningRecord(tag.kerningTable[i], tagw, tag.wideCodes); - } - } - //UPGRADE_NOTE: Label 'loop' was moved. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1014'" -loop: ; - } - while (again); - - encodeTag(tag); - } - - public override void defineFont3(DefineFont3 tag) - { - defineFont2(tag); - } - - public override void defineFont4(DefineFont4 tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - - tagw.writeUBits(0, 5); // reserved - tagw.writeBit(tag.hasFontData); - //tagw.writeBit(tag.smallText); - tagw.writeBit(tag.italic); - tagw.writeBit(tag.bold); - tagw.flushBits(); - - //tagw.writeUI8(tag.langCode); - tagw.writeString(tag.fontName); - if (tag.hasFontData) - { - tagw.write(tag.data); - } - - encodeTag(tag); - } - - public override void defineFontAlignZones(DefineFontAlignZones tag) - { - int fontID = dict.getId(tag.font); - tagw.writeUI16(fontID); - tagw.writeUBits(tag.csmTableHint, 2); - tagw.writeUBits(0, 6); // reserved - for (int i = 0; i < tag.zoneTable.Length; i++) - { - ZoneRecord record = tag.zoneTable[i]; - tagw.writeUI8(record.numZoneData); - for (int j = 0; j < record.numZoneData; j++) - { - tagw.write32((int) record.zoneData[j]); - } - tagw.writeUI8(record.zoneMask); - } - encodeTag(tag); - } - - public override void csmTextSettings(CSMTextSettings tag) - { - int textID = 0; - if (tag.textReference != null) - { - textID = dict.getId(tag.textReference); - } - tagw.writeUI16(textID); - tagw.writeUBits(tag.styleFlagsUseSaffron, 2); - tagw.writeUBits(tag.gridFitType, 3); - tagw.writeUBits(0, 3); // reserved - // FIXME: thickness/sharpness should be written out as 32 bit IEEE Single Precision format in little Endian - tagw.writeUBits((int) tag.thickness, 32); - tagw.writeUBits((int) tag.sharpness, 32); - tagw.writeUBits(0, 8); //reserved - - encodeTag(tag); - } - - public override void defineFontName(DefineFontName tag) - { - int fontID = dict.getId(tag.font); - tagw.writeUI16(fontID); - if (tag.fontName != null) - { - tagw.writeString(tag.fontName); - } - else - { - tagw.writeString(""); - } - if (tag.copyright != null) - { - tagw.writeString(tag.copyright); - } - else - { - tagw.writeString(""); - } - - encodeTag(tag); - } - - private void encodeKerningRecord(KerningRecord kerningRecord, SwfEncoder w, bool wideCodes) - { - if (wideCodes) - { - w.writeUI16(kerningRecord.code1); - w.writeUI16(kerningRecord.code2); - } - else - { - w.writeUI8(kerningRecord.code1); - w.writeUI8(kerningRecord.code2); - } - w.writeUI16(kerningRecord.adjustment); - } - - public override void defineFontInfo(DefineFontInfo tag) - { - int idref = dict.getId(tag.font); - tagw.writeUI16(idref); - - tagw.writeLengthString(tag.name); - - tagw.writeUBits(0, 3); // reserved - tagw.writeBit(tag.shiftJIS); - tagw.writeBit(tag.ansi); - tagw.writeBit(tag.italic); - tagw.writeBit(tag.bold); - - if (tag.code == flash.swf.TagValues_Fields.stagDefineFontInfo2) - { - tagw.writeBit(tag.wideCodes = true); - tagw.writeUI8(tag.langCode); - } - else - { - if (!tag.wideCodes) - { - for (int i = 0; i < tag.codeTable.Length; i++) - { - if (tag.codeTable[i] > 255) - { - tag.wideCodes = true; - break; - } - } - } - tagw.writeBit(tag.wideCodes); - } - - if (tag.wideCodes) - { - for (int i = 0; i < tag.codeTable.Length; i++) - tagw.writeUI16(tag.codeTable[i]); - } - else - { - for (int i = 0; i < tag.codeTable.Length; i++) - tagw.writeUI8(tag.codeTable[i]); - } - encodeTag(tag); - } - - public override void defineFontInfo2(DefineFontInfo tag) - { - defineFontInfo(tag); - } - - public override void defineMorphShape(DefineMorphShape tag) - { - defineMorphShape2(tag); - } - - public override void defineMorphShape2(DefineMorphShape tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - encodeRect(tag.startBounds, tagw); - encodeRect(tag.endBounds, tagw); - if (tag.code == flash.swf.TagValues_Fields.stagDefineMorphShape2) - { - encodeRect(tag.startEdgeBounds, tagw); - encodeRect(tag.endEdgeBounds, tagw); - tagw.writeUBits(tag.reserved, 6); - tagw.writeUBits(tag.usesNonScalingStrokes?1:0, 1); - tagw.writeUBits(tag.usesScalingStrokes?1:0, 1); - } - tagw.write32(0); - int pos = tagw.Pos; - encodeMorphFillstyles(tag.fillStyles, tagw, tag.code); - encodeMorphLinestyles(tag.lineStyles, tagw, tag.code); - encodeShape(tag.startEdges, tagw, flash.swf.TagValues_Fields.stagDefineShape3, tag.fillStyles.Length, tag.lineStyles.Length); - tagw.write32at(pos - 4, tagw.Pos - pos); - // end shape contains only edges, no style information - encodeShape(tag.endEdges, tagw, flash.swf.TagValues_Fields.stagDefineShape3, 0, 0); - encodeTag(tag); - } - - private void encodeMorphFillstyles(MorphFillStyle[] fillStyles, SwfEncoder w, int code) - { - int count = fillStyles.Length; - if (count >= 0xFF) - { - w.writeUI8(0xFF); - w.writeUI16(count); - } - else - { - w.writeUI8(count); - } - - for (int i = 0; i < count; i++) - { - encodeMorphFillstyle(fillStyles[i], w, code); - } - } - - private void encodeMorphFillstyle(MorphFillStyle style, SwfEncoder w, int code) - { - w.writeUI8(style.type); - switch (style.type) - { - - case FillStyle.FILL_SOLID: // 0x00 - encodeRGBA(style.startColor, w); - encodeRGBA(style.endColor, w); - break; - - case FillStyle.FILL_GRADIENT: - // 0x10 linear gradient fill - case FillStyle.FILL_RADIAL_GRADIENT: - // 0x12 radial gradient fill - case FillStyle.FILL_FOCAL_RADIAL_GRADIENT: // 0x13 focal radial gradient fill - encodeMatrix(style.startGradientMatrix, w); - encodeMatrix(style.endGradientMatrix, w); - encodeMorphGradient(style.gradRecords, w); - if (style.type == FillStyle.FILL_FOCAL_RADIAL_GRADIENT && code == flash.swf.TagValues_Fields.stagDefineMorphShape2) - { - w.writeSI16(style.ratio1); - w.writeSI16(style.ratio2); - } - break; - - case FillStyle.FILL_BITS: - // 0x40 tiled bitmap fill - case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP): - // 0x41 clipped bitmap fill - case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_NOSMOOTH): - // 0x42 tiled non-smoothed fill - case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP | FillStyle.FILL_BITS_NOSMOOTH): // 0x43 clipped non-smoothed fill - w.writeUI16(dict.getId(style.bitmap)); - encodeMatrix(style.startBitmapMatrix, w); - encodeMatrix(style.endBitmapMatrix, w); - break; - - default: - assert(false); - //throw new IOException("unrecognized fill style type: " + style.type); - break; - - } - } - - private void encodeMorphGradient(MorphGradRecord[] gradRecords, SwfEncoder w) - { - w.writeUI8(gradRecords.Length); - for (int i = 0; i < gradRecords.Length; i++) - { - MorphGradRecord record = gradRecords[i]; - w.writeUI8(record.startRatio); - encodeRGBA(record.startColor, w); - w.writeUI8(record.endRatio); - encodeRGBA(record.endColor, w); - } - } - - private void encodeMorphLinestyles(MorphLineStyle[] lineStyles, SwfEncoder w, int code) - { - if (lineStyles.Length >= 0xFF) - { - w.writeUI8(0xFF); - w.writeUI16(lineStyles.Length); - } - else - { - w.writeUI8(lineStyles.Length); - } - - for (int i = 0; i < lineStyles.Length; i++) - { - MorphLineStyle style = lineStyles[i]; - w.writeUI16(style.startWidth); - w.writeUI16(style.endWidth); - if (code == flash.swf.TagValues_Fields.stagDefineMorphShape2) - { - w.writeUBits(style.startCapsStyle, 2); - w.writeUBits(style.jointStyle, 2); - w.writeBit(style.hasFill); - w.writeBit(style.noHScale); - w.writeBit(style.noVScale); - w.writeBit(style.pixelHinting); - w.writeUBits(0, 5); // reserved - w.writeBit(style.noClose); - w.writeUBits(style.endCapsStyle, 2); - if (style.jointStyle == 2) - { - w.writeUI16(style.miterLimit); - } - } - if (!style.hasFill) - { - encodeRGBA(style.startColor, w); - encodeRGBA(style.endColor, w); - } - if (style.hasFill) - { - encodeMorphFillstyle(style.fillType, w, code); - } - } - } - - public override void defineShape(DefineShape tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - encodeRect(tag.bounds, tagw); - if (tag.code == flash.swf.TagValues_Fields.stagDefineShape6) - { - encodeRect(tag.edgeBounds, tagw); - tagw.writeUBits(0, 6); - tagw.writeBit(tag.usesNonScalingStrokes); - tagw.writeBit(tag.usesScalingStrokes); - } - encodeShapeWithStyle(tag.shapeWithStyle, tagw, tag.code); - encodeTag(tag); - } - - private void encodeShapeWithStyle(ShapeWithStyle shapeWithStyle, SwfEncoder w, int shape) - { - encodeFillstyles(shapeWithStyle.fillstyles, w, shape); - encodeLinestyles(shapeWithStyle.linestyles, w, shape); - - encodeShape(shapeWithStyle, w, shape, shapeWithStyle.fillstyles.Count, shapeWithStyle.linestyles.Count); - } - - public override void defineShape2(DefineShape tag) - { - defineShape(tag); - } - - public override void defineShape3(DefineShape tag) - { - defineShape(tag); - } - - public override void defineShape6(DefineShape tag) - { - defineShape(tag); - } - - public override void defineSound(DefineSound tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - tagw.writeUBits(tag.format, 4); - tagw.writeUBits(tag.rate, 2); - tagw.writeUBits(tag.size, 1); - tagw.writeUBits(tag.type, 1); - tagw.write32((int) tag.sampleCount); - tagw.write(tag.data); - encodeTag(tag); - } - - public override void defineSprite(DefineSprite tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - tagw.writeUI16(tag.framecount); - - if (Debug) - { - debug.adjust = writer.Pos + 6; - } - - // save frame count - int oldFrames = frames; - frames = 0; - - // save the movie writer, and push a new writer - SwfEncoder oldWriter = writer; - writer = tagw; - tagw = createEncoder(SwfVersion); - - // write sprite tags - System.Collections.IList tags = tag.tagList.tags; - int size = tags.Count; - for (int i = 0; i < size; i++) - { - Tag t = (Tag) tags[i]; - if (!(t is DefineTag)) - t.visit(this); - } - - // terminate with end marker - writer.writeUI16(0); - - // update frame count - writer.writeUI16at(2, frames); - - // restore writers - tagw = writer; - writer = oldWriter; - frames = oldFrames; - - if (Debug) - { - debug.adjust = 0; - } - - encodeTag(tag); - } - - public override void defineText(DefineText tag) - { - encodeDefineText(tag, tagw, tag.code); - encodeTag(tag); - } - - private void encodeDefineText(DefineText tag, SwfEncoder w, int type) - { - int id = dict.add(tag); - w.writeUI16(id); - encodeRect(tag.bounds, w); - encodeMatrix(tag.matrix, w); - int length = tag.records.Count; - - // compute necessary bit width - int glyphBits = 0; - int advanceBits = 0; - for (int i = 0; i < length; i++) - { - TextRecord tr = (TextRecord) tag.records[i]; - - for (int j = 0; j < tr.entries.Length; j++) - { - GlyphEntry entry = tr.entries[j]; - - while (entry.Index > (1 << glyphBits)) - glyphBits++; - while (System.Math.Abs(entry.advance) > (1 << advanceBits)) - advanceBits++; - } - } - - // increment to get from bit index to bit count. - ++glyphBits; - ++advanceBits; - - w.writeUI8(glyphBits); - w.writeUI8(++advanceBits); // add one extra bit because advances are signed - - for (int i = 0; i < length; i++) - { - TextRecord record = (TextRecord) tag.records[i]; - encodeTextRecord(record, w, type, glyphBits, advanceBits); - } - - w.writeUI8(0); - } - - private void encodeFilterList(System.Collections.IList filters, SwfEncoder w) - { - int count = filters.Count; - w.writeUI8(count); - //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" - for (System.Collections.IEnumerator it = filters.GetEnumerator(); it.MoveNext(); ) - { - //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" - Filter f = (Filter) it.Current; - w.writeUI8(f.getID()); - // I've never quite understood why the serialization code isn't in the tags themselves.. - switch (f.getID()) - { - - case DropShadowFilter.ID: encodeDropShadowFilter(w, (DropShadowFilter) f); break; - - case BlurFilter.ID: encodeBlurFilter(w, (BlurFilter) f); break; - - case ConvolutionFilter.ID: encodeConvolutionFilter(w, (ConvolutionFilter) f); break; - - case GlowFilter.ID: encodeGlowFilter(w, (GlowFilter) f); break; - - case BevelFilter.ID: encodeBevelFilter(w, (BevelFilter) f); break; - - case ColorMatrixFilter.ID: encodeColorMatrixFilter(w, (ColorMatrixFilter) f); break; - - case GradientGlowFilter.ID: encodeGradientGlowFilter(w, (GradientGlowFilter) f); break; - - case GradientBevelFilter.ID: encodeGradientBevelFilter(w, (GradientBevelFilter) f); break; - } - } - } - - private void encodeDropShadowFilter(SwfEncoder w, DropShadowFilter f) - { - encodeRGBA(f.color, w); - w.write32(f.blurX); - w.write32(f.blurY); - w.write32(f.angle); - w.write32(f.distance); - w.writeUI16(f.strength); - w.writeUI8(f.flags); - } - - private void encodeBlurFilter(SwfEncoder w, BlurFilter f) - { - w.write32(f.blurX); - w.write32(f.blurY); - w.writeUI8(f.passes); - } - private void encodeColorMatrixFilter(SwfEncoder w, ColorMatrixFilter f) - { - for (int i = 0; i < 20; ++i) - { - w.writeFloat(f.values[i]); - } - } - private void encodeConvolutionFilter(SwfEncoder w, ConvolutionFilter f) - { - w.writeUI8(f.matrixX); - w.writeUI8(f.matrixY); - w.writeFloat(f.divisor); - w.writeFloat(f.bias); - for (int i = 0; i < f.matrix.Length; ++i) - w.writeFloat(f.matrix[i]); - w.writeUI8(f.flags); - } - private void encodeGlowFilter(SwfEncoder w, GlowFilter f) - { - encodeRGBA(f.color, w); - w.write32(f.blurX); - w.write32(f.blurY); - w.writeUI16(f.strength); - w.writeUI8(f.flags); - } - private void encodeBevelFilter(SwfEncoder w, BevelFilter f) - { - encodeRGBA(f.shadowColor, w); - encodeRGBA(f.highlightColor, w); - w.write32(f.blurX); - w.write32(f.blurY); - w.write32(f.angle); - w.write32(f.distance); - w.writeUI16(f.strength); - w.writeUI8(f.flags); - } - - private void encodeGradientGlowFilter(SwfEncoder w, GradientGlowFilter f) - { - w.writeUI8(f.numcolors); - for (int i = 0; i < f.numcolors; ++i) - encodeRGBA(f.gradientColors[i], w); - for (int i = 0; i < f.numcolors; ++i) - w.writeUI8(f.gradientRatio[i]); - //w.write32( f.color ); - w.write32(f.blurX); - w.write32(f.blurY); - w.write32(f.angle); - w.write32(f.distance); - w.writeUI16(f.strength); - w.writeUI8(f.flags); - } - private void encodeGradientBevelFilter(SwfEncoder w, GradientBevelFilter f) - { - w.writeUI8(f.numcolors); - for (int i = 0; i < f.numcolors; ++i) - encodeRGBA(f.gradientColors[i], w); - for (int i = 0; i < f.numcolors; ++i) - w.writeUI8(f.gradientRatio[i]); - - // w.write32( f.shadowColor ); - // w.write32( f.highlightColor ); - w.write32(f.blurX); - w.write32(f.blurY); - w.write32(f.angle); - w.write32(f.distance); - w.writeUI16(f.strength); - w.writeUI8(f.flags); - } - - private void encodeTextRecord(TextRecord record, SwfEncoder w, int type, int glyphBits, int advanceBits) - { - w.writeUI8(record.flags); - - if (record.hasFont()) - { - w.writeUI16(dict.getId(record.font)); - } - - if (record.hasColor()) - { - if (type == flash.swf.TagValues_Fields.stagDefineText2) - encodeRGBA(record.color, w); - else - encodeRGB(record.color, w); - } - - if (record.hasX()) - { - w.writeSI16(record.xOffset); - } - - if (record.hasY()) - { - w.writeSI16(record.yOffset); - } - - if (record.hasHeight()) - { - w.writeUI16(record.height); - } - - w.writeUI8(record.entries.Length); - - for (int i = 0; i < record.entries.Length; i++) - { - w.writeUBits(record.entries[i].Index, glyphBits); - w.writeSBits(record.entries[i].advance, advanceBits); - } - w.flushBits(); - } - - public override void defineText2(DefineText tag) - { - defineText(tag); - } - - public override void defineVideoStream(DefineVideoStream tag) - { - int id = dict.add(tag); - tagw.writeUI16(id); - tagw.writeUI16(tag.numFrames); - tagw.writeUI16(tag.width); - tagw.writeUI16(tag.height); - - tagw.writeUBits(0, 4); // reserved - tagw.writeUBits(tag.deblocking, 3); - tagw.writeBit(tag.smoothing); - - tagw.writeUI8(tag.codecID); - encodeTag(tag); - } - - public override void doAction(DoAction tag) - { - int adjust = 0; - if (Debug) - { - adjust = writer.Pos + 6; - debug.adjust += adjust; - } - - new ActionEncoder(tagw, debug).encode(tag.actionList); - tagw.writeUI8(0); - encodeTag(tag); - - if (Debug) - { - debug.adjust -= adjust; - } - } - - public override void doInitAction(DoInitAction tag) - { - int adjust = 0; - if (Debug) - { - adjust = writer.Pos + 6; - debug.adjust += adjust; - } - - int idref = dict.getId(tag.sprite); - tagw.writeUI16(idref); - new ActionEncoder(tagw, debug).encode(tag.actionList); - tagw.writeUI8(0); - encodeTag(tag); - - if (Debug) - { - debug.adjust -= adjust; - } - } - - public override void enableDebugger(EnableDebugger tag) - { - tagw.writeString(tag.password); - encodeTag(tag); - } - - public override void enableDebugger2(EnableDebugger tag) - { - // This corresponds to the constant used in the player, - // core/splay.cpp, in ScriptThread::EnableDebugger(). - tagw.writeUI16(0x1975); - tagw.writeString(tag.password); - encodeTag(tag); - } - - public override void exportAssets(ExportAssets tag) - { - tagw.writeUI16(tag.exports.Count); - System.Collections.IEnumerator it = tag.exports.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" - while (it.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" - DefineTag ref_Renamed = (DefineTag) it.Current; - int idref = dict.getId(ref_Renamed); - tagw.writeUI16(idref); - assert(ref_Renamed.name != null); // exported symbols must have names - tagw.writeString(ref_Renamed.name); - dict.addName(ref_Renamed, ref_Renamed.name); - } - encodeTag(tag); - } - - public override void symbolClass(SymbolClass tag) - { - tagw.writeUI16(tag.class2tag.Count + (tag.topLevelClass != null?1:0)); - //UPGRADE_TODO: Method 'java.util.Map.entrySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapentrySet'" - System.Collections.IEnumerator it = new SupportClass.HashSetSupport(tag.class2tag).GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" - while (it.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" - System.Collections.DictionaryEntry e = (System.Collections.DictionaryEntry) it.Current; - System.String name = (System.String) e.Key; - DefineTag ref_Renamed = (DefineTag) e.Value; - - int idref = dict.getId(ref_Renamed); - tagw.writeUI16(idref); - tagw.writeString(name); - } - if (tag.topLevelClass != null) - { - tagw.writeUI16(0); - tagw.writeString(tag.topLevelClass); - } - encodeTag(tag); - } - - public override void frameLabel(FrameLabel tag) - { - tagw.writeString(tag.label); - if (tag.anchor && SwfVersion >= 6) - { - tagw.writeUI8(1); - } - encodeTag(tag); - } - - public override void importAssets(ImportAssets tag) - { - tagw.writeString(tag.url); - if (tag.code == flash.swf.TagValues_Fields.stagImportAssets2) - { - tagw.writeUI8(tag.downloadNow?1:0); - tagw.writeUI8(tag.SHA1 != null?1:0); - if (tag.SHA1 != null) - { - tagw.write(tag.SHA1); - } - } - tagw.writeUI16(tag.importRecords.Count); - System.Collections.IEnumerator it = tag.importRecords.GetEnumerator(); - //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" - while (it.MoveNext()) - { - //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" - ImportRecord record = (ImportRecord) it.Current; - int id = dict.add(record); - tagw.writeUI16(id); - tagw.writeString(record.name); - } - encodeTag(tag); - } - - public override void importAssets2(ImportAssets tag) - { - importAssets(tag); - } - - public override void jpegTables(GenericTag tag) - { - encodeTagHeader(tag.code, tag.data.Length, false); - writer.write(tag.data); - } - - public override void placeObject(PlaceObject tag) - { - int idref = dict.getId(tag.ref_Renamed); - tagw.writeUI16(idref); - tagw.writeUI16(tag.depth); - encodeMatrix(tag.matrix, tagw); - if (tag.colorTransform != null) - { - encodeCxform(tag.colorTransform, tagw); - } - encodeTag(tag); - } - - public override void placeObject2(PlaceObject tag) - { - placeObject23(tag); - } - - public override void placeObject3(PlaceObject tag) - { - placeObject23(tag); - } - - public virtual void placeObject23(PlaceObject tag) - { - tagw.writeUI8(tag.flags); - if (tag.code == flash.swf.TagValues_Fields.stagPlaceObject3) - { - tagw.writeUI8(tag.flags2); - } - tagw.writeUI16(tag.depth); - if (tag.hasClassName()) - { - tagw.writeString(tag.className); - } - if (tag.hasCharID()) - { - int idref = dict.getId(tag.ref_Renamed); - tagw.writeUI16(idref); - } - if (tag.hasMatrix()) - { - encodeMatrix(tag.matrix, tagw); - } - if (tag.hasCxform()) - { - // ed 5/22/03 the SWF 6 file format spec says this should be a CXFORM, but - // the spec is wrong. the player expects a CXFORMA. - encodeCxforma(((CXFormWithAlpha) tag.colorTransform), tagw); - } - if (tag.hasRatio()) - { - tagw.writeUI16(tag.ratio); - } - if (tag.hasName()) - { - tagw.writeString(tag.name); - } - if (tag.hasClipDepth()) - { - tagw.writeUI16(tag.clipDepth); - } - if (tag.code == flash.swf.TagValues_Fields.stagPlaceObject3) - { - if (tag.hasFilterList()) - { - encodeFilterList(tag.filters, tagw); - } - if (tag.hasBlendMode()) - { - tagw.writeUI8(tag.blendMode); - } - } - if (tag.hasClipAction()) - { - int adjust = 0; - if (Debug) - { - adjust = writer.Pos + 6; - debug.adjust += adjust; - } - new ActionEncoder(tagw, debug).encodeClipActions(tag.clipActions); - if (Debug) - { - debug.adjust -= adjust; - } - } - encodeTag(tag); - } - - public override void protect(GenericTag tag) - { - if (tag.data != null) - { - encodeTagHeader(tag.code, tag.data.Length, false); - writer.write(tag.data); - } - else - { - encodeTagHeader(tag.code, 0, false); - } - } - - public override void removeObject(RemoveObject tag) - { - encodeTagHeader(tag.code, 4, false); - int idref = dict.getId(tag.ref_Renamed); - writer.writeUI16(idref); - writer.writeUI16(tag.depth); - } - - public override void removeObject2(RemoveObject tag) - { - encodeTagHeader(tag.code, 2, false); - writer.writeUI16(tag.depth); - } - - public override void showFrame(ShowFrame tag) - { - encodeTagHeader(tag.code, 0, false); - frames++; - } - - public override void soundStreamBlock(GenericTag tag) - { - encodeTagHeader(tag.code, tag.data.Length, false); - writer.write(tag.data); - } - - public override void soundStreamHead(SoundStreamHead tag) - { - int length = 4; - - // we need to add two bytes for an extra SI16 (latencySeek) - if (tag.compression == SoundStreamHead.sndCompressMP3) - { - length += 2; - } - - encodeTagHeader(tag.code, length, false); - - // 1 byte - writer.writeUBits(0, 4); // reserved - writer.writeUBits(tag.playbackRate, 2); - writer.writeUBits(tag.playbackSize, 1); - writer.writeUBits(tag.playbackType, 1); - - // 1 byte - writer.writeUBits(tag.compression, 4); - writer.writeUBits(tag.streamRate, 2); - writer.writeUBits(tag.streamSize, 1); - writer.writeUBits(tag.streamType, 1); - - // 2 bytes - writer.writeUI16(tag.streamSampleCount); - - if (tag.compression == SoundStreamHead.sndCompressMP3) - { - // 2 bytes - writer.writeSI16(tag.latencySeek); - } - } - - public override void soundStreamHead2(SoundStreamHead tag) - { - soundStreamHead(tag); - } - - public override void startSound(StartSound tag) - { - int idref = dict.getId(tag.sound); - tagw.writeUI16(idref); - encodeSoundInfo(tag.soundInfo, tagw); - encodeTag(tag); - } - - public override void videoFrame(VideoFrame tag) - { - encodeTagHeader(tag.code, 4 + tag.videoData.Length, false); - int idref = dict.getId(tag.stream); - writer.writeUI16(idref); - writer.writeUI16(tag.frameNum); - writer.write(tag.videoData); - } - - public override void defineSceneAndFrameLabelData(DefineSceneAndFrameLabelData tag) - { - encodeTagHeader(tag.code, tag.data.Length, false); - writer.write(tag.data); - } - - public override void doABC(DoABC tag) - { - if (tag.code == flash.swf.TagValues_Fields.stagDoABC2) - { - encodeTagHeader(tag.code, 4 + tag.name.Length + 1 + tag.abc.Length, false); - writer.write32(tag.flag); - writer.writeString(tag.name); - } - else - { - encodeTagHeader(tag.code, tag.abc.Length, false); - } - - writer.write(tag.abc); - } - - public override void unknown(GenericTag tag) - { - encodeTagHeader(tag.code, tag.data.Length, false); - writer.write(tag.data); - } - - public virtual sbyte[] toByteArray() - { - //TODO this could be improved, tricky bit is that writeTo is not trivial - // and has the side effect of compressing (meaning the writer.size() - // may be larger than necessary) - System.IO.MemoryStream out_Renamed = new System.IO.MemoryStream(writer.Length); - writeTo(out_Renamed); - return SupportClass.ToSByteArray(out_Renamed.ToArray()); - } - - public override void scriptLimits(ScriptLimits tag) - { - tagw.writeUI16(tag.scriptRecursionLimit); - tagw.writeUI16(tag.scriptTimeLimit); - encodeTag(tag); - } - } +//////////////////////////////////////////////////////////////////////////////// +// +// ADOBE SYSTEMS INCORPORATED +// Copyright 2003-2007 Adobe Systems Incorporated +// All Rights Reserved. +// +// NOTICE: Adobe permits you to use, modify, and distribute this file +// in accordance with the terms of the license agreement accompanying it. +// +//////////////////////////////////////////////////////////////////////////////// +using System; +using flash.swf.tags; +using ButtonCondAction = flash.swf.types.ButtonCondAction; +using ButtonRecord = flash.swf.types.ButtonRecord; +using CXForm = flash.swf.types.CXForm; +using CXFormWithAlpha = flash.swf.types.CXFormWithAlpha; +using CurvedEdgeRecord = flash.swf.types.CurvedEdgeRecord; +using EdgeRecord = flash.swf.types.EdgeRecord; +using FillStyle = flash.swf.types.FillStyle; +using GlyphEntry = flash.swf.types.GlyphEntry; +using GradRecord = flash.swf.types.GradRecord; +using ImportRecord = flash.swf.types.ImportRecord; +using KerningRecord = flash.swf.types.KerningRecord; +using LineStyle = flash.swf.types.LineStyle; +using MD5 = flash.swf.types.MD5; +using Matrix = flash.swf.types.Matrix; +using MorphFillStyle = flash.swf.types.MorphFillStyle; +using MorphGradRecord = flash.swf.types.MorphGradRecord; +using MorphLineStyle = flash.swf.types.MorphLineStyle; +using Rect = flash.swf.types.Rect; +using Shape = flash.swf.types.Shape; +using ShapeRecord = flash.swf.types.ShapeRecord; +using ShapeWithStyle = flash.swf.types.ShapeWithStyle; +using SoundInfo = flash.swf.types.SoundInfo; +using StraightEdgeRecord = flash.swf.types.StraightEdgeRecord; +using StyleChangeRecord = flash.swf.types.StyleChangeRecord; +using TextRecord = flash.swf.types.TextRecord; +using Filter = flash.swf.types.Filter; +using DropShadowFilter = flash.swf.types.DropShadowFilter; +using BlurFilter = flash.swf.types.BlurFilter; +using ColorMatrixFilter = flash.swf.types.ColorMatrixFilter; +using GlowFilter = flash.swf.types.GlowFilter; +using ConvolutionFilter = flash.swf.types.ConvolutionFilter; +using BevelFilter = flash.swf.types.BevelFilter; +using GradientGlowFilter = flash.swf.types.GradientGlowFilter; +using GradientBevelFilter = flash.swf.types.GradientBevelFilter; +using Gradient = flash.swf.types.Gradient; +using FocalGradient = flash.swf.types.FocalGradient; +namespace flash.swf +{ + + public class TagEncoder:TagHandler, TagValues + { + virtual public int Pos + { + get + { + return writer.Pos; + } + + } + virtual protected internal int SwfVersion + { + get + { + return header_Renamed_Field.version; + } + + } + virtual protected internal int FrameRate + { + get + { + return header_Renamed_Field.rate; + } + + } + virtual public Dictionary EncoderDictionary + { + set + { + assert((this.dict == null) || (this.dict.ids.Count == 0)); + this.dict = value; + } + + } + virtual public Dictionary Dictionary + { + get + { + return dict; + } + + } + virtual public bool Debug + { + get + { + return debug != null; + } + + } + virtual public int Width + { + get + { + return width / 20; + } + + } + virtual public int Height + { + get + { + return height / 20; + } + + } + virtual public System.String MainDebugScript + { + set + { + debug.MainDebugScript = value; + } + + } + override public SetBackgroundColor BackgroundColor + { + set + { + encodeTagHeader(value.code, 3, false); + encodeRGB(value.color, writer); + } + + } + override public SetTabIndex TabIndex + { + set + { + tagw.writeUI16(value.depth); + tagw.writeUI16(value.index); + encodeTag(value); + } + + } + // changed from private to protected to support Flash Authoring - jkamerer 2007.07.30 + protected internal SwfEncoder writer; + private SwfEncoder tagw; + private int width; + private int height; + private int frames; + private int framecountPos; + private DebugEncoder debug; + private Header header_Renamed_Field; + + protected internal Dictionary dict; + private int uuidOffset; + + public TagEncoder() + { + dict = new Dictionary(); + } + + public TagEncoder(Dictionary dict) + { + this.dict = dict; + } + + public override void productInfo(ProductInfo tag) + { + tagw.write32(tag.Product); + tagw.write32(tag.Edition); + tagw.write(new sbyte[]{tag.MajorVersion, tag.MinorVersion}); + tagw.write64(tag.Build); + tagw.write64(tag.CompileDate); + encodeTag(tag); + } + + public override void fileAttributes(FileAttributes tag) + { + tagw.writeUBits(0, 3); + tagw.writeBit(tag.hasMetadata); + tagw.writeBit(tag.actionScript3); + tagw.writeBit(tag.suppressCrossDomainCaching); + tagw.writeBit(tag.swfRelativeUrls); + tagw.writeBit(tag.useNetwork); + tagw.writeUBits(0, 24); + encodeTag(tag); + } + + public override void metadata(Metadata tag) + { + tagw.writeString(tag.xml); + encodeTag(tag); + } + + protected internal virtual SwfEncoder createEncoder(int swfVersion) + { + return new SwfEncoder(swfVersion); + } + + public override void header(Header header) + { + // get some header properties we need to know + int swfVersion = header.version; + this.header_Renamed_Field = header; + this.writer = createEncoder(swfVersion); + this.tagw = createEncoder(swfVersion); + width = header.size.Width; + height = header.size.Height; + frames = 0; + + // write the header + writer.writeUI8(header.compressed?'C':'F'); + writer.writeUI8('W'); + writer.writeUI8('S'); + writer.writeUI8(header.version); + writer.write32((int) header.length); + if (header.compressed) + { + writer.markComp(); + } + encodeRect(header.size, writer); + writer.writeUI8(header.rate >> 8); + writer.writeUI8(header.rate & 255); + framecountPos = writer.Pos; + writer.writeUI16(header.framecount); + } + + public override void finish() + { + // write end marker + writer.writeUI16(0); + + // update the length + writer.write32at(4, writer.Pos); + + // update the frame count + writer.writeUI16at(framecountPos, frames); + + if (debug != null) + { + // compute a crc and use it for the debug id. that way it + // is wholly dependent on the bytes in the SWF and not some + // outside value. If any of the bytes are different, + // then the UUID will be different. + sbyte[] md5 = MD5.getDigest(writer.ByteArray, writer.Length); + writer.writeAt(uuidOffset, md5); + debug.updateUUID(md5); + } + } + + public virtual void writeTo(System.IO.Stream out_Renamed) + { + writer.WriteTo(out_Renamed); + } + + + public virtual void writeDebugTo(System.IO.Stream out_Renamed) + { + debug.writeTo(out_Renamed); + } + + public virtual void encodeRect(Rect r, SwfEncoder w) + { + int nBits = r.nbits(); + w.writeUBits(nBits, 5); + w.writeSBits(r.xMin, nBits); + w.writeSBits(r.xMax, nBits); + w.writeSBits(r.yMin, nBits); + w.writeSBits(r.yMax, nBits); + w.flushBits(); + } + + public override void debugID(DebugID tag) + { + encodeTagHeader(tag.code, tag.uuid.bytes.Length, false); + uuidOffset = writer.Pos; + writer.write(tag.uuid.bytes); + + debug = new DebugEncoder(); + debug.header(SwfVersion); + debug.uuid(tag.uuid); + } + + private void encodeTag(Tag tag) + { + try + { + tagw.compress(); + encodeTagHeader(tag.code, tagw.Pos, isLongHeader(tag)); + tagw.WriteTo(writer); + tagw.reset(); + } + catch (System.IO.IOException e) + { + assert(false); + } + } + + private bool isLongHeader(Tag t) + { + switch (t.code) + { + + // [preilly] In the player code, ScriptThread::DefineBits() assumes all DefineBits + // tags use a long header. See "ch->data = AttachData(pos-8);". If the player + // also supported a short header, it would use "pos-4". + case flash.swf.TagValues_Fields.stagDefineBits: + case flash.swf.TagValues_Fields.stagDefineBitsJPEG2: + case flash.swf.TagValues_Fields.stagDefineBitsJPEG3: + case flash.swf.TagValues_Fields.stagDefineBitsLossless: + case flash.swf.TagValues_Fields.stagDefineBitsLossless2: + return true; + + // [ed] the FlashPaper codebase also indicates that stagSoundStreamBlock must use + // a long format header. todo - verify by looking at the player code. + + case flash.swf.TagValues_Fields.stagSoundStreamBlock: + return true; + + // [edsmith] these tags have code in them. When we're writing a SWD, we use long headers + // so we can predict SWF offsets correctly when writing SWD line/offset records. + + case flash.swf.TagValues_Fields.stagDefineButton: + case flash.swf.TagValues_Fields.stagDefineButton2: + case flash.swf.TagValues_Fields.stagDefineSprite: + case flash.swf.TagValues_Fields.stagDoInitAction: + case flash.swf.TagValues_Fields.stagDoAction: + return Debug; + + + case flash.swf.TagValues_Fields.stagPlaceObject2: + return Debug && ((PlaceObject) t).hasClipAction(); + + // all other tags will use short/long headers depending on their length + + default: + return false; + + } + } + + private void encodeTagHeader(int code, int length, bool longHeader) + { + if (longHeader || length >= 63) + { + writer.writeUI16((code << 6) | 63); + writer.write32(length); + } + else + { + writer.writeUI16((code << 6) | length); + } + } + + public override void defineScalingGrid(DefineScalingGrid tag) + { + int idref = dict.getId(tag.scalingTarget); + tagw.writeUI16(idref); + encodeRect(tag.rect, tagw); + encodeTag(tag); + } + + public override void defineBinaryData(DefineBinaryData tag) + { + encodeTagHeader(tag.code, 6 + tag.data.Length, false); + int id = dict.add(tag); + writer.writeUI16(id); + writer.write32(tag.reserved); + writer.write(tag.data); + } + + public override void defineBits(DefineBits tag) + { + encodeTagHeader(tag.code, 2 + tag.data.Length, true); + int id = dict.add(tag); + writer.writeUI16(id); + writer.write(tag.data); + } + + public override void defineBitsJPEG2(DefineBits tag) + { + defineBits(tag); + } + + public override void defineBitsJPEG3(DefineBitsJPEG3 tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + tagw.write32(tag.data.Length); + tagw.write(tag.data); + tagw.markComp(); + tagw.write(tag.alphaData); + encodeTag(tag); + } + + public override void defineBitsLossless(DefineBitsLossless tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + tagw.writeUI8(tag.format); + tagw.writeUI16(tag.width); + tagw.writeUI16(tag.height); + switch (tag.format) + { + + case 3: + tagw.writeUI8(tag.colorData.Length - 1); + tagw.markComp(); + encodeColorMapData(tag.colorData, tag.data, tagw); + break; + + case 4: + case 5: + tagw.markComp(); + encodeBitmapData(tag.data, tagw); + break; + } + encodeTag(tag); + } + + private void encodeBitmapData(sbyte[] data, SwfEncoder w) + { + w.write(data); + } + + private void encodeColorMapData(int[] colorData, sbyte[] pixelData, SwfEncoder w) + { + for (int i = 0; i < colorData.Length; i++) + { + encodeRGB(colorData[i], w); + } + w.write(pixelData); + } + + /// as 0x00RRGGBB + /// + /// + /// + private void encodeRGB(int rgb, SwfEncoder w) + { + w.writeUI8(SupportClass.URShift(rgb, 16)); // red. we don't mask this because if rgb has an Alpha value, something's wrong + w.writeUI8((SupportClass.URShift(rgb, 8)) & 255); + w.writeUI8(rgb & 255); // blue + } + + public override void defineBitsLossless2(DefineBitsLossless tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + tagw.writeUI8(tag.format); + tagw.writeUI16(tag.width); + tagw.writeUI16(tag.height); + switch (tag.format) + { + + case 3: + tagw.writeUI8(tag.colorData.Length - 1); + tagw.markComp(); + encodeAlphaColorMapData(tag.colorData, tag.data, tagw); + break; + + case 4: + case 5: + tagw.markComp(); + encodeBitmapData(tag.data, tagw); + break; + } + encodeTag(tag); + } + + private void encodeAlphaColorMapData(int[] colorData, sbyte[] pixelData, SwfEncoder w) + { + for (int i = 0; i < colorData.Length; i++) + { + encodeRGBA(colorData[i], w); + } + w.write(pixelData); + } + + /// as 0xAARRGGBB + /// + /// + /// + private void encodeRGBA(int rgba, SwfEncoder w) + { + w.writeUI8((SupportClass.URShift(rgba, 16)) & 255); // red + w.writeUI8((SupportClass.URShift(rgba, 8)) & 255); // green + w.writeUI8(rgba & 255); // blue + w.writeUI8(SupportClass.URShift(rgba, 24)); // alpha + } + + public override void defineButton(DefineButton tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + + if (Debug) + { + debug.adjust = writer.Pos + 6; + } + + for (int i = 0; i < tag.buttonRecords.Length; i++) + { + encodeButtonRecord(tag.buttonRecords[i], tagw, tag.code); + } + tagw.writeUI8(0); // no more button records + + // assume there is only one condition we will handle + new ActionEncoder(tagw, debug).encode(tag.condActions[0].actionList); + tagw.writeUI8(0); // write action end flag, must be zero + encodeTag(tag); + + if (Debug) + { + debug.adjust = 0; + } + } + + private void encodeButtonRecord(ButtonRecord record, SwfEncoder w, int defineButton) + { + if (defineButton == flash.swf.TagValues_Fields.stagDefineButton2) + { + w.writeUBits(0, 2); + w.writeBit(record.blendMode != - 1); + w.writeBit(record.filters != null); + } + else + { + w.writeUBits(0, 4); + } + w.writeBit(record.hitTest); + w.writeBit(record.down); + w.writeBit(record.over); + w.writeBit(record.up); + + w.writeUI16(dict.getId(record.characterRef)); + w.writeUI16(record.placeDepth); + encodeMatrix(record.placeMatrix, w); + + if (defineButton == flash.swf.TagValues_Fields.stagDefineButton2) + { + encodeCxforma(record.colorTransform, w); + if (record.filters != null) + { + this.encodeFilterList(record.filters, w); + } + if (record.blendMode != - 1) + { + w.writeUI8(record.blendMode); + } + } + } + + private void encodeCxforma(CXFormWithAlpha cxforma, SwfEncoder w) + { + w.writeBit(cxforma.hasAdd); + w.writeBit(cxforma.hasMult); + + int nbits = cxforma.nbits(); + w.writeUBits(nbits, 4); + + if (cxforma.hasMult) + { + w.writeSBits(cxforma.redMultTerm, nbits); + w.writeSBits(cxforma.greenMultTerm, nbits); + w.writeSBits(cxforma.blueMultTerm, nbits); + w.writeSBits(cxforma.alphaMultTerm, nbits); + } + + if (cxforma.hasAdd) + { + w.writeSBits(cxforma.redAddTerm, nbits); + w.writeSBits(cxforma.greenAddTerm, nbits); + w.writeSBits(cxforma.blueAddTerm, nbits); + w.writeSBits(cxforma.alphaAddTerm, nbits); + } + + w.flushBits(); + } + + private void encodeMatrix(Matrix matrix, SwfEncoder w) + { + w.writeBit(matrix.hasScale); + if (matrix.hasScale) + { + int nScaleBits = matrix.nScaleBits(); + w.writeUBits(nScaleBits, 5); + w.writeSBits(matrix.scaleX, nScaleBits); + w.writeSBits(matrix.scaleY, nScaleBits); + } + + w.writeBit(matrix.hasRotate); + if (matrix.hasRotate) + { + int nRotateBits = matrix.nRotateBits(); + w.writeUBits(nRotateBits, 5); + w.writeSBits(matrix.rotateSkew0, nRotateBits); + w.writeSBits(matrix.rotateSkew1, nRotateBits); + } + + int nTranslateBits = matrix.nTranslateBits(); + w.writeUBits(nTranslateBits, 5); + w.writeSBits(matrix.translateX, nTranslateBits); + w.writeSBits(matrix.translateY, nTranslateBits); + + w.flushBits(); + } + + public override void defineButton2(DefineButton tag) + { + if (Debug) + { + debug.adjust = writer.Pos + 6; + } + + int id = dict.add(tag); + tagw.writeUI16(id); + tagw.writeUBits(0, 7); // reserved + tagw.writeBit(tag.trackAsMenu); + int offsetPos = tagw.Pos; + tagw.writeUI16(0); // actionOffset + + for (int i = 0; i < tag.buttonRecords.Length; i++) + { + encodeButtonRecord(tag.buttonRecords[i], tagw, tag.code); + } + + tagw.writeUI8(0); // charEndFlag + + if (tag.condActions.Length > 0) + { + tagw.writeUI16at(offsetPos, tagw.Pos - offsetPos); + + for (int i = 0; i < tag.condActions.Length; i++) + { + bool isLast = i + 1 == tag.condActions.Length; + encodeButtonCondAction(tag.condActions[i], tagw, isLast); + } + } + encodeTag(tag); + + if (Debug) + { + debug.adjust = 0; + } + } + + private void encodeButtonCondAction(ButtonCondAction condAction, SwfEncoder w, bool last) + { + int pos = w.Pos; + w.writeUI16(0); + + w.writeUBits(condAction.keyPress, 7); + w.writeBit(condAction.overDownToIdle); + + w.writeBit(condAction.idleToOverDown); + w.writeBit(condAction.outDownToIdle); + w.writeBit(condAction.outDownToOverDown); + w.writeBit(condAction.overDownToOutDown); + w.writeBit(condAction.overDownToOverUp); + w.writeBit(condAction.overUpToOverDown); + w.writeBit(condAction.overUpToIdle); + w.writeBit(condAction.idleToOverUp); + + new ActionEncoder(w, debug).encode(condAction.actionList); + w.writeUI8(0); // end action byte + + if (!last) + { + w.writeUI16at(pos, w.Pos - pos); + } + } + + public override void defineButtonCxform(DefineButtonCxform tag) + { + int idref = dict.getId(tag.button); + tagw.writeUI16(idref); + encodeCxform(tag.colorTransform, tagw); + encodeTag(tag); + } + + private void encodeCxform(CXForm cxform, SwfEncoder w) + { + + w.writeBit(cxform.hasAdd); + w.writeBit(cxform.hasMult); + + int nbits = cxform.nbits(); + w.writeUBits(nbits, 4); + + if (cxform.hasMult) + { + w.writeSBits(cxform.redMultTerm, nbits); + w.writeSBits(cxform.greenMultTerm, nbits); + w.writeSBits(cxform.blueMultTerm, nbits); + } + + if (cxform.hasAdd) + { + w.writeSBits(cxform.redAddTerm, nbits); + w.writeSBits(cxform.greenAddTerm, nbits); + w.writeSBits(cxform.blueAddTerm, nbits); + } + + w.flushBits(); + } + + public override void defineButtonSound(DefineButtonSound tag) + { + int idref = dict.getId(tag.button); + tagw.writeUI16(idref); + if (tag.sound0 != null) + { + tagw.writeUI16(dict.getId(tag.sound0)); + encodeSoundInfo(tag.info0, tagw); + } + else + { + tagw.writeUI16(0); + } + if (tag.sound1 != null) + { + tagw.writeUI16(dict.getId(tag.sound1)); + encodeSoundInfo(tag.info1, tagw); + } + else + { + tagw.writeUI16(0); + } + if (tag.sound2 != null) + { + tagw.writeUI16(dict.getId(tag.sound2)); + encodeSoundInfo(tag.info2, tagw); + } + else + { + tagw.writeUI16(0); + } + if (tag.sound3 != null) + { + tagw.writeUI16(dict.getId(tag.sound3)); + encodeSoundInfo(tag.info3, tagw); + } + else + { + tagw.writeUI16(0); + } + encodeTag(tag); + } + + private void encodeSoundInfo(SoundInfo info, SwfEncoder w) + { + w.writeUBits(0, 2); // reserved + w.writeBit(info.syncStop); + w.writeBit(info.syncNoMultiple); + w.writeBit(info.records != null); + w.writeBit(info.loopCount != SoundInfo.UNINITIALIZED); + w.writeBit(info.outPoint != SoundInfo.UNINITIALIZED); + w.writeBit(info.inPoint != SoundInfo.UNINITIALIZED); + + if (info.inPoint != SoundInfo.UNINITIALIZED) + { + w.write32((int) info.inPoint); + } + if (info.outPoint != SoundInfo.UNINITIALIZED) + { + w.write32((int) info.outPoint); + } + if (info.loopCount != SoundInfo.UNINITIALIZED) + { + w.writeUI16(info.loopCount); + } + if (info.records != null) + { + w.writeUI8(info.records.Length); + for (int k = 0; k < info.records.Length; k++) + { + w.write64(info.records[k]); + } + } + } + + public override void defineEditText(DefineEditText tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + encodeRect(tag.bounds, tagw); + + tagw.writeBit(tag.hasText); + tagw.writeBit(tag.wordWrap); + tagw.writeBit(tag.multiline); + tagw.writeBit(tag.password); + tagw.writeBit(tag.readOnly); + tagw.writeBit(tag.hasTextColor); + tagw.writeBit(tag.hasMaxLength); + tagw.writeBit(tag.hasFont); + + tagw.writeBit(false); // reserved + tagw.writeBit(tag.autoSize); + tagw.writeBit(tag.hasLayout); + tagw.writeBit(tag.noSelect); + tagw.writeBit(tag.border); + tagw.writeBit(tag.wasStatic); + tagw.writeBit(tag.html); + tagw.writeBit(tag.useOutlines); + + tagw.flushBits(); + + if (tag.hasFont) + { + int idref = dict.getId(tag.font); + tagw.writeUI16(idref); + tagw.writeUI16(tag.height); + } + + if (tag.hasTextColor) + { + encodeRGBA(tag.color, tagw); + } + + if (tag.hasMaxLength) + { + tagw.writeUI16(tag.maxLength); + } + + if (tag.hasLayout) + { + tagw.writeUI8(tag.align); + tagw.writeUI16(tag.leftMargin); + tagw.writeUI16(tag.rightMargin); + tagw.writeUI16(tag.ident); + tagw.writeSI16(tag.leading); // see errata, leading is signed + } + + tagw.writeString(tag.varName); + if (tag.hasText) + { + tagw.writeString(tag.initialText); + } + encodeTag(tag); + } + + public override void defineFont(DefineFont1 tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + + int count = tag.glyphShapeTable.Length; + + int offsetPos = tagw.Pos; + + // write offset placeholders + for (int i = 0; i < count; i++) + { + tagw.writeUI16(0); + } + + // now write glyphs and update the encoded offset table + for (int i = 0; i < count; i++) + { + tagw.writeUI16at(offsetPos + 2 * i, tagw.Pos - offsetPos); + encodeShape(tag.glyphShapeTable[i], tagw, flash.swf.TagValues_Fields.stagDefineShape3, 1, 0); + } + + encodeTag(tag); + } + + public virtual void encodeShape(Shape s, SwfEncoder w, int shape, int nFillStyles, int nLineStyles) + { + int[] numFillBits = new int[]{SwfEncoder.minBits(nFillStyles, 0)}; + int[] numLineBits = new int[]{SwfEncoder.minBits(nLineStyles, 0)}; + + w.writeUBits(numFillBits[0], 4); + w.writeUBits(numLineBits[0], 4); + + System.Collections.IEnumerator it = s.shapeRecords.GetEnumerator(); + //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" + while (it.MoveNext()) + { + //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" + ShapeRecord record = (ShapeRecord) it.Current; + if (record is StyleChangeRecord) + { + // style change + w.writeBit(false); + StyleChangeRecord change = (StyleChangeRecord) record; + encodeStyleChangeRecord(w, change, numFillBits, numLineBits, shape); + } + else + { + // edge + w.writeBit(true); + EdgeRecord e = (EdgeRecord) record; + bool straight = e is StraightEdgeRecord; + w.writeBit(straight); + int nbits = straight?calcBits((StraightEdgeRecord) e):calcBits((CurvedEdgeRecord) e); + if (nbits < 2) + nbits = 2; + w.writeUBits(nbits - 2, 4); + if (straight) + { + // line + StraightEdgeRecord line = (StraightEdgeRecord) e; + encodeStraightEdgeRecord(line, w, nbits); + } + else + { + // curve + CurvedEdgeRecord curve = (CurvedEdgeRecord) e; + w.writeSBits(curve.controlDeltaX, nbits); + w.writeSBits(curve.controlDeltaY, nbits); + w.writeSBits(curve.anchorDeltaX, nbits); + w.writeSBits(curve.anchorDeltaY, nbits); + } + } + } + + // endshaperecord + w.writeUBits(0, 6); + + w.flushBits(); + } + + private int calcBits(StraightEdgeRecord edge) + { + return SwfEncoder.minBits(SwfEncoder.maxNum(edge.deltaX, edge.deltaY, 0, 0), 1); + } + + private int calcBits(CurvedEdgeRecord edge) + { + return SwfEncoder.minBits(SwfEncoder.maxNum(edge.controlDeltaX, edge.controlDeltaY, edge.anchorDeltaX, edge.anchorDeltaY), 1); + } + + private void encodeStraightEdgeRecord(StraightEdgeRecord line, SwfEncoder w, int nbits) + { + if (line.deltaX == 0) + { + w.writeUBits(1, 2); // vertical line + w.writeSBits(line.deltaY, nbits); + } + else if (line.deltaY == 0) + { + w.writeUBits(0, 2); // horizontal line + w.writeSBits(line.deltaX, nbits); + } + else + { + w.writeBit(true); // general line + w.writeSBits(line.deltaX, nbits); + w.writeSBits(line.deltaY, nbits); + } + } + + private void encodeStyleChangeRecord(SwfEncoder w, StyleChangeRecord s, int[] numFillBits, int[] numLineBits, int shape) + { + w.writeBit(s.stateNewStyles); + w.writeBit(s.stateLineStyle); + w.writeBit(s.stateFillStyle1); + w.writeBit(s.stateFillStyle0); + w.writeBit(s.stateMoveTo); + + if (s.stateMoveTo) + { + int moveBits = s.nMoveBits(); + w.writeUBits(moveBits, 5); + w.writeSBits(s.moveDeltaX, moveBits); + w.writeSBits(s.moveDeltaY, moveBits); + } + + if (s.stateFillStyle0) + { + w.writeUBits(s.fillstyle0, numFillBits[0]); + } + + if (s.stateFillStyle1) + { + w.writeUBits(s.fillstyle1, numFillBits[0]); + } + + if (s.stateLineStyle) + { + w.writeUBits(s.linestyle, numLineBits[0]); + } + + if (s.stateNewStyles) + { + w.flushBits(); + + encodeFillstyles(s.fillstyles, w, shape); + encodeLinestyles(s.linestyles, w, shape); + + numFillBits[0] = SwfEncoder.minBits(s.fillstyles.Count, 0); + numLineBits[0] = SwfEncoder.minBits(s.linestyles.Count, 0); + w.writeUBits(numFillBits[0], 4); + w.writeUBits(numLineBits[0], 4); + } + } + + private void encodeLinestyles(System.Collections.ArrayList linestyles, SwfEncoder w, int shape) + { + int count = linestyles.Count; + if (count > 0xFF) + { + w.writeUI8(0xFF); + w.writeUI16(count); + } + else + { + w.writeUI8(count); + } + + for (int i = 0; i < count; i++) + { + encodeLineStyle((LineStyle) linestyles[i], w, shape); + } + } + + private void encodeLineStyle(LineStyle lineStyle, SwfEncoder w, int shape) + { + w.writeUI16(lineStyle.width); + + if (shape == flash.swf.TagValues_Fields.stagDefineShape6) + { + w.writeUI16(lineStyle.flags); + if (lineStyle.hasMiterJoint()) + w.writeUI16(lineStyle.miterLimit); + } + + if (shape == flash.swf.TagValues_Fields.stagDefineShape6 && lineStyle.hasFillStyle()) + { + encodeFillStyle(lineStyle.fillStyle, w, shape); + } + else if ((shape == flash.swf.TagValues_Fields.stagDefineShape3) || (shape == flash.swf.TagValues_Fields.stagDefineShape6)) + { + encodeRGBA(lineStyle.color, w); + } + else + { + encodeRGB(lineStyle.color, w); + } + } + + private void encodeFillstyles(System.Collections.ArrayList fillstyles, SwfEncoder w, int shape) + { + int count = fillstyles.Count; + if (count >= 0xFF) + { + w.writeUI8(0xFF); + w.writeUI16(count); + } + else + { + w.writeUI8(count); + } + + System.Collections.IEnumerator it = fillstyles.GetEnumerator(); + //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" + while (it.MoveNext()) + { + //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" + FillStyle style = (FillStyle) it.Current; + encodeFillStyle(style, w, shape); + } + } + + private void encodeFillStyle(FillStyle style, SwfEncoder w, int shape) + { + w.writeUI8(style.type); + switch (style.type) + { + + case FillStyle.FILL_SOLID: // 0x00 + if ((shape == flash.swf.TagValues_Fields.stagDefineShape3) || (shape == flash.swf.TagValues_Fields.stagDefineShape6)) + encodeRGBA(style.color, w); + else + encodeRGB(style.color, w); + break; + + case FillStyle.FILL_GRADIENT: + // 0x10 linear gradient fill + case FillStyle.FILL_RADIAL_GRADIENT: + // 0x12 radial gradient fill + case FillStyle.FILL_FOCAL_RADIAL_GRADIENT: // 0x13 focal radial gradient fill + encodeMatrix(style.matrix, w); + encodeGradient(style.gradient, w, shape); + break; + + case FillStyle.FILL_BITS: + // 0x40 tiled bitmap fill + case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP): + // 0x41 clipped bitmap fill + case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_NOSMOOTH): + // 0x42 tiled non-smoothed fill + case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP | FillStyle.FILL_BITS_NOSMOOTH): // 0x43 clipped non-smoothed fill + w.writeUI16(dict.getId(style.bitmap)); + encodeMatrix(style.matrix, w); + break; + } + } + + private void encodeGradient(Gradient gradient, SwfEncoder w, int shape) + { + w.writeUBits(gradient.spreadMode, 2); + w.writeUBits(gradient.interpolationMode, 2); + w.writeUBits(gradient.records.Length, 4); + for (int i = 0; i < gradient.records.Length; i++) + { + encodeGradRecord(gradient.records[i], w, shape); + } + if (gradient is FocalGradient) + { + w.writeFixed8(((FocalGradient) gradient).focalPoint); + } + } + + private void encodeGradRecord(GradRecord record, SwfEncoder w, int shape) + { + w.writeUI8(record.ratio); + if ((shape == flash.swf.TagValues_Fields.stagDefineShape3) || (shape == flash.swf.TagValues_Fields.stagDefineShape6)) + encodeRGBA(record.color, w); + else + encodeRGB(record.color, w); + } + + public override void defineFont2(DefineFont2 tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + int startPos = tagw.Pos; + bool again; + + if (tag.code == flash.swf.TagValues_Fields.stagDefineFont3) + { + tag.wideCodes = true; + } + + if (!tag.wideCodes) + { + for (int i = 0; i < tag.codeTable.Length; i++) + { + if (tag.codeTable[i] > 255) + { + tag.wideCodes = true; + break; + } + } + } + + //UPGRADE_NOTE: Label 'loop' was moved. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1014'" + do + { + again = false; + tagw.writeBit(tag.hasLayout); + tagw.writeBit(tag.shiftJIS); + tagw.writeBit(tag.smallText); + tagw.writeBit(tag.ansi); + tagw.writeBit(tag.wideOffsets); + tagw.writeBit(tag.wideCodes); + tagw.writeBit(tag.italic); + tagw.writeBit(tag.bold); + tagw.flushBits(); + + tagw.writeUI8(tag.langCode); + + tagw.writeLengthString(tag.fontName); + int count = tag.glyphShapeTable.Length; + + tagw.writeUI16(count); + int offsetPos = tagw.Pos; + + // save space for the offset table + if (tag.wideOffsets) + { + for (int i = 0; i < count; i++) + { + tagw.write32(0); + } + } + else + { + for (int i = 0; i < count; i++) + { + tagw.writeUI16(0); + } + } + + //PJF: write placeholder for codeTableOffset, this will be changed after shapes encoded + if (count > 0) + { + if (tag.wideOffsets) + { + tagw.write32(0); + } + else + { + tagw.writeUI16(0); + } + } + + for (int i = 0; i < count; i++) + { + // save offset to this glyph + int offset = tagw.Pos - offsetPos; + if (!tag.wideOffsets && offset > 65535) + { + again = true; + tag.wideOffsets = true; + tagw.Pos = startPos; + //UPGRADE_NOTE: Labeled continue statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1015'" + goto loop; + } + if (tag.wideOffsets) + tagw.write32at(offsetPos + 4 * i, offset); + else + tagw.writeUI16at(offsetPos + 2 * i, offset); + + encodeShape(tag.glyphShapeTable[i], tagw, flash.swf.TagValues_Fields.stagDefineShape3, 1, 0); + } + + // update codeTableOffset + int offset2 = tagw.Pos - offsetPos; + if (!tag.wideOffsets && offset2 > 65535) + { + again = true; + tag.wideOffsets = true; + tagw.Pos = startPos; + //UPGRADE_NOTE: Labeled continue statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1015'" + goto loop; + } + if (tag.wideOffsets) + { + tagw.write32at(offsetPos + 4 * count, offset2); + } + else + { + tagw.writeUI16at(offsetPos + 2 * count, offset2); + } + + // now write the codetable + + if (tag.wideCodes) + { + for (int i = 0; i < tag.codeTable.Length; i++) + { + tagw.writeUI16(tag.codeTable[i]); + } + } + else + { + for (int i = 0; i < tag.codeTable.Length; i++) + { + tagw.writeUI8(tag.codeTable[i]); + } + } + + if (tag.hasLayout) + { + tagw.writeSI16(tag.ascent); + tagw.writeSI16(tag.descent); + tagw.writeSI16(tag.leading); + + for (int i = 0; i < tag.advanceTable.Length; i++) + { + tagw.writeSI16(tag.advanceTable[i]); + } + + for (int i = 0; i < tag.boundsTable.Length; i++) + { + encodeRect(tag.boundsTable[i], tagw); + } + + tagw.writeUI16(tag.kerningTable.Length); + + for (int i = 0; i < tag.kerningTable.Length; i++) + { + if (!tag.wideCodes && ((tag.kerningTable[i].code1 > 255) || (tag.kerningTable[i].code2 > 255))) + { + again = true; + tag.wideCodes = true; + tagw.Pos = startPos; + //UPGRADE_NOTE: Labeled continue statement was changed to a goto statement. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1015'" + goto loop; + } + + encodeKerningRecord(tag.kerningTable[i], tagw, tag.wideCodes); + } + } + //UPGRADE_NOTE: Label 'loop' was moved. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1014'" +loop: ; + } + while (again); + + encodeTag(tag); + } + + public override void defineFont3(DefineFont3 tag) + { + defineFont2(tag); + } + + public override void defineFont4(DefineFont4 tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + + tagw.writeUBits(0, 5); // reserved + tagw.writeBit(tag.hasFontData); + //tagw.writeBit(tag.smallText); + tagw.writeBit(tag.italic); + tagw.writeBit(tag.bold); + tagw.flushBits(); + + //tagw.writeUI8(tag.langCode); + tagw.writeString(tag.fontName); + if (tag.hasFontData) + { + tagw.write(tag.data); + } + + encodeTag(tag); + } + + public override void defineFontAlignZones(DefineFontAlignZones tag) + { + int fontID = dict.getId(tag.font); + tagw.writeUI16(fontID); + tagw.writeUBits(tag.csmTableHint, 2); + tagw.writeUBits(0, 6); // reserved + for (int i = 0; i < tag.zoneTable.Length; i++) + { + ZoneRecord record = tag.zoneTable[i]; + tagw.writeUI8(record.numZoneData); + for (int j = 0; j < record.numZoneData; j++) + { + tagw.write32((int) record.zoneData[j]); + } + tagw.writeUI8(record.zoneMask); + } + encodeTag(tag); + } + + public override void csmTextSettings(CSMTextSettings tag) + { + int textID = 0; + if (tag.textReference != null) + { + textID = dict.getId(tag.textReference); + } + tagw.writeUI16(textID); + tagw.writeUBits(tag.styleFlagsUseSaffron, 2); + tagw.writeUBits(tag.gridFitType, 3); + tagw.writeUBits(0, 3); // reserved + // FIXME: thickness/sharpness should be written out as 32 bit IEEE Single Precision format in little Endian + tagw.writeUBits((int) tag.thickness, 32); + tagw.writeUBits((int) tag.sharpness, 32); + tagw.writeUBits(0, 8); //reserved + + encodeTag(tag); + } + + public override void defineFontName(DefineFontName tag) + { + int fontID = dict.getId(tag.font); + tagw.writeUI16(fontID); + if (tag.fontName != null) + { + tagw.writeString(tag.fontName); + } + else + { + tagw.writeString(""); + } + if (tag.copyright != null) + { + tagw.writeString(tag.copyright); + } + else + { + tagw.writeString(""); + } + + encodeTag(tag); + } + + private void encodeKerningRecord(KerningRecord kerningRecord, SwfEncoder w, bool wideCodes) + { + if (wideCodes) + { + w.writeUI16(kerningRecord.code1); + w.writeUI16(kerningRecord.code2); + } + else + { + w.writeUI8(kerningRecord.code1); + w.writeUI8(kerningRecord.code2); + } + w.writeUI16(kerningRecord.adjustment); + } + + public override void defineFontInfo(DefineFontInfo tag) + { + int idref = dict.getId(tag.font); + tagw.writeUI16(idref); + + tagw.writeLengthString(tag.name); + + tagw.writeUBits(0, 3); // reserved + tagw.writeBit(tag.shiftJIS); + tagw.writeBit(tag.ansi); + tagw.writeBit(tag.italic); + tagw.writeBit(tag.bold); + + if (tag.code == flash.swf.TagValues_Fields.stagDefineFontInfo2) + { + tagw.writeBit(tag.wideCodes = true); + tagw.writeUI8(tag.langCode); + } + else + { + if (!tag.wideCodes) + { + for (int i = 0; i < tag.codeTable.Length; i++) + { + if (tag.codeTable[i] > 255) + { + tag.wideCodes = true; + break; + } + } + } + tagw.writeBit(tag.wideCodes); + } + + if (tag.wideCodes) + { + for (int i = 0; i < tag.codeTable.Length; i++) + tagw.writeUI16(tag.codeTable[i]); + } + else + { + for (int i = 0; i < tag.codeTable.Length; i++) + tagw.writeUI8(tag.codeTable[i]); + } + encodeTag(tag); + } + + public override void defineFontInfo2(DefineFontInfo tag) + { + defineFontInfo(tag); + } + + public override void defineMorphShape(DefineMorphShape tag) + { + defineMorphShape2(tag); + } + + public override void defineMorphShape2(DefineMorphShape tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + encodeRect(tag.startBounds, tagw); + encodeRect(tag.endBounds, tagw); + if (tag.code == flash.swf.TagValues_Fields.stagDefineMorphShape2) + { + encodeRect(tag.startEdgeBounds, tagw); + encodeRect(tag.endEdgeBounds, tagw); + tagw.writeUBits(tag.reserved, 6); + tagw.writeUBits(tag.usesNonScalingStrokes?1:0, 1); + tagw.writeUBits(tag.usesScalingStrokes?1:0, 1); + } + tagw.write32(0); + int pos = tagw.Pos; + encodeMorphFillstyles(tag.fillStyles, tagw, tag.code); + encodeMorphLinestyles(tag.lineStyles, tagw, tag.code); + encodeShape(tag.startEdges, tagw, flash.swf.TagValues_Fields.stagDefineShape3, tag.fillStyles.Length, tag.lineStyles.Length); + tagw.write32at(pos - 4, tagw.Pos - pos); + // end shape contains only edges, no style information + encodeShape(tag.endEdges, tagw, flash.swf.TagValues_Fields.stagDefineShape3, 0, 0); + encodeTag(tag); + } + + private void encodeMorphFillstyles(MorphFillStyle[] fillStyles, SwfEncoder w, int code) + { + int count = fillStyles.Length; + if (count >= 0xFF) + { + w.writeUI8(0xFF); + w.writeUI16(count); + } + else + { + w.writeUI8(count); + } + + for (int i = 0; i < count; i++) + { + encodeMorphFillstyle(fillStyles[i], w, code); + } + } + + private void encodeMorphFillstyle(MorphFillStyle style, SwfEncoder w, int code) + { + w.writeUI8(style.type); + switch (style.type) + { + + case FillStyle.FILL_SOLID: // 0x00 + encodeRGBA(style.startColor, w); + encodeRGBA(style.endColor, w); + break; + + case FillStyle.FILL_GRADIENT: + // 0x10 linear gradient fill + case FillStyle.FILL_RADIAL_GRADIENT: + // 0x12 radial gradient fill + case FillStyle.FILL_FOCAL_RADIAL_GRADIENT: // 0x13 focal radial gradient fill + encodeMatrix(style.startGradientMatrix, w); + encodeMatrix(style.endGradientMatrix, w); + encodeMorphGradient(style.gradRecords, w); + if (style.type == FillStyle.FILL_FOCAL_RADIAL_GRADIENT && code == flash.swf.TagValues_Fields.stagDefineMorphShape2) + { + w.writeSI16(style.ratio1); + w.writeSI16(style.ratio2); + } + break; + + case FillStyle.FILL_BITS: + // 0x40 tiled bitmap fill + case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP): + // 0x41 clipped bitmap fill + case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_NOSMOOTH): + // 0x42 tiled non-smoothed fill + case (FillStyle.FILL_BITS | FillStyle.FILL_BITS_CLIP | FillStyle.FILL_BITS_NOSMOOTH): // 0x43 clipped non-smoothed fill + w.writeUI16(dict.getId(style.bitmap)); + encodeMatrix(style.startBitmapMatrix, w); + encodeMatrix(style.endBitmapMatrix, w); + break; + + default: + assert(false); + //throw new IOException("unrecognized fill style type: " + style.type); + break; + + } + } + + private void encodeMorphGradient(MorphGradRecord[] gradRecords, SwfEncoder w) + { + w.writeUI8(gradRecords.Length); + for (int i = 0; i < gradRecords.Length; i++) + { + MorphGradRecord record = gradRecords[i]; + w.writeUI8(record.startRatio); + encodeRGBA(record.startColor, w); + w.writeUI8(record.endRatio); + encodeRGBA(record.endColor, w); + } + } + + private void encodeMorphLinestyles(MorphLineStyle[] lineStyles, SwfEncoder w, int code) + { + if (lineStyles.Length >= 0xFF) + { + w.writeUI8(0xFF); + w.writeUI16(lineStyles.Length); + } + else + { + w.writeUI8(lineStyles.Length); + } + + for (int i = 0; i < lineStyles.Length; i++) + { + MorphLineStyle style = lineStyles[i]; + w.writeUI16(style.startWidth); + w.writeUI16(style.endWidth); + if (code == flash.swf.TagValues_Fields.stagDefineMorphShape2) + { + w.writeUBits(style.startCapsStyle, 2); + w.writeUBits(style.jointStyle, 2); + w.writeBit(style.hasFill); + w.writeBit(style.noHScale); + w.writeBit(style.noVScale); + w.writeBit(style.pixelHinting); + w.writeUBits(0, 5); // reserved + w.writeBit(style.noClose); + w.writeUBits(style.endCapsStyle, 2); + if (style.jointStyle == 2) + { + w.writeUI16(style.miterLimit); + } + } + if (!style.hasFill) + { + encodeRGBA(style.startColor, w); + encodeRGBA(style.endColor, w); + } + if (style.hasFill) + { + encodeMorphFillstyle(style.fillType, w, code); + } + } + } + + public override void defineShape(DefineShape tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + encodeRect(tag.bounds, tagw); + if (tag.code == flash.swf.TagValues_Fields.stagDefineShape6) + { + encodeRect(tag.edgeBounds, tagw); + tagw.writeUBits(0, 6); + tagw.writeBit(tag.usesNonScalingStrokes); + tagw.writeBit(tag.usesScalingStrokes); + } + encodeShapeWithStyle(tag.shapeWithStyle, tagw, tag.code); + encodeTag(tag); + } + + private void encodeShapeWithStyle(ShapeWithStyle shapeWithStyle, SwfEncoder w, int shape) + { + encodeFillstyles(shapeWithStyle.fillstyles, w, shape); + encodeLinestyles(shapeWithStyle.linestyles, w, shape); + + encodeShape(shapeWithStyle, w, shape, shapeWithStyle.fillstyles.Count, shapeWithStyle.linestyles.Count); + } + + public override void defineShape2(DefineShape tag) + { + defineShape(tag); + } + + public override void defineShape3(DefineShape tag) + { + defineShape(tag); + } + + public override void defineShape6(DefineShape tag) + { + defineShape(tag); + } + + public override void defineSound(DefineSound tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + tagw.writeUBits(tag.format, 4); + tagw.writeUBits(tag.rate, 2); + tagw.writeUBits(tag.size, 1); + tagw.writeUBits(tag.type, 1); + tagw.write32((int) tag.sampleCount); + tagw.write(tag.data); + encodeTag(tag); + } + + public override void defineSprite(DefineSprite tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + tagw.writeUI16(tag.framecount); + + if (Debug) + { + debug.adjust = writer.Pos + 6; + } + + // save frame count + int oldFrames = frames; + frames = 0; + + // save the movie writer, and push a new writer + SwfEncoder oldWriter = writer; + writer = tagw; + tagw = createEncoder(SwfVersion); + + // write sprite tags + System.Collections.IList tags = tag.tagList.tags; + int size = tags.Count; + for (int i = 0; i < size; i++) + { + Tag t = (Tag) tags[i]; + if (!(t is DefineTag)) + t.visit(this); + } + + // terminate with end marker + writer.writeUI16(0); + + // update frame count + writer.writeUI16at(2, frames); + + // restore writers + tagw = writer; + writer = oldWriter; + frames = oldFrames; + + if (Debug) + { + debug.adjust = 0; + } + + encodeTag(tag); + } + + public override void defineText(DefineText tag) + { + encodeDefineText(tag, tagw, tag.code); + encodeTag(tag); + } + + private void encodeDefineText(DefineText tag, SwfEncoder w, int type) + { + int id = dict.add(tag); + w.writeUI16(id); + encodeRect(tag.bounds, w); + encodeMatrix(tag.matrix, w); + int length = tag.records.Count; + + // compute necessary bit width + int glyphBits = 0; + int advanceBits = 0; + for (int i = 0; i < length; i++) + { + TextRecord tr = (TextRecord) tag.records[i]; + + for (int j = 0; j < tr.entries.Length; j++) + { + GlyphEntry entry = tr.entries[j]; + + while (entry.Index > (1 << glyphBits)) + glyphBits++; + while (System.Math.Abs(entry.advance) > (1 << advanceBits)) + advanceBits++; + } + } + + // increment to get from bit index to bit count. + ++glyphBits; + ++advanceBits; + + w.writeUI8(glyphBits); + w.writeUI8(++advanceBits); // add one extra bit because advances are signed + + for (int i = 0; i < length; i++) + { + TextRecord record = (TextRecord) tag.records[i]; + encodeTextRecord(record, w, type, glyphBits, advanceBits); + } + + w.writeUI8(0); + } + + private void encodeFilterList(System.Collections.IList filters, SwfEncoder w) + { + int count = filters.Count; + w.writeUI8(count); + //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" + for (System.Collections.IEnumerator it = filters.GetEnumerator(); it.MoveNext(); ) + { + //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" + Filter f = (Filter) it.Current; + w.writeUI8(f.getID()); + // I've never quite understood why the serialization code isn't in the tags themselves.. + switch (f.getID()) + { + + case DropShadowFilter.ID: encodeDropShadowFilter(w, (DropShadowFilter) f); break; + + case BlurFilter.ID: encodeBlurFilter(w, (BlurFilter) f); break; + + case ConvolutionFilter.ID: encodeConvolutionFilter(w, (ConvolutionFilter) f); break; + + case GlowFilter.ID: encodeGlowFilter(w, (GlowFilter) f); break; + + case BevelFilter.ID: encodeBevelFilter(w, (BevelFilter) f); break; + + case ColorMatrixFilter.ID: encodeColorMatrixFilter(w, (ColorMatrixFilter) f); break; + + case GradientGlowFilter.ID: encodeGradientGlowFilter(w, (GradientGlowFilter) f); break; + + case GradientBevelFilter.ID: encodeGradientBevelFilter(w, (GradientBevelFilter) f); break; + } + } + } + + private void encodeDropShadowFilter(SwfEncoder w, DropShadowFilter f) + { + encodeRGBA(f.color, w); + w.write32(f.blurX); + w.write32(f.blurY); + w.write32(f.angle); + w.write32(f.distance); + w.writeUI16(f.strength); + w.writeUI8(f.flags); + } + + private void encodeBlurFilter(SwfEncoder w, BlurFilter f) + { + w.write32(f.blurX); + w.write32(f.blurY); + w.writeUI8(f.passes); + } + private void encodeColorMatrixFilter(SwfEncoder w, ColorMatrixFilter f) + { + for (int i = 0; i < 20; ++i) + { + w.writeFloat(f.values[i]); + } + } + private void encodeConvolutionFilter(SwfEncoder w, ConvolutionFilter f) + { + w.writeUI8(f.matrixX); + w.writeUI8(f.matrixY); + w.writeFloat(f.divisor); + w.writeFloat(f.bias); + for (int i = 0; i < f.matrix.Length; ++i) + w.writeFloat(f.matrix[i]); + w.writeUI8(f.flags); + } + private void encodeGlowFilter(SwfEncoder w, GlowFilter f) + { + encodeRGBA(f.color, w); + w.write32(f.blurX); + w.write32(f.blurY); + w.writeUI16(f.strength); + w.writeUI8(f.flags); + } + private void encodeBevelFilter(SwfEncoder w, BevelFilter f) + { + encodeRGBA(f.shadowColor, w); + encodeRGBA(f.highlightColor, w); + w.write32(f.blurX); + w.write32(f.blurY); + w.write32(f.angle); + w.write32(f.distance); + w.writeUI16(f.strength); + w.writeUI8(f.flags); + } + + private void encodeGradientGlowFilter(SwfEncoder w, GradientGlowFilter f) + { + w.writeUI8(f.numcolors); + for (int i = 0; i < f.numcolors; ++i) + encodeRGBA(f.gradientColors[i], w); + for (int i = 0; i < f.numcolors; ++i) + w.writeUI8(f.gradientRatio[i]); + //w.write32( f.color ); + w.write32(f.blurX); + w.write32(f.blurY); + w.write32(f.angle); + w.write32(f.distance); + w.writeUI16(f.strength); + w.writeUI8(f.flags); + } + private void encodeGradientBevelFilter(SwfEncoder w, GradientBevelFilter f) + { + w.writeUI8(f.numcolors); + for (int i = 0; i < f.numcolors; ++i) + encodeRGBA(f.gradientColors[i], w); + for (int i = 0; i < f.numcolors; ++i) + w.writeUI8(f.gradientRatio[i]); + + // w.write32( f.shadowColor ); + // w.write32( f.highlightColor ); + w.write32(f.blurX); + w.write32(f.blurY); + w.write32(f.angle); + w.write32(f.distance); + w.writeUI16(f.strength); + w.writeUI8(f.flags); + } + + private void encodeTextRecord(TextRecord record, SwfEncoder w, int type, int glyphBits, int advanceBits) + { + w.writeUI8(record.flags); + + if (record.hasFont()) + { + w.writeUI16(dict.getId(record.font)); + } + + if (record.hasColor()) + { + if (type == flash.swf.TagValues_Fields.stagDefineText2) + encodeRGBA(record.color, w); + else + encodeRGB(record.color, w); + } + + if (record.hasX()) + { + w.writeSI16(record.xOffset); + } + + if (record.hasY()) + { + w.writeSI16(record.yOffset); + } + + if (record.hasHeight()) + { + w.writeUI16(record.height); + } + + w.writeUI8(record.entries.Length); + + for (int i = 0; i < record.entries.Length; i++) + { + w.writeUBits(record.entries[i].Index, glyphBits); + w.writeSBits(record.entries[i].advance, advanceBits); + } + w.flushBits(); + } + + public override void defineText2(DefineText tag) + { + defineText(tag); + } + + public override void defineVideoStream(DefineVideoStream tag) + { + int id = dict.add(tag); + tagw.writeUI16(id); + tagw.writeUI16(tag.numFrames); + tagw.writeUI16(tag.width); + tagw.writeUI16(tag.height); + + tagw.writeUBits(0, 4); // reserved + tagw.writeUBits(tag.deblocking, 3); + tagw.writeBit(tag.smoothing); + + tagw.writeUI8(tag.codecID); + encodeTag(tag); + } + + public override void doAction(DoAction tag) + { + int adjust = 0; + if (Debug) + { + adjust = writer.Pos + 6; + debug.adjust += adjust; + } + + new ActionEncoder(tagw, debug).encode(tag.actionList); + tagw.writeUI8(0); + encodeTag(tag); + + if (Debug) + { + debug.adjust -= adjust; + } + } + + public override void doInitAction(DoInitAction tag) + { + int adjust = 0; + if (Debug) + { + adjust = writer.Pos + 6; + debug.adjust += adjust; + } + + int idref = dict.getId(tag.sprite); + tagw.writeUI16(idref); + new ActionEncoder(tagw, debug).encode(tag.actionList); + tagw.writeUI8(0); + encodeTag(tag); + + if (Debug) + { + debug.adjust -= adjust; + } + } + + public override void enableDebugger(EnableDebugger tag) + { + tagw.writeString(tag.password); + encodeTag(tag); + } + + public override void enableDebugger2(EnableDebugger tag) + { + // This corresponds to the constant used in the player, + // core/splay.cpp, in ScriptThread::EnableDebugger(). + tagw.writeUI16(0x1975); + tagw.writeString(tag.password); + encodeTag(tag); + } + + public override void exportAssets(ExportAssets tag) + { + tagw.writeUI16(tag.exports.Count); + System.Collections.IEnumerator it = tag.exports.GetEnumerator(); + //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" + while (it.MoveNext()) + { + //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" + DefineTag ref_Renamed = (DefineTag) it.Current; + int idref = dict.getId(ref_Renamed); + tagw.writeUI16(idref); + assert(ref_Renamed.name != null); // exported symbols must have names + tagw.writeString(ref_Renamed.name); + dict.addName(ref_Renamed, ref_Renamed.name); + } + encodeTag(tag); + } + + public override void symbolClass(SymbolClass tag) + { + tagw.writeUI16(tag.class2tag.Count + (tag.topLevelClass != null?1:0)); + //UPGRADE_TODO: Method 'java.util.Map.entrySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapentrySet'" + System.Collections.IEnumerator it = new SupportClass.HashSetSupport(tag.class2tag).GetEnumerator(); + //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" + while (it.MoveNext()) + { + //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" + System.Collections.DictionaryEntry e = (System.Collections.DictionaryEntry) it.Current; + System.String name = (System.String) e.Key; + DefineTag ref_Renamed = (DefineTag) e.Value; + + int idref = dict.getId(ref_Renamed); + tagw.writeUI16(idref); + tagw.writeString(name); + } + if (tag.topLevelClass != null) + { + tagw.writeUI16(0); + tagw.writeString(tag.topLevelClass); + } + encodeTag(tag); + } + + public override void frameLabel(FrameLabel tag) + { + tagw.writeString(tag.label); + if (tag.anchor && SwfVersion >= 6) + { + tagw.writeUI8(1); + } + encodeTag(tag); + } + + public override void importAssets(ImportAssets tag) + { + tagw.writeString(tag.url); + if (tag.code == flash.swf.TagValues_Fields.stagImportAssets2) + { + tagw.writeUI8(tag.downloadNow?1:0); + tagw.writeUI8(tag.SHA1 != null?1:0); + if (tag.SHA1 != null) + { + tagw.write(tag.SHA1); + } + } + tagw.writeUI16(tag.importRecords.Count); + System.Collections.IEnumerator it = tag.importRecords.GetEnumerator(); + //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" + while (it.MoveNext()) + { + //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" + ImportRecord record = (ImportRecord) it.Current; + int id = dict.add(record); + tagw.writeUI16(id); + tagw.writeString(record.name); + } + encodeTag(tag); + } + + public override void importAssets2(ImportAssets tag) + { + importAssets(tag); + } + + public override void jpegTables(GenericTag tag) + { + encodeTagHeader(tag.code, tag.data.Length, false); + writer.write(tag.data); + } + + public override void placeObject(PlaceObject tag) + { + int idref = dict.getId(tag.ref_Renamed); + tagw.writeUI16(idref); + tagw.writeUI16(tag.depth); + encodeMatrix(tag.matrix, tagw); + if (tag.colorTransform != null) + { + encodeCxform(tag.colorTransform, tagw); + } + encodeTag(tag); + } + + public override void placeObject2(PlaceObject tag) + { + placeObject23(tag); + } + + public override void placeObject3(PlaceObject tag) + { + placeObject23(tag); + } + + public virtual void placeObject23(PlaceObject tag) + { + tagw.writeUI8(tag.flags); + if (tag.code == flash.swf.TagValues_Fields.stagPlaceObject3) + { + tagw.writeUI8(tag.flags2); + } + tagw.writeUI16(tag.depth); + if (tag.hasClassName()) + { + tagw.writeString(tag.className); + } + if (tag.hasCharID()) + { + int idref = dict.getId(tag.ref_Renamed); + tagw.writeUI16(idref); + } + if (tag.hasMatrix()) + { + encodeMatrix(tag.matrix, tagw); + } + if (tag.hasCxform()) + { + // ed 5/22/03 the SWF 6 file format spec says this should be a CXFORM, but + // the spec is wrong. the player expects a CXFORMA. + encodeCxforma(((CXFormWithAlpha) tag.colorTransform), tagw); + } + if (tag.hasRatio()) + { + tagw.writeUI16(tag.ratio); + } + if (tag.hasName()) + { + tagw.writeString(tag.name); + } + if (tag.hasClipDepth()) + { + tagw.writeUI16(tag.clipDepth); + } + if (tag.code == flash.swf.TagValues_Fields.stagPlaceObject3) + { + if (tag.hasFilterList()) + { + encodeFilterList(tag.filters, tagw); + } + if (tag.hasBlendMode()) + { + tagw.writeUI8(tag.blendMode); + } + } + if (tag.hasClipAction()) + { + int adjust = 0; + if (Debug) + { + adjust = writer.Pos + 6; + debug.adjust += adjust; + } + new ActionEncoder(tagw, debug).encodeClipActions(tag.clipActions); + if (Debug) + { + debug.adjust -= adjust; + } + } + encodeTag(tag); + } + + public override void protect(GenericTag tag) + { + if (tag.data != null) + { + encodeTagHeader(tag.code, tag.data.Length, false); + writer.write(tag.data); + } + else + { + encodeTagHeader(tag.code, 0, false); + } + } + + public override void removeObject(RemoveObject tag) + { + encodeTagHeader(tag.code, 4, false); + int idref = dict.getId(tag.ref_Renamed); + writer.writeUI16(idref); + writer.writeUI16(tag.depth); + } + + public override void removeObject2(RemoveObject tag) + { + encodeTagHeader(tag.code, 2, false); + writer.writeUI16(tag.depth); + } + + public override void showFrame(ShowFrame tag) + { + encodeTagHeader(tag.code, 0, false); + frames++; + } + + public override void soundStreamBlock(GenericTag tag) + { + encodeTagHeader(tag.code, tag.data.Length, false); + writer.write(tag.data); + } + + public override void soundStreamHead(SoundStreamHead tag) + { + int length = 4; + + // we need to add two bytes for an extra SI16 (latencySeek) + if (tag.compression == SoundStreamHead.sndCompressMP3) + { + length += 2; + } + + encodeTagHeader(tag.code, length, false); + + // 1 byte + writer.writeUBits(0, 4); // reserved + writer.writeUBits(tag.playbackRate, 2); + writer.writeUBits(tag.playbackSize, 1); + writer.writeUBits(tag.playbackType, 1); + + // 1 byte + writer.writeUBits(tag.compression, 4); + writer.writeUBits(tag.streamRate, 2); + writer.writeUBits(tag.streamSize, 1); + writer.writeUBits(tag.streamType, 1); + + // 2 bytes + writer.writeUI16(tag.streamSampleCount); + + if (tag.compression == SoundStreamHead.sndCompressMP3) + { + // 2 bytes + writer.writeSI16(tag.latencySeek); + } + } + + public override void soundStreamHead2(SoundStreamHead tag) + { + soundStreamHead(tag); + } + + public override void startSound(StartSound tag) + { + int idref = dict.getId(tag.sound); + tagw.writeUI16(idref); + encodeSoundInfo(tag.soundInfo, tagw); + encodeTag(tag); + } + + public override void videoFrame(VideoFrame tag) + { + encodeTagHeader(tag.code, 4 + tag.videoData.Length, false); + int idref = dict.getId(tag.stream); + writer.writeUI16(idref); + writer.writeUI16(tag.frameNum); + writer.write(tag.videoData); + } + + public override void defineSceneAndFrameLabelData(DefineSceneAndFrameLabelData tag) + { + encodeTagHeader(tag.code, tag.data.Length, false); + writer.write(tag.data); + } + + public override void doABC(DoABC tag) + { + if (tag.code == flash.swf.TagValues_Fields.stagDoABC2) + { + encodeTagHeader(tag.code, 4 + tag.name.Length + 1 + tag.abc.Length, false); + writer.write32(tag.flag); + writer.writeString(tag.name); + } + else + { + encodeTagHeader(tag.code, tag.abc.Length, false); + } + + writer.write(tag.abc); + } + + public override void unknown(GenericTag tag) + { + encodeTagHeader(tag.code, tag.data.Length, false); + writer.write(tag.data); + } + + public virtual sbyte[] toByteArray() + { + //TODO this could be improved, tricky bit is that writeTo is not trivial + // and has the side effect of compressing (meaning the writer.size() + // may be larger than necessary) + System.IO.MemoryStream out_Renamed = new System.IO.MemoryStream(writer.Length); + writeTo(out_Renamed); + return SupportClass.ToSByteArray(out_Renamed.ToArray()); + } + + public override void scriptLimits(ScriptLimits tag) + { + tagw.writeUI16(tag.scriptRecursionLimit); + tagw.writeUI16(tag.scriptTimeLimit); + encodeTag(tag); + } + } } \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.as3proj new file mode 100644 index 0000000000..71f47c7559 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.as3proj @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.png new file mode 100644 index 0000000000..d1c3fe6222 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.txt new file mode 100644 index 0000000000..645e307742 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/110 ActionScript 3 - Flash IDE Project/Project.txt @@ -0,0 +1 @@ +An empty project written in ActionScript 3 with compilation using the Flash IDE \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.as3proj new file mode 100644 index 0000000000..e8ed942628 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.as3proj @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.png new file mode 100644 index 0000000000..bf1262c6e8 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.txt new file mode 100644 index 0000000000..a6eb1f267c --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/Project.txt @@ -0,0 +1 @@ +A project written in ActionScript 3 for the Flash 9+ Player \ No newline at end of file diff --git a/FlashDevelop/Bin/Debug/Projects/310 Haxe - AS3 Project/bin/expressInstall.swf b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/bin/expressInstall.swf similarity index 100% rename from FlashDevelop/Bin/Debug/Projects/310 Haxe - AS3 Project/bin/expressInstall.swf rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/bin/expressInstall.swf diff --git a/FlashDevelop/Bin/Debug/Projects/310 Haxe - AS3 Project/bin/index.html.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/bin/index.html.template similarity index 100% rename from FlashDevelop/Bin/Debug/Projects/310 Haxe - AS3 Project/bin/index.html.template rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/bin/index.html.template diff --git a/FlashDevelop/Bin/Debug/Projects/310 Haxe - AS3 Project/bin/js/swfobject.js b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/bin/js/swfobject.js similarity index 100% rename from FlashDevelop/Bin/Debug/Projects/310 Haxe - AS3 Project/bin/js/swfobject.js rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/bin/js/swfobject.js diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/src/$(PackagePath)/Main.as.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/src/$(PackagePath)/Main.as.template new file mode 100644 index 0000000000..47dbeffff5 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/120 ActionScript 3 - AS3 Project/src/$(PackagePath)/Main.as.template @@ -0,0 +1,23 @@ +package $(PackageName)$(CSLB){ + import flash.display.Sprite; + import flash.events.Event; + + /** + $(CBI)* ... + $(CBI)* @author $(DefaultUser) + $(CBI)*/ + public class Main extends Sprite $(CSLB){ + + public function Main() $(CSLB){ + if (stage) init(); + else addEventListener(Event.ADDED_TO_STAGE, init); + } + + private function init(e:Event = null):void $(CSLB){ + removeEventListener(Event.ADDED_TO_STAGE, init); + // entry point + } + + } + +} \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.as3proj new file mode 100644 index 0000000000..e8ed942628 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.as3proj @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.png new file mode 100644 index 0000000000..08c1d7238c Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.txt new file mode 100644 index 0000000000..82ae7b6d46 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/Project.txt @@ -0,0 +1 @@ +A project written in ActionScript 3 for the Flash 9+ Player - optimized with a preloader \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/expressInstall.swf b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/expressInstall.swf new file mode 100644 index 0000000000..86958bf3a7 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/expressInstall.swf differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/index.html.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/index.html.template new file mode 100644 index 0000000000..d07510f497 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/index.html.template @@ -0,0 +1,40 @@ + + + + + $(ProjectName) + + + + + + + +
    +

    $(ProjectName)

    +

    Get Adobe Flash player

    +
    + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/js/swfobject.js b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/js/swfobject.js new file mode 100644 index 0000000000..8eafe9dd83 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/130 ActionScript 3 - AS3 Project with Preloader/bin/js/swfobject.js @@ -0,0 +1,4 @@ +/* SWFObject v2.2 + is released under the MIT License +*/ +var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y0){for(var af=0;af0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad'}}aa.outerHTML='"+af+"";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + build.bat "$(CompilerPath)" + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/Project.png new file mode 100644 index 0000000000..bf1262c6e8 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/Project.txt new file mode 100644 index 0000000000..41d7c6a41e --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/Project.txt @@ -0,0 +1 @@ +An ActionScript 3 library (SWC) project to compile with an 'ant' script. \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/build.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/build.bat new file mode 100644 index 0000000000..223f8d56d4 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/build.bat @@ -0,0 +1,8 @@ +@echo off + +:: set environment +if not "%~1"=="" set FLEX_HOME=%~1 + +:: build +echo build with %FLEX_HOME% +ant diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/build.xml.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/build.xml.template new file mode 100644 index 0000000000..c279f53bcc --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/build.xml.template @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FlashDevelop/Bin/Debug/Projects/315 Haxe - AIR AS3 Projector/bin/.empty b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/lib/.empty similarity index 100% rename from FlashDevelop/Bin/Debug/Projects/315 Haxe - AIR AS3 Projector/bin/.empty rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/lib/.empty diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/src/$(PackagePath)/$(ProjectID).as.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/src/$(PackagePath)/$(ProjectID).as.template new file mode 100644 index 0000000000..5da7c3a3b7 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/135 ActionScript 3 - AS3 Library SWC/src/$(PackagePath)/$(ProjectID).as.template @@ -0,0 +1,15 @@ +package $(PackageName)$(CSLB){ + + /** + $(CBI)* ... + $(CBI)* @author $(DefaultUser) + $(CBI)*/ + public class $(ProjectID) { + + public function $(ProjectID)() $(CSLB){ + + } + + } + +} \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.as3proj new file mode 100644 index 0000000000..12669b4be5 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.as3proj @@ -0,0 +1,81 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.png new file mode 100644 index 0000000000..8dc30ca1af Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.txt new file mode 100644 index 0000000000..35a213b47d --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/Project.txt @@ -0,0 +1 @@ +An ActionScript 3 project that uses MXML and the Flex 3 Framework \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/expressInstall.swf b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/expressInstall.swf new file mode 100644 index 0000000000..86958bf3a7 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/expressInstall.swf differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/index.html.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/index.html.template new file mode 100644 index 0000000000..d07510f497 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/index.html.template @@ -0,0 +1,40 @@ + + + + + $(ProjectName) + + + + + + + +
    +

    $(ProjectName)

    +

    Get Adobe Flash player

    +
    + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/js/swfobject.js b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/js/swfobject.js new file mode 100644 index 0000000000..8eafe9dd83 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/140 ActionScript 3 - Flex 3 Project/bin/js/swfobject.js @@ -0,0 +1,4 @@ +/* SWFObject v2.2 + is released under the MIT License +*/ +var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y0){for(var af=0;af0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad'}}aa.outerHTML='"+af+"";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.as3proj new file mode 100644 index 0000000000..a963c6b5b3 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.as3proj @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.png new file mode 100644 index 0000000000..33031dea06 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.txt new file mode 100644 index 0000000000..30a7e620b5 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/Project.txt @@ -0,0 +1 @@ +An ActionScript 3 project that uses MXML and the Flex 4 Framework \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/expressInstall.swf b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/expressInstall.swf new file mode 100644 index 0000000000..86958bf3a7 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/expressInstall.swf differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/index.html.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/index.html.template new file mode 100644 index 0000000000..d07510f497 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/index.html.template @@ -0,0 +1,40 @@ + + + + + $(ProjectName) + + + + + + + +
    +

    $(ProjectName)

    +

    Get Adobe Flash player

    +
    + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/js/swfobject.js b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/js/swfobject.js new file mode 100644 index 0000000000..8eafe9dd83 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/150 ActionScript 3 - Flex 4 Project/bin/js/swfobject.js @@ -0,0 +1,4 @@ +/* SWFObject v2.2 + is released under the MIT License +*/ +var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y0){for(var af=0;af0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad'}}aa.outerHTML='"+af+"";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/AIR_readme.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/AIR_readme.txt new file mode 100644 index 0000000000..75d1a6acdb --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/AIR_readme.txt @@ -0,0 +1,20 @@ +AIR for desktop instructions + +1. Configuration + + - edit 'bat\SetupSDK.bat' for the path to Flex SDK (defaults should be ok) + + +2. Creating a self-signed certificate: + + - run 'bat\CreateCertificate.bat' to generate your self-signed certificate, + + (!) wait a minute before packaging. + + +3. Run/debug from FlashDevelop as usual (build F8, build&run F5 or Ctrl+Enter) + + +4. Packaging for release: + + - run 'bat\PackageApp.bat' to only create the AIR setup diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.as3proj new file mode 100644 index 0000000000..27c6e874ac --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.as3proj @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.png new file mode 100644 index 0000000000..5cad22b601 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.txt new file mode 100644 index 0000000000..242a035de9 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/Project.txt @@ -0,0 +1 @@ +An AIR projector written in ActionScript 3 \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/application.xml.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/application.xml.template new file mode 100644 index 0000000000..24c7106b31 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/application.xml.template @@ -0,0 +1,27 @@ + + + + $(PACKAGEDOT)$(PROJECTID) + 1.0 + $(PROJECTID) + + $(PROJECTNAME) + + + + + $(PROJECTNAME) + $(PROJECTID).swf + standard + false + true + true + true + true + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/CreateCertificate.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/CreateCertificate.bat new file mode 100644 index 0000000000..f9a51a57f9 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/CreateCertificate.bat @@ -0,0 +1,34 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:: Generate +echo. +echo Generating a self-signed certificate... +call adt -certificate -cn %CERT_NAME% 2048-RSA %CERT_FILE% %CERT_PASS% +if errorlevel 1 goto failed + +:succeed +echo. +echo Certificate created: %CERT_FILE% with password "%CERT_PASS%" +echo. +if "%CERT_PASS%" == "fd" echo Note: You did not change the default password +echo. +echo HINTS: +echo - you only need to generate this certificate once, +echo - wait a minute before using this certificate to package your AIR application. +echo. +goto end + +:failed +echo. +echo Certificate creation FAILED. +echo. + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/PackageApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/PackageApp.bat new file mode 100644 index 0000000000..59aed98b63 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/PackageApp.bat @@ -0,0 +1,15 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +set AIR_TARGET= +::set AIR_TARGET=-captive-runtime +set OPTIONS=-tsa none +call bat\Packager.bat + +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/Packager.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/Packager.bat new file mode 100644 index 0000000000..03a520e1a7 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/Packager.bat @@ -0,0 +1,39 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +if not exist %CERT_FILE% goto certificate + +:: AIR output +if not exist %AIR_PATH% md %AIR_PATH% +set OUTPUT=%AIR_PATH%\%AIR_NAME%%AIR_TARGET%.air + +:: Package +echo. +echo Packaging %AIR_NAME%%AIR_TARGET%.air using certificate %CERT_FILE%... +call adt -package %OPTIONS% %SIGNING_OPTIONS% %OUTPUT% %APP_XML% %FILE_OR_DIR% +if errorlevel 1 goto failed +goto end + +:certificate +echo. +echo Certificate not found: %CERT_FILE% +echo. +echo Troubleshooting: +echo - generate a default certificate using 'bat\CreateCertificate.bat' +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:failed +echo AIR setup creation FAILED. +echo. +echo Troubleshooting: +echo - verify AIR SDK target version in %APP_XML% +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:end +echo. diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/RunApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/RunApp.bat new file mode 100644 index 0000000000..5b00357b4f --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/RunApp.bat @@ -0,0 +1,21 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +echo. +echo Starting AIR Debug Launcher... +echo. + +adl "%APP_XML%" "%APP_DIR%" +if errorlevel 1 goto error +goto end + +:error +pause + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/SetupApp.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/SetupApp.bat.template new file mode 100644 index 0000000000..afe57569cc --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/SetupApp.bat.template @@ -0,0 +1,47 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: About AIR application packaging +:: http://livedocs.adobe.com/flex/3/html/help.html?content=CommandLineTools_5.html#1035959 +:: http://livedocs.adobe.com/flex/3/html/distributing_apps_4.html#1037515 + +:: NOTICE: all paths are relative to project root + +:: Your certificate information +set CERT_NAME="$(PROJECTNAME)" +set CERT_PASS=fd +set CERT_FILE="bat\$(PROJECTID).p12" +set SIGNING_OPTIONS=-storetype pkcs12 -keystore %CERT_FILE% -storepass %CERT_PASS% + +:: Application descriptor +set APP_XML=application.xml + +:: Files to package +set APP_DIR=bin +set FILE_OR_DIR=-C %APP_DIR% . + +:: Your application ID (must match of Application descriptor) and remove spaces +for /f "tokens=3 delims=<>" %%a in ('findstr /R /C:"^[ ]*" %APP_XML%') do set APP_ID=%%a +set APP_ID=%APP_ID: =% + +:: Output +set AIR_PATH=air +set AIR_NAME=$(PROJECTID) + +:validation +findstr /C:"%APP_ID%" "%APP_XML%" > NUL +if errorlevel 1 goto badid +goto end + +:badid +echo. +echo ERROR: +echo Application ID in 'bat\SetupApp.bat' (APP_ID) +echo does NOT match Application descriptor '%APP_XML%' (id) +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/SetupSDK.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/SetupSDK.bat.template new file mode 100644 index 0000000000..55942b9136 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bat/SetupSDK.bat.template @@ -0,0 +1,26 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: Static path to Flex SDK +set FLEX_SDK=$(FlexSDK) + +:: Use FD supplied SDK path if executed from FD +if exist "%FD_CUR_SDK%" set FLEX_SDK=%FD_CUR_SDK% + +:validation +if not exist "%FLEX_SDK%\bin" goto flexsdk +goto succeed + +:flexsdk +echo. +echo ERROR: incorrect path to Flex SDK in 'bat\SetupSDK.bat' +echo. +echo Looking for: %FLEX_SDK%\bin +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:succeed +set PATH=%FLEX_SDK%\bin;%PATH% diff --git a/FlashDevelop/Bin/Debug/Projects/370 Haxe - NME Project/assets/img/.empty b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bin/.empty similarity index 100% rename from FlashDevelop/Bin/Debug/Projects/370 Haxe - NME Project/assets/img/.empty rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/bin/.empty diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/src/$(PackagePath)/Main.as.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/src/$(PackagePath)/Main.as.template new file mode 100644 index 0000000000..3d011abc2c --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/160 ActionScript 3 - AIR AS3 Projector/src/$(PackagePath)/Main.as.template @@ -0,0 +1,16 @@ +package $(PackageName)$(CSLB){ + import flash.display.Sprite; + + /** + $(CBI)* ... + $(CBI)* @author $(DefaultUser) + $(CBI)*/ + public class Main extends Sprite $(CSLB){ + + public function Main() $(CSLB){ + + } + + } + +} \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/AIR_readme.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/AIR_readme.txt new file mode 100644 index 0000000000..75d1a6acdb --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/AIR_readme.txt @@ -0,0 +1,20 @@ +AIR for desktop instructions + +1. Configuration + + - edit 'bat\SetupSDK.bat' for the path to Flex SDK (defaults should be ok) + + +2. Creating a self-signed certificate: + + - run 'bat\CreateCertificate.bat' to generate your self-signed certificate, + + (!) wait a minute before packaging. + + +3. Run/debug from FlashDevelop as usual (build F8, build&run F5 or Ctrl+Enter) + + +4. Packaging for release: + + - run 'bat\PackageApp.bat' to only create the AIR setup diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.as3proj new file mode 100644 index 0000000000..8f00e65ec1 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.as3proj @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.png new file mode 100644 index 0000000000..5cad22b601 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.txt new file mode 100644 index 0000000000..aa90493fb8 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/Project.txt @@ -0,0 +1 @@ +An AIR projector that uses MXML and the Flex 3 Framework \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/application.xml.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/application.xml.template new file mode 100644 index 0000000000..8f56518ea0 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/application.xml.template @@ -0,0 +1,27 @@ + + + + $(PACKAGEDOT)$(PROJECTID) + 1.0 + $(PROJECTID) + + $(PROJECTNAME) + + + + + $(PROJECTNAME) + $(PROJECTID).swf + standard + false + true + true + true + true + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/CreateCertificate.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/CreateCertificate.bat new file mode 100644 index 0000000000..f9a51a57f9 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/CreateCertificate.bat @@ -0,0 +1,34 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:: Generate +echo. +echo Generating a self-signed certificate... +call adt -certificate -cn %CERT_NAME% 2048-RSA %CERT_FILE% %CERT_PASS% +if errorlevel 1 goto failed + +:succeed +echo. +echo Certificate created: %CERT_FILE% with password "%CERT_PASS%" +echo. +if "%CERT_PASS%" == "fd" echo Note: You did not change the default password +echo. +echo HINTS: +echo - you only need to generate this certificate once, +echo - wait a minute before using this certificate to package your AIR application. +echo. +goto end + +:failed +echo. +echo Certificate creation FAILED. +echo. + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/PackageApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/PackageApp.bat new file mode 100644 index 0000000000..59aed98b63 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/PackageApp.bat @@ -0,0 +1,15 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +set AIR_TARGET= +::set AIR_TARGET=-captive-runtime +set OPTIONS=-tsa none +call bat\Packager.bat + +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/Packager.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/Packager.bat new file mode 100644 index 0000000000..03a520e1a7 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/Packager.bat @@ -0,0 +1,39 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +if not exist %CERT_FILE% goto certificate + +:: AIR output +if not exist %AIR_PATH% md %AIR_PATH% +set OUTPUT=%AIR_PATH%\%AIR_NAME%%AIR_TARGET%.air + +:: Package +echo. +echo Packaging %AIR_NAME%%AIR_TARGET%.air using certificate %CERT_FILE%... +call adt -package %OPTIONS% %SIGNING_OPTIONS% %OUTPUT% %APP_XML% %FILE_OR_DIR% +if errorlevel 1 goto failed +goto end + +:certificate +echo. +echo Certificate not found: %CERT_FILE% +echo. +echo Troubleshooting: +echo - generate a default certificate using 'bat\CreateCertificate.bat' +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:failed +echo AIR setup creation FAILED. +echo. +echo Troubleshooting: +echo - verify AIR SDK target version in %APP_XML% +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:end +echo. diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/RunApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/RunApp.bat new file mode 100644 index 0000000000..5b00357b4f --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/RunApp.bat @@ -0,0 +1,21 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +echo. +echo Starting AIR Debug Launcher... +echo. + +adl "%APP_XML%" "%APP_DIR%" +if errorlevel 1 goto error +goto end + +:error +pause + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/SetupApp.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/SetupApp.bat.template new file mode 100644 index 0000000000..afe57569cc --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/SetupApp.bat.template @@ -0,0 +1,47 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: About AIR application packaging +:: http://livedocs.adobe.com/flex/3/html/help.html?content=CommandLineTools_5.html#1035959 +:: http://livedocs.adobe.com/flex/3/html/distributing_apps_4.html#1037515 + +:: NOTICE: all paths are relative to project root + +:: Your certificate information +set CERT_NAME="$(PROJECTNAME)" +set CERT_PASS=fd +set CERT_FILE="bat\$(PROJECTID).p12" +set SIGNING_OPTIONS=-storetype pkcs12 -keystore %CERT_FILE% -storepass %CERT_PASS% + +:: Application descriptor +set APP_XML=application.xml + +:: Files to package +set APP_DIR=bin +set FILE_OR_DIR=-C %APP_DIR% . + +:: Your application ID (must match of Application descriptor) and remove spaces +for /f "tokens=3 delims=<>" %%a in ('findstr /R /C:"^[ ]*" %APP_XML%') do set APP_ID=%%a +set APP_ID=%APP_ID: =% + +:: Output +set AIR_PATH=air +set AIR_NAME=$(PROJECTID) + +:validation +findstr /C:"%APP_ID%" "%APP_XML%" > NUL +if errorlevel 1 goto badid +goto end + +:badid +echo. +echo ERROR: +echo Application ID in 'bat\SetupApp.bat' (APP_ID) +echo does NOT match Application descriptor '%APP_XML%' (id) +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/SetupSDK.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/SetupSDK.bat.template new file mode 100644 index 0000000000..55942b9136 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bat/SetupSDK.bat.template @@ -0,0 +1,26 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: Static path to Flex SDK +set FLEX_SDK=$(FlexSDK) + +:: Use FD supplied SDK path if executed from FD +if exist "%FD_CUR_SDK%" set FLEX_SDK=%FD_CUR_SDK% + +:validation +if not exist "%FLEX_SDK%\bin" goto flexsdk +goto succeed + +:flexsdk +echo. +echo ERROR: incorrect path to Flex SDK in 'bat\SetupSDK.bat' +echo. +echo Looking for: %FLEX_SDK%\bin +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:succeed +set PATH=%FLEX_SDK%\bin;%PATH% diff --git a/FlashDevelop/Bin/Debug/Projects/370 Haxe - NME Project/bin/.empty b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bin/.empty similarity index 100% rename from FlashDevelop/Bin/Debug/Projects/370 Haxe - NME Project/bin/.empty rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/bin/.empty diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/src/$(PackagePath)/Main.mxml b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/src/$(PackagePath)/Main.mxml new file mode 100644 index 0000000000..38f80a3fc9 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/170 ActionScript 3 - AIR Flex 3 Projector/src/$(PackagePath)/Main.mxml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/AIR_readme.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/AIR_readme.txt new file mode 100644 index 0000000000..75d1a6acdb --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/AIR_readme.txt @@ -0,0 +1,20 @@ +AIR for desktop instructions + +1. Configuration + + - edit 'bat\SetupSDK.bat' for the path to Flex SDK (defaults should be ok) + + +2. Creating a self-signed certificate: + + - run 'bat\CreateCertificate.bat' to generate your self-signed certificate, + + (!) wait a minute before packaging. + + +3. Run/debug from FlashDevelop as usual (build F8, build&run F5 or Ctrl+Enter) + + +4. Packaging for release: + + - run 'bat\PackageApp.bat' to only create the AIR setup diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.as3proj new file mode 100644 index 0000000000..72242b4dd2 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.as3proj @@ -0,0 +1,83 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.png new file mode 100644 index 0000000000..5cad22b601 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.txt new file mode 100644 index 0000000000..48c6e87f13 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/Project.txt @@ -0,0 +1 @@ +An AIR projector that uses MXML and the Flex 4 Framework \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/application.xml.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/application.xml.template new file mode 100644 index 0000000000..25f8745565 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/application.xml.template @@ -0,0 +1,27 @@ + + + + $(PACKAGEDOT)$(PROJECTID) + 1.0 + $(PROJECTID) + + $(PROJECTNAME) + + + + + $(PROJECTNAME) + $(PROJECTID).swf + standard + false + true + true + true + true + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/CreateCertificate.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/CreateCertificate.bat new file mode 100644 index 0000000000..f9a51a57f9 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/CreateCertificate.bat @@ -0,0 +1,34 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:: Generate +echo. +echo Generating a self-signed certificate... +call adt -certificate -cn %CERT_NAME% 2048-RSA %CERT_FILE% %CERT_PASS% +if errorlevel 1 goto failed + +:succeed +echo. +echo Certificate created: %CERT_FILE% with password "%CERT_PASS%" +echo. +if "%CERT_PASS%" == "fd" echo Note: You did not change the default password +echo. +echo HINTS: +echo - you only need to generate this certificate once, +echo - wait a minute before using this certificate to package your AIR application. +echo. +goto end + +:failed +echo. +echo Certificate creation FAILED. +echo. + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/PackageApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/PackageApp.bat new file mode 100644 index 0000000000..59aed98b63 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/PackageApp.bat @@ -0,0 +1,15 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +set AIR_TARGET= +::set AIR_TARGET=-captive-runtime +set OPTIONS=-tsa none +call bat\Packager.bat + +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/Packager.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/Packager.bat new file mode 100644 index 0000000000..03a520e1a7 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/Packager.bat @@ -0,0 +1,39 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +if not exist %CERT_FILE% goto certificate + +:: AIR output +if not exist %AIR_PATH% md %AIR_PATH% +set OUTPUT=%AIR_PATH%\%AIR_NAME%%AIR_TARGET%.air + +:: Package +echo. +echo Packaging %AIR_NAME%%AIR_TARGET%.air using certificate %CERT_FILE%... +call adt -package %OPTIONS% %SIGNING_OPTIONS% %OUTPUT% %APP_XML% %FILE_OR_DIR% +if errorlevel 1 goto failed +goto end + +:certificate +echo. +echo Certificate not found: %CERT_FILE% +echo. +echo Troubleshooting: +echo - generate a default certificate using 'bat\CreateCertificate.bat' +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:failed +echo AIR setup creation FAILED. +echo. +echo Troubleshooting: +echo - verify AIR SDK target version in %APP_XML% +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:end +echo. diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/RunApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/RunApp.bat new file mode 100644 index 0000000000..5b00357b4f --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/RunApp.bat @@ -0,0 +1,21 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +echo. +echo Starting AIR Debug Launcher... +echo. + +adl "%APP_XML%" "%APP_DIR%" +if errorlevel 1 goto error +goto end + +:error +pause + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/SetupApp.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/SetupApp.bat.template new file mode 100644 index 0000000000..afe57569cc --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/SetupApp.bat.template @@ -0,0 +1,47 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: About AIR application packaging +:: http://livedocs.adobe.com/flex/3/html/help.html?content=CommandLineTools_5.html#1035959 +:: http://livedocs.adobe.com/flex/3/html/distributing_apps_4.html#1037515 + +:: NOTICE: all paths are relative to project root + +:: Your certificate information +set CERT_NAME="$(PROJECTNAME)" +set CERT_PASS=fd +set CERT_FILE="bat\$(PROJECTID).p12" +set SIGNING_OPTIONS=-storetype pkcs12 -keystore %CERT_FILE% -storepass %CERT_PASS% + +:: Application descriptor +set APP_XML=application.xml + +:: Files to package +set APP_DIR=bin +set FILE_OR_DIR=-C %APP_DIR% . + +:: Your application ID (must match of Application descriptor) and remove spaces +for /f "tokens=3 delims=<>" %%a in ('findstr /R /C:"^[ ]*" %APP_XML%') do set APP_ID=%%a +set APP_ID=%APP_ID: =% + +:: Output +set AIR_PATH=air +set AIR_NAME=$(PROJECTID) + +:validation +findstr /C:"%APP_ID%" "%APP_XML%" > NUL +if errorlevel 1 goto badid +goto end + +:badid +echo. +echo ERROR: +echo Application ID in 'bat\SetupApp.bat' (APP_ID) +echo does NOT match Application descriptor '%APP_XML%' (id) +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/SetupSDK.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/SetupSDK.bat.template new file mode 100644 index 0000000000..55942b9136 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bat/SetupSDK.bat.template @@ -0,0 +1,26 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: Static path to Flex SDK +set FLEX_SDK=$(FlexSDK) + +:: Use FD supplied SDK path if executed from FD +if exist "%FD_CUR_SDK%" set FLEX_SDK=%FD_CUR_SDK% + +:validation +if not exist "%FLEX_SDK%\bin" goto flexsdk +goto succeed + +:flexsdk +echo. +echo ERROR: incorrect path to Flex SDK in 'bat\SetupSDK.bat' +echo. +echo Looking for: %FLEX_SDK%\bin +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:succeed +set PATH=%FLEX_SDK%\bin;%PATH% diff --git a/FlashDevelop/Bin/Debug/Templates/ProjectFiles/AS2Project/Empty File.txt.fdt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bin/.empty similarity index 100% rename from FlashDevelop/Bin/Debug/Templates/ProjectFiles/AS2Project/Empty File.txt.fdt rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/bin/.empty diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/src/$(PackagePath)/Main.mxml b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/src/$(PackagePath)/Main.mxml new file mode 100644 index 0000000000..b1a0a9c28c --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/180 ActionScript 3 - AIR Flex 4 Projector/src/$(PackagePath)/Main.mxml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/AIR_Android_readme.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/AIR_Android_readme.txt new file mode 100644 index 0000000000..3a50c8cc03 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/AIR_Android_readme.txt @@ -0,0 +1,48 @@ +AIR for Android instructions + +1. Configuration: + + - edit 'bat\SetupSDK.bat' for paths to Flex SDK and Android SDK (defaults should be ok) + + - install your device's USB drivers: + http://developer.android.com/sdk/oem-usb.html + - enable "USB debugging" on your Android device: + Parameters > Applications > Development > USB Debugging + + +2. Creating a self-signed certificate: + + - run 'bat\CreateCertificate.bat' to generate your self-signed certificate, + + (!) wait a minute before packaging. + + +3. Build from FlashDevelop as usual (F8) + + +4. Run/debug the application on the desktop as usual (F5 or Ctrl+Enter) + + +5. Install AIR runtime on your device: + + - run 'bat\InstallAirRuntime.bat' + + +6. Running/debugging the application on the device: + + 6.a. Build/Debug directly on device + - edit 'bat\RunApp.bat' and change the run target 'goto desktop' by 'goto android-debug' + - build & run as usual (Ctrl+Enter or F5) to package, install & run the application on your device + + 6.b. Debug occasionally on device + - Debug-build from FlashDevelop (F8) + - run 'bat\PackageApp.bat' to package and install a debug version of the application + - start FlashDevelop debugger: Debug > Start Remote Session + - start the application on device + - the application should connect to FlashDevelop interactive debugger as usual + + +7. Packaging for release: + + - Release-build from FlashDevelop (F8) + - run 'bat\PackageApp.bat' and select Android/normal target diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/AIR_iOS_readme.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/AIR_iOS_readme.txt new file mode 100644 index 0000000000..02d430c7fa --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/AIR_iOS_readme.txt @@ -0,0 +1,75 @@ +AIR for iOS instructions + +1. Configuration: + + - edit 'bat\SetupSDK.bat' for path to Flex SDK (defaults should be ok) + +3. Build from FlashDevelop as usual (F8) + +4. Run/debug the application on the desktop as usual (F5 or Ctrl+Enter) + +5. Configure for iOS packaging in 'bat\SetupApp.bat': + + Take a deep breath, pay the Apple tax and read extra carefully this tutorial: + - http://www.codeandvisual.com/2011/exporting-for-iphone-using-air-27-and-flashdevelop-part-three-generating-developer-certificates-provisioning-profiles-and-p12-files/ + + Now this is how to create the p12 key entirely on Windows (steps 1. to 8.): + - http://connorullmann.com/2011/04/air-2-6-and-ios/ + + Then for each project you'll have to go to on Apple's iOS Provisioning Portal: + - create a new App ID with: name of the project and ID indicated in 'application.xml', + - create a new Provisioning Profile: select App ID & registered devices that will be allowed to install the app. + + Once you have obtained a .p12 and .mobileprovision file from Apple's Provisioning Portal: + - save a copy of your .p12 and .mobileprovision certificates in the 'cert\' folder in your FlashDevelop project. + (make sure to keep an extra copy of these 2 files in a safe place) + + Finally edit 'bat\SetupApp.bat' and complete the following lines: + + - IOS_DEV_CERT_FILE: path to your iOS developer 'p12' key ('cert\' folder, if you have followed the instructions above) + - IOS_DEV_CERT_PASS: developer certificate's password + if you don't set it, remove "-storepass %IOS_DEV_CERT_PASS%" from the IOS_SIGNING_OPTIONS, + you'll be prompted to type it when packaging. + - IOS_PROVISION: path to the project's Provisioning Profile file + + For example: + + set IOS_DIST_CERT_FILE=cert\iphone_dev.p12 + set IOS_DEV_CERT_FILE=cert\iphone_dev.p12 + set IOS_DEV_CERT_PASS=YourPassword + set IOS_PROVISION=cert\YourFileName.mobileprovision + + +6. Running/debugging the application on the device: + + Note: if are testing your application for performance, always package for release (see step 7.) + + 6.a. Build/Debug on device + - edit 'bat\RunApp.bat' and change the run target 'goto desktop' by 'goto ios-debug' + - build as usual (Ctrl+Enter or F5) to package + - you'll still have to manually upload & run the app on the device + - the application should connect to FlashDevelop interactive debugger as usual + + 6.b. Debug occasionally on device + - Debug-build from FlashDevelop (F8) + - run 'bat\PackageApp.bat' to package and install a debug version of the application + - start FlashDevelop debugger: Debug > Start Remote Session + - start the application on device + - the application should connect to FlashDevelop interactive debugger as usual + + +7. Packaging for release: + + - edit 'bat\SetupApp.bat' to add the path to your "distribution" certificate (IOS_DIST_CERT_FILE) + Note: you can package ad-hoc IPAs using your developer certificate. + + - Release-build from FlashDevelop (F8) + - run 'bat\PackageApp.bat' and select + either iOS/"ad-hoc" for installation on test devices + or iOS/App Store for upload in the iOS App Store. + +Tips: +- iFunBox: iTunes replacement; installs app faster even if app version doesn't change, +- TestFlightApp: ad-hoc distribution service http://testflightapp.com +- HockeyKit: self hosted ad-hoc distribution https://github.com/TheRealKerni/HockeyKit +- Manual ad-hoc distribution: http://samvermette.com/71 diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.as3proj new file mode 100644 index 0000000000..c36ebd068d --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.as3proj @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.png new file mode 100644 index 0000000000..bd84420d38 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.txt new file mode 100644 index 0000000000..5fa873d1c2 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/Project.txt @@ -0,0 +1 @@ +An AIR mobile app written in ActionScript 3 \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/application.xml.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/application.xml.template new file mode 100644 index 0000000000..21d8a8f3ad --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/application.xml.template @@ -0,0 +1,85 @@ + + + + air.$(PACKAGEDOT)$(PROJECTID) + 0.1 + mobileDevice + $(PROJECTID) + + $(PROJECTNAME) + + + + + + + + + + + ]]> + + + UIStatusBarStyle + UIStatusBarStyleBlackOpaque + UIRequiresPersistentWiFi + NO + UIPrerenderedIcon + + UIApplicationExitsOnSuspend + + + UIDeviceFamily + + + 1 + + + + + ]]> + high + + + + $(PROJECTNAME) + $(PROJECTID).swf + true + true + + + direct + + + + + icons/icon_48.png + icons/icon_57.png + icons/icon_72.png + icons/icon_76.png + icons/icon_96.png + icons/icon_114.png + icons/icon_120.png + icons/icon_144.png + icons/icon_152.png + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/CreateCertificate.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/CreateCertificate.bat new file mode 100644 index 0000000000..d2808914b9 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/CreateCertificate.bat @@ -0,0 +1,34 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:: Generate +echo. +echo Generating a self-signed certificate for Android packaging +call adt -certificate -validityPeriod 25 -cn %AND_CERT_NAME% 2048-RSA "%AND_CERT_FILE%" %AND_CERT_PASS% +if errorlevel 1 goto failed + +:succeed +echo. +echo Certificate created: %AND_CERT_FILE% with password "%AND_CERT_PASS%" +echo. +if "%AND_CERT_PASS%" == "fd" echo Note: you did not change the default password +echo. +echo HINTS: +echo - you only need to generate this certificate once, +echo - wait a minute before using this certificate to package your AIR application. +echo. +goto end + +:failed +echo. +echo Certificate creation FAILED. +echo. + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/InstallAirRuntime.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/InstallAirRuntime.bat new file mode 100644 index 0000000000..7e9e16f470 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/InstallAirRuntime.bat @@ -0,0 +1,31 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat + +:: AIR runtime installer +set AIR_INSTALLER=%FLEX_SDK%\runtimes\air\android\device\runtime.apk + +:: Install +adb devices +echo. +echo Installing AIR runtime on current device: +echo %AIR_INSTALLER% +echo. +adb install "%AIR_INSTALLER%" +echo. +if errorlevel 1 goto failed +goto end + +:failed +echo Troubleshooting: +echo - one, and only one, Android device should be connected +echo - verify 'bat\SetupSDK.bat' +echo. +goto end + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/PackageApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/PackageApp.bat new file mode 100644 index 0000000000..e9dc50ecd1 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/PackageApp.bat @@ -0,0 +1,87 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:menu +echo. +echo Package for target +echo. +echo Android: +echo. +echo [1] normal (apk) +echo [2] debug (apk-debug) +echo [3] captive (apk-captive-runtime) +echo. +echo iOS: +echo. +echo [4] fast test (ipa-test-interpreter) +echo [5] fast debug (ipa-debug-interpreter) +echo [6] slow test (ipa-test) +echo [7] slow debug (ipa-debug) +echo [8] "ad-hoc" (ipa-ad-hoc) +echo [9] App Store (ipa-app-store) +echo. + +:choice +set /P C=[Choice]: +echo. + +set PLATFORM=android +set OPTIONS= +if %C% GTR 3 set PLATFORM=ios +if %C% GTR 7 set PLATFORM=ios-dist + +if "%C%"=="1" set TARGET= +if "%C%"=="2" set TARGET=-debug +if "%C%"=="2" set OPTIONS=-connect %DEBUG_IP% +if "%C%"=="3" set TARGET=-captive-runtime + +if "%C%"=="4" set TARGET=-test-interpreter +if "%C%"=="5" set TARGET=-debug-interpreter +if "%C%"=="5" set OPTIONS=-connect %DEBUG_IP% +if "%C%"=="6" set TARGET=-test +if "%C%"=="7" set TARGET=-debug +if "%C%"=="7" set OPTIONS=-connect %DEBUG_IP% +if "%C%"=="8" set TARGET=-ad-hoc +if "%C%"=="9" set TARGET=-app-store + +call bat\Packager.bat + +if "%PLATFORM%"=="android" goto android-package + +:ios-package +if "%AUTO_INSTALL_IOS%" == "yes" goto ios-install +echo Now manually install and start application on device +echo. +goto end + +:ios-install +echo Installing application for testing on iOS (%DEBUG_IP%) +echo. +call adt -installApp -platform ios -package "%OUTPUT%" +if errorlevel 1 goto installfail + +echo Now manually start application on device +echo. +goto end + +:android-package +adb devices +echo. +echo Installing %OUTPUT% on the device... +echo. +adb -d install -r "%OUTPUT%" +if errorlevel 1 goto installfail +goto end + +:installfail +echo. +echo Installing the app on the device failed + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/Packager.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/Packager.bat new file mode 100644 index 0000000000..2c005b0034 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/Packager.bat @@ -0,0 +1,76 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +if "%PLATFORM%"=="android" goto android-config +if "%PLATFORM%"=="ios" goto ios-config +if "%PLATFORM%"=="ios-dist" goto ios-dist-config +goto start + +:android-config +set CERT_FILE=%AND_CERT_FILE% +set SIGNING_OPTIONS=%AND_SIGNING_OPTIONS% +set ICONS=%AND_ICONS% +set DIST_EXT=apk +set TYPE=apk +goto start + +:ios-config +set CERT_FILE=%IOS_DEV_CERT_FILE% +set SIGNING_OPTIONS=%IOS_DEV_SIGNING_OPTIONS% +set ICONS=%IOS_ICONS% +set DIST_EXT=ipa +set TYPE=ipa +goto start +:: Set working dir +cd %~dp0 & cd .. + +:ios-dist-config +set CERT_FILE=%IOS_DIST_CERT_FILE% +set SIGNING_OPTIONS=%IOS_DIST_SIGNING_OPTIONS% +set ICONS=%IOS_ICONS% +set DIST_EXT=ipa +set TYPE=ipa +goto start + +:start +if not exist "%CERT_FILE%" goto certificate +:: Output file +set FILE_OR_DIR=%FILE_OR_DIR% -C "%ICONS%" . +if not exist "%DIST_PATH%" md "%DIST_PATH%" +set OUTPUT=%DIST_PATH%\%DIST_NAME%%TARGET%.%DIST_EXT% +:: Package +echo Packaging: %OUTPUT% +echo using certificate: %CERT_FILE%... +echo. +call adt -package -target %TYPE%%TARGET% %OPTIONS% %SIGNING_OPTIONS% "%OUTPUT%" "%APP_XML%" %FILE_OR_DIR% +echo. +if errorlevel 1 goto failed +goto end + +:certificate +echo Certificate not found: %CERT_FILE% +echo. +echo Android: +echo - generate a default certificate using 'bat\CreateCertificate.bat' +echo or configure a specific certificate in 'bat\SetupApp.bat'. +echo. +echo iOS: +echo - configure your developer key and project's Provisioning Profile +echo in 'bat\SetupApp.bat'. +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:failed +echo APK setup creation FAILED. +echo. +echo Troubleshooting: +echo - verify AIR SDK target version in %APP_XML% +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:end + diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/RunApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/RunApp.bat new file mode 100644 index 0000000000..9a06a2115e --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/RunApp.bat @@ -0,0 +1,112 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:target +goto desktop +::goto android-debug +::goto android-test +set INTERPRETER=-interpreter +::goto ios-debug +::goto ios-test + +:desktop +:: http://help.adobe.com/en_US/air/build/WSfffb011ac560372f-6fa6d7e0128cca93d31-8000.html + +set SCREEN_SIZE=NexusOne +::set SCREEN_SIZE=iPhoneRetina + +:desktop-run +echo. +echo Starting AIR Debug Launcher with screen size '%SCREEN_SIZE%' +echo. +echo (hint: edit 'Run.bat' to test on device or change screen size) +echo. +adl -screensize %SCREEN_SIZE% "%APP_XML%" "%APP_DIR%" +if errorlevel 1 goto end +goto endNoPause + +:ios-debug +echo. +echo Packaging application for debugging on iOS %INTERPRETER% +if "%INTERPRETER%" == "" echo (this will take a while) +echo. +set TARGET=-debug%INTERPRETER% +set OPTIONS=-connect %DEBUG_IP% +goto ios-package + +:ios-test +echo. +echo Packaging application for testing on iOS %INTERPRETER% +if "%INTERPRETER%" == "" echo (this will take a while) +echo. +set TARGET=-test%INTERPRETER% +set OPTIONS= +goto ios-package + +:ios-package +set PLATFORM=ios +call bat\Packager.bat + +if "%AUTO_INSTALL_IOS%" == "yes" goto ios-install +echo Now manually install and start application on device +echo. +goto end + +:ios-install +echo Installing application for testing on iOS (%DEBUG_IP%) +echo. +call adt -installApp -platform ios -package "%OUTPUT%" +if errorlevel 1 goto installfail + +echo Now manually start application on device +echo. +goto end + +:android-debug +echo. +echo Packaging and installing application for debugging on Android (%DEBUG_IP%) +echo. +set TARGET=-debug +set OPTIONS=-connect %DEBUG_IP% +goto android-package + +:android-test +echo. +echo Packaging and Installing application for testing on Android (%DEBUG_IP%) +echo. +set TARGET= +set OPTIONS= +goto android-package + +:android-package +set PLATFORM=android +call bat\Packager.bat + +adb devices +echo. +echo Installing %OUTPUT% on the device... +echo. +adb -d install -r "%OUTPUT%" +if errorlevel 1 goto installfail + +echo. +echo Starting application on the device for debugging... +echo. +adb shell am start -n air.%APP_ID%/.AppEntry +exit + +:installfail +echo. +echo Installing the app on the device failed + +:end +pause + +:endNoPause + diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/SetupApp.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/SetupApp.bat.template new file mode 100644 index 0000000000..344a238091 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/SetupApp.bat.template @@ -0,0 +1,59 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: About AIR application packaging +:: http://help.adobe.com/en_US/air/build/WS5b3ccc516d4fbf351e63e3d118666ade46-7fd9.html + +:: NOTICE: all paths are relative to project root + +:: Android packaging +set AND_CERT_NAME="$(PROJECTNAME)" +set AND_CERT_PASS=fd +set AND_CERT_FILE=cert\$(PROJECTID).p12 +set AND_ICONS=icons/android + +set AND_SIGNING_OPTIONS=-storetype pkcs12 -keystore "%AND_CERT_FILE%" -storepass %AND_CERT_PASS% + +:: iOS packaging +set IOS_DIST_CERT_FILE= +set IOS_DEV_CERT_FILE= +set IOS_DEV_CERT_PASS= +set IOS_PROVISION=cert\$(PROJECTID).mobileprovision +set IOS_ICONS=icons/ios + +set IOS_DEV_SIGNING_OPTIONS=-storetype pkcs12 -keystore "%IOS_DEV_CERT_FILE%" -storepass %IOS_DEV_CERT_PASS% -provisioning-profile %IOS_PROVISION% +set IOS_DIST_SIGNING_OPTIONS=-storetype pkcs12 -keystore "%IOS_DIST_CERT_FILE%" -provisioning-profile %IOS_PROVISION% + +:: Application descriptor +set APP_XML=application.xml + +:: Files to package +set APP_DIR=bin +set FILE_OR_DIR=-C %APP_DIR% . + +:: Your application ID (must match of Application descriptor) and remove spaces +for /f "tokens=3 delims=<>" %%a in ('findstr /R /C:"^[ ]*" %APP_XML%') do set APP_ID=%%a +set APP_ID=%APP_ID: =% + +:: Output packages +set DIST_PATH=dist +set DIST_NAME=$(PROJECTID) + +:: Debugging using a custom IP +set DEBUG_IP= + +:validation +findstr /C:"%APP_ID%" "%APP_XML%" > NUL +if errorlevel 1 goto badid +goto end + +:badid +echo. +echo ERROR: +echo Application ID in 'bat\SetupApp.bat' (APP_ID) +echo does NOT match Application descriptor '%APP_XML%' (id) +echo. + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/SetupSDK.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/SetupSDK.bat.template new file mode 100644 index 0000000000..049596bcd5 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bat/SetupSDK.bat.template @@ -0,0 +1,42 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: Static path to Flex SDK +set FLEX_SDK=$(FlexSDK) + +:: Use FD supplied SDK path if executed from FD +if exist "%FD_CUR_SDK%" set FLEX_SDK=%FD_CUR_SDK% + +set AUTO_INSTALL_IOS=yes + +:: Path to Android SDK +set ANDROID_SDK="%FLEX_SDK%\lib\android\bin" + +:validation +if not exist "%FLEX_SDK%\bin" goto flexsdk +if not exist "%ANDROID_SDK%" goto androidsdk +goto succeed + +:flexsdk +echo. +echo ERROR: incorrect path to Flex SDK in 'bat\SetupSDK.bat' +echo. +echo Looking for: %FLEX_SDK%\bin +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:androidsdk +echo. +echo ERROR: incorrect path to Android SDK in 'bat\SetupSDK.bat' +echo. +echo Looking for: %ANDROID_SDK%\platform-tools +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:succeed +set PATH=%FLEX_SDK%\bin;%PATH% +set PATH=%PATH%;%ANDROID_SDK% diff --git a/FlashDevelop/Bin/Debug/Templates/ProjectFiles/AS3Project/Empty File.txt.fdt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bin/.empty similarity index 100% rename from FlashDevelop/Bin/Debug/Templates/ProjectFiles/AS3Project/Empty File.txt.fdt rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/bin/.empty diff --git a/FlashDevelop/Bin/Debug/Templates/ProjectFiles/HaxeProject/Empty File.txt.fdt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/cert/.empty similarity index 100% rename from FlashDevelop/Bin/Debug/Templates/ProjectFiles/HaxeProject/Empty File.txt.fdt rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/cert/.empty diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_114.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_114.png new file mode 100644 index 0000000000..5fa6290732 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_114.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_120.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_120.png new file mode 100644 index 0000000000..89b32b51ee Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_120.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_144.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_144.png new file mode 100644 index 0000000000..7a951f96ef Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_144.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_152.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_152.png new file mode 100644 index 0000000000..5112cae675 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_152.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_192.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_192.png new file mode 100644 index 0000000000..f4728d262d Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_192.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_48.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_48.png new file mode 100644 index 0000000000..41fde440a2 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_48.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_57.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_57.png new file mode 100644 index 0000000000..c1e5b2b97b Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_57.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_72.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_72.png new file mode 100644 index 0000000000..3f884a977e Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_72.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_76.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_76.png new file mode 100644 index 0000000000..5f5dc25b25 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_76.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_96.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_96.png new file mode 100644 index 0000000000..4bac47c0a1 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/android/icons/icon_96.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-568h@2x.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-568h@2x.png new file mode 100644 index 0000000000..a8c9bba5f5 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-568h@2x.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-Landscape.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-Landscape.png new file mode 100644 index 0000000000..5047b30cb0 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-Landscape.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-Portrait.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-Portrait.png new file mode 100644 index 0000000000..ec4faa2845 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default-Portrait.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default.png new file mode 100644 index 0000000000..2b7b4be337 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default@2x.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default@2x.png new file mode 100644 index 0000000000..45a5563bae Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/Default@2x.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_114.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_114.png new file mode 100644 index 0000000000..5fa6290732 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_114.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_120.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_120.png new file mode 100644 index 0000000000..89b32b51ee Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_120.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_144.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_144.png new file mode 100644 index 0000000000..7a951f96ef Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_144.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_152.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_152.png new file mode 100644 index 0000000000..5112cae675 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_152.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_192.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_192.png new file mode 100644 index 0000000000..a177bd46d8 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_192.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_48.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_48.png new file mode 100644 index 0000000000..41fde440a2 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_48.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_512.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_512.png new file mode 100644 index 0000000000..5f9e4c7d53 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_512.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_57.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_57.png new file mode 100644 index 0000000000..c1e5b2b97b Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_57.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_72.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_72.png new file mode 100644 index 0000000000..3f884a977e Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_72.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_76.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_76.png new file mode 100644 index 0000000000..5f5dc25b25 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_76.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_96.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_96.png new file mode 100644 index 0000000000..4bac47c0a1 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/icons/ios/icons/icon_96.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/src/$(PackagePath)/Main.as.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/src/$(PackagePath)/Main.as.template new file mode 100644 index 0000000000..69d1444a31 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/190 ActionScript 3 - AIR Mobile AS3 App/src/$(PackagePath)/Main.as.template @@ -0,0 +1,35 @@ +package $(PackageName)$(CSLB){ + import flash.desktop.NativeApplication; + import flash.events.Event; + import flash.display.Sprite; + import flash.display.StageAlign; + import flash.display.StageScaleMode; + import flash.ui.Multitouch; + import flash.ui.MultitouchInputMode; + + /** + $(CBI)* ... + $(CBI)* @author $(DefaultUser) + $(CBI)*/ + public class Main extends Sprite $(CSLB){ + + public function Main() $(CSLB){ + stage.scaleMode = StageScaleMode.NO_SCALE; + stage.align = StageAlign.TOP_LEFT; + stage.addEventListener(Event.DEACTIVATE, deactivate); + + // touch or gesture? + Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; + + // Entry point + // New to AIR? Please read *carefully* the readme.txt files! + } + + private function deactivate(e:Event):void $(CSLB){ + // make sure the app behaves well (or exits) when in background + //NativeApplication.nativeApplication.exit(); + } + + } + +} \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/AIR_Android_readme.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/AIR_Android_readme.txt new file mode 100644 index 0000000000..3a50c8cc03 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/AIR_Android_readme.txt @@ -0,0 +1,48 @@ +AIR for Android instructions + +1. Configuration: + + - edit 'bat\SetupSDK.bat' for paths to Flex SDK and Android SDK (defaults should be ok) + + - install your device's USB drivers: + http://developer.android.com/sdk/oem-usb.html + - enable "USB debugging" on your Android device: + Parameters > Applications > Development > USB Debugging + + +2. Creating a self-signed certificate: + + - run 'bat\CreateCertificate.bat' to generate your self-signed certificate, + + (!) wait a minute before packaging. + + +3. Build from FlashDevelop as usual (F8) + + +4. Run/debug the application on the desktop as usual (F5 or Ctrl+Enter) + + +5. Install AIR runtime on your device: + + - run 'bat\InstallAirRuntime.bat' + + +6. Running/debugging the application on the device: + + 6.a. Build/Debug directly on device + - edit 'bat\RunApp.bat' and change the run target 'goto desktop' by 'goto android-debug' + - build & run as usual (Ctrl+Enter or F5) to package, install & run the application on your device + + 6.b. Debug occasionally on device + - Debug-build from FlashDevelop (F8) + - run 'bat\PackageApp.bat' to package and install a debug version of the application + - start FlashDevelop debugger: Debug > Start Remote Session + - start the application on device + - the application should connect to FlashDevelop interactive debugger as usual + + +7. Packaging for release: + + - Release-build from FlashDevelop (F8) + - run 'bat\PackageApp.bat' and select Android/normal target diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/AIR_iOS_readme.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/AIR_iOS_readme.txt new file mode 100644 index 0000000000..2749617db4 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/AIR_iOS_readme.txt @@ -0,0 +1,82 @@ +AIR for iOS instructions + +1. Configuration: + + - edit 'bat\SetupSDK.bat' for path to Flex SDK (defaults should be ok) + + +3. Build from FlashDevelop as usual (F8) + + +4. Run/debug the application on the desktop as usual (F5 or Ctrl+Enter) + + +5. Configure for iOS packaging in 'bat\SetupApp.bat': + + Take a deep breath, pay the Apple tax and read extra carefully this tutorial: + - http://www.codeandvisual.com/2011/exporting-for-iphone-using-air-27-and-flashdevelop-part-three-generating-developer-certificates-provisioning-profiles-and-p12-files/ + + Now this is how to create the p12 key entirely on Windows: + - http://blog.nngafook.com/2012/06/ios-certificate-process/ + + And later to sign the application for the App Store publication: + - http://blog.nngafook.com/2013/03/packaging-and-submitting-your-app-to-apple-on-windows-kind-of/ + + Then for each project you'll have to go to on Apple's iOS Provisioning Portal: + - create a new App ID with: name of the project and ID indicated in 'application.xml', + - create a new Provisioning Profile: select App ID & registered devices that will be allowed to install the app. + + Once you have obtained a .p12 and .mobileprovision file from Apple's Provisioning Portal: + - save a copy of your .p12 and .mobileprovision certificates in the 'cert\' folder in your FlashDevelop project. + (make sure to keep an extra copy of these 2 files in a safe place) + + Finally edit 'bat\SetupApp.bat' and complete the following lines: + + - IOS_DEV_CERT_FILE: path to your iOS developer 'p12' key ('cert\' folder, if you have followed the instructions above) + - IOS_DEV_CERT_PASS: developer certificate's password + if you don't set it, remove "-storepass %IOS_DEV_CERT_PASS%" from the IOS_SIGNING_OPTIONS, + you'll be prompted to type it when packaging. + - IOS_PROVISION: path to the project's Provisioning Profile file + + For example: + + set IOS_DIST_CERT_FILE=cert\iphone_dev.p12 + set IOS_DEV_CERT_FILE=cert\iphone_dev.p12 + set IOS_DEV_CERT_PASS=YourPassword + set IOS_PROVISION=cert\YourFileName.mobileprovision + + +6. Running/debugging the application on the device: + + Note: if are testing your application for performance, always package for release (see step 7.) + + 6.a. Build/Debug on device + - edit 'bat\RunApp.bat' and change the run target 'goto desktop' by 'goto ios-debug' + - build as usual (Ctrl+Enter or F5) to package + - you'll still have to manually upload & run the app on the device + - the application should connect to FlashDevelop interactive debugger as usual + + 6.b. Debug occasionally on device + - Debug-build from FlashDevelop (F8) + - run 'bat\PackageApp.bat' to package and install a debug version of the application + - start FlashDevelop debugger: Debug > Start Remote Session + - start the application on device + - the application should connect to FlashDevelop interactive debugger as usual + + +7. Packaging for release: + + - edit in 'bat\SetupApp.bat' to add your "distribution" certificate (IOS_DIST_CERT_FILE) + Note: you can package ad-hoc IPAs using your developer certificate. + + - Release-build from FlashDevelop (F8) + - run 'bat\PackageApp.bat' and select + either iOS/"ad-hoc" for installation on test devices + or iOS/App Store for upload in the iOS App Store. + +Tips: +- iFunBox: iTunes replacement; installs app faster even if app version doesn't change, +- TestFlightApp: ad-hoc distribution service http://testflightapp.com +- HockeyKit: self hosted ad-hoc distribution https://github.com/TheRealKerni/HockeyKit +- Manual ad-hoc distribution: http://samvermette.com/71 + diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.as3proj new file mode 100644 index 0000000000..28261c4442 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.as3proj @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.png new file mode 100644 index 0000000000..bd84420d38 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.txt new file mode 100644 index 0000000000..c582302989 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/Project.txt @@ -0,0 +1 @@ +An AIR mobile app written in ActionScript 3 using the Flex framework \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/application.xml.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/application.xml.template new file mode 100644 index 0000000000..21a8986457 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/application.xml.template @@ -0,0 +1,84 @@ + + + + air.$(PACKAGEDOT)$(PROJECTID) + 0.1 + mobileDevice + $(PROJECTID) + + $(PROJECTNAME) + + + + + + + + + + + ]]> + + + UIStatusBarStyle + UIStatusBarStyleBlackOpaque + UIRequiresPersistentWiFi + NO + UIPrerenderedIcon + + UIApplicationExitsOnSuspend + + + UIDeviceFamily + + + 1 + + + + + ]]> + high + + + + $(PROJECTNAME) + $(PROJECTID).swf + true + true + + + direct + + + + icons/icon_48.png + icons/icon_57.png + icons/icon_72.png + icons/icon_76.png + icons/icon_96.png + icons/icon_114.png + icons/icon_120.png + icons/icon_144.png + icons/icon_152.png + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/CreateCertificate.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/CreateCertificate.bat new file mode 100644 index 0000000000..3b3f27e3b0 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/CreateCertificate.bat @@ -0,0 +1,34 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:: Generate +echo. +echo Generating a self-signed certificate for Android packaging +call adt -certificate -validityPeriod 25 -cn %AND_CERT_NAME% 2048-RSA "%AND_CERT_FILE%" %AND_CERT_PASS% +if errorlevel 1 goto failed + +:succeed +echo. +echo Certificate created: %AND_CERT_FILE% with password "%AND_CERT_PASS%" +echo. +if "%AND_CERT_PASS%" == "fd" echo Note: You did not change the default password +echo. +echo HINTS: +echo - you only need to generate this certificate once, +echo - wait a minute before using this certificate to package your AIR application. +echo. +goto end + +:failed +echo. +echo Certificate creation FAILED. +echo. + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/InstallAirRuntime.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/InstallAirRuntime.bat new file mode 100644 index 0000000000..7e9e16f470 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/InstallAirRuntime.bat @@ -0,0 +1,31 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat + +:: AIR runtime installer +set AIR_INSTALLER=%FLEX_SDK%\runtimes\air\android\device\runtime.apk + +:: Install +adb devices +echo. +echo Installing AIR runtime on current device: +echo %AIR_INSTALLER% +echo. +adb install "%AIR_INSTALLER%" +echo. +if errorlevel 1 goto failed +goto end + +:failed +echo Troubleshooting: +echo - one, and only one, Android device should be connected +echo - verify 'bat\SetupSDK.bat' +echo. +goto end + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/PackageApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/PackageApp.bat new file mode 100644 index 0000000000..e9dc50ecd1 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/PackageApp.bat @@ -0,0 +1,87 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:menu +echo. +echo Package for target +echo. +echo Android: +echo. +echo [1] normal (apk) +echo [2] debug (apk-debug) +echo [3] captive (apk-captive-runtime) +echo. +echo iOS: +echo. +echo [4] fast test (ipa-test-interpreter) +echo [5] fast debug (ipa-debug-interpreter) +echo [6] slow test (ipa-test) +echo [7] slow debug (ipa-debug) +echo [8] "ad-hoc" (ipa-ad-hoc) +echo [9] App Store (ipa-app-store) +echo. + +:choice +set /P C=[Choice]: +echo. + +set PLATFORM=android +set OPTIONS= +if %C% GTR 3 set PLATFORM=ios +if %C% GTR 7 set PLATFORM=ios-dist + +if "%C%"=="1" set TARGET= +if "%C%"=="2" set TARGET=-debug +if "%C%"=="2" set OPTIONS=-connect %DEBUG_IP% +if "%C%"=="3" set TARGET=-captive-runtime + +if "%C%"=="4" set TARGET=-test-interpreter +if "%C%"=="5" set TARGET=-debug-interpreter +if "%C%"=="5" set OPTIONS=-connect %DEBUG_IP% +if "%C%"=="6" set TARGET=-test +if "%C%"=="7" set TARGET=-debug +if "%C%"=="7" set OPTIONS=-connect %DEBUG_IP% +if "%C%"=="8" set TARGET=-ad-hoc +if "%C%"=="9" set TARGET=-app-store + +call bat\Packager.bat + +if "%PLATFORM%"=="android" goto android-package + +:ios-package +if "%AUTO_INSTALL_IOS%" == "yes" goto ios-install +echo Now manually install and start application on device +echo. +goto end + +:ios-install +echo Installing application for testing on iOS (%DEBUG_IP%) +echo. +call adt -installApp -platform ios -package "%OUTPUT%" +if errorlevel 1 goto installfail + +echo Now manually start application on device +echo. +goto end + +:android-package +adb devices +echo. +echo Installing %OUTPUT% on the device... +echo. +adb -d install -r "%OUTPUT%" +if errorlevel 1 goto installfail +goto end + +:installfail +echo. +echo Installing the app on the device failed + +:end +pause diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/Packager.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/Packager.bat new file mode 100644 index 0000000000..6b96b0cc84 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/Packager.bat @@ -0,0 +1,75 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +if "%PLATFORM%"=="android" goto android-config +if "%PLATFORM%"=="ios" goto ios-config +if "%PLATFORM%"=="ios-dist" goto ios-dist-config +goto start + +:android-config +set CERT_FILE=%AND_CERT_FILE% +set SIGNING_OPTIONS=%AND_SIGNING_OPTIONS% +set ICONS=%AND_ICONS% +set DIST_EXT=apk +set TYPE=apk +goto start + +:ios-config +set CERT_FILE=%IOS_DEV_CERT_FILE% +set SIGNING_OPTIONS=%IOS_DEV_SIGNING_OPTIONS% +set ICONS=%IOS_ICONS% +set DIST_EXT=ipa +set TYPE=ipa +goto start +:: Set working dir +cd %~dp0 & cd .. + +:ios-dist-config +set CERT_FILE=%IOS_DIST_CERT_FILE% +set SIGNING_OPTIONS=%IOS_DIST_SIGNING_OPTIONS% +set ICONS=%IOS_ICONS% +set DIST_EXT=ipa +set TYPE=ipa +goto start + +:start +if not exist "%CERT_FILE%" goto certificate +:: Output file +set FILE_OR_DIR=%FILE_OR_DIR% -C "%ICONS%" . +if not exist "%DIST_PATH%" md "%DIST_PATH%" +set OUTPUT=%DIST_PATH%\%DIST_NAME%%TARGET%.%DIST_EXT% +:: Package +echo Packaging: %OUTPUT% +echo using certificate: %CERT_FILE%... +echo. +call adt -package -target %TYPE%%TARGET% %OPTIONS% %SIGNING_OPTIONS% "%OUTPUT%" "%APP_XML%" %FILE_OR_DIR% +echo. +if errorlevel 1 goto failed +goto end + +:certificate +echo Certificate not found: %CERT_FILE% +echo. +echo Android: +echo - generate a default certificate using 'bat\CreateCertificate.bat' +echo or configure a specific certificate in 'bat\SetupApp.bat'. +echo. +echo iOS: +echo - configure your developer key and project's Provisioning Profile +echo in 'bat\SetupApp.bat'. +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:failed +echo APK setup creation FAILED. +echo. +echo Troubleshooting: +echo - verify AIR SDK target version in %APP_XML% +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/RunApp.bat b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/RunApp.bat new file mode 100644 index 0000000000..c621e41e79 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/RunApp.bat @@ -0,0 +1,112 @@ +@echo off + +:: Set working dir +cd %~dp0 & cd .. + +set PAUSE_ERRORS=1 +call bat\SetupSDK.bat +call bat\SetupApp.bat + +:target +goto desktop +::goto android-debug +::goto android-test +set INTERPRETER=-interpreter +::goto ios-debug +::goto ios-test + +:desktop +:: http://help.adobe.com/en_US/air/build/WSfffb011ac560372f-6fa6d7e0128cca93d31-8000.html + +set SCREEN_SIZE=NexusOne +::set SCREEN_SIZE=iPhoneRetina + +:desktop-run +echo. +echo Starting AIR Debug Launcher with screen size '%SCREEN_SIZE%' +echo. +echo (hint: edit 'bat\RunApp.bat' to test on device or change screen size) +echo. +adl -screensize %SCREEN_SIZE% "%APP_XML%" "%APP_DIR%" +if errorlevel 1 goto end +goto endNoPause + +:ios-debug +echo. +echo Packaging application for debugging on iOS %INTERPRETER% +if "%INTERPRETER%" == "" echo (this will take a while) +echo. +set TARGET=-debug%INTERPRETER% +set OPTIONS=-connect %DEBUG_IP% +goto ios-package + +:ios-test +echo. +echo Packaging application for testing on iOS %INTERPRETER% +if "%INTERPRETER%" == "" echo (this will take a while) +echo. +set TARGET=-test%INTERPRETER% +set OPTIONS= +goto ios-package + +:ios-package +set PLATFORM=ios +call bat\Packager.bat + +if "%AUTO_INSTALL_IOS%" == "yes" goto ios-install +echo Now manually install and start application on device +echo. +goto end + +:ios-install +echo Installing application for testing on iOS (%DEBUG_IP%) +echo. +call adt -installApp -platform ios -package "%OUTPUT%" +if errorlevel 1 goto installfail + +echo Now manually start application on device +echo. +goto end + +:android-debug +echo. +echo Packaging and installing application for debugging on Android (%DEBUG_IP%) +echo. +set TARGET=-debug +set OPTIONS=-connect %DEBUG_IP% +goto android-package + +:android-test +echo. +echo Packaging and Installing application for testing on Android (%DEBUG_IP%) +echo. +set TARGET= +set OPTIONS= +goto android-package + +:android-package +set PLATFORM=android +call bat\Packager.bat + +adb devices +echo. +echo Installing %OUTPUT% on the device... +echo. +adb -d install -r "%OUTPUT%" +if errorlevel 1 goto installfail + +echo. +echo Starting application on the device for debugging... +echo. +adb shell am start -n air.%APP_ID%/.AppEntry +exit + +:installfail +echo. +echo Installing the app on the device failed + +:end +pause + +:endNoPause + diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/SetupApp.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/SetupApp.bat.template new file mode 100644 index 0000000000..344a238091 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/SetupApp.bat.template @@ -0,0 +1,59 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: About AIR application packaging +:: http://help.adobe.com/en_US/air/build/WS5b3ccc516d4fbf351e63e3d118666ade46-7fd9.html + +:: NOTICE: all paths are relative to project root + +:: Android packaging +set AND_CERT_NAME="$(PROJECTNAME)" +set AND_CERT_PASS=fd +set AND_CERT_FILE=cert\$(PROJECTID).p12 +set AND_ICONS=icons/android + +set AND_SIGNING_OPTIONS=-storetype pkcs12 -keystore "%AND_CERT_FILE%" -storepass %AND_CERT_PASS% + +:: iOS packaging +set IOS_DIST_CERT_FILE= +set IOS_DEV_CERT_FILE= +set IOS_DEV_CERT_PASS= +set IOS_PROVISION=cert\$(PROJECTID).mobileprovision +set IOS_ICONS=icons/ios + +set IOS_DEV_SIGNING_OPTIONS=-storetype pkcs12 -keystore "%IOS_DEV_CERT_FILE%" -storepass %IOS_DEV_CERT_PASS% -provisioning-profile %IOS_PROVISION% +set IOS_DIST_SIGNING_OPTIONS=-storetype pkcs12 -keystore "%IOS_DIST_CERT_FILE%" -provisioning-profile %IOS_PROVISION% + +:: Application descriptor +set APP_XML=application.xml + +:: Files to package +set APP_DIR=bin +set FILE_OR_DIR=-C %APP_DIR% . + +:: Your application ID (must match of Application descriptor) and remove spaces +for /f "tokens=3 delims=<>" %%a in ('findstr /R /C:"^[ ]*" %APP_XML%') do set APP_ID=%%a +set APP_ID=%APP_ID: =% + +:: Output packages +set DIST_PATH=dist +set DIST_NAME=$(PROJECTID) + +:: Debugging using a custom IP +set DEBUG_IP= + +:validation +findstr /C:"%APP_ID%" "%APP_XML%" > NUL +if errorlevel 1 goto badid +goto end + +:badid +echo. +echo ERROR: +echo Application ID in 'bat\SetupApp.bat' (APP_ID) +echo does NOT match Application descriptor '%APP_XML%' (id) +echo. + +:end diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/SetupSDK.bat.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/SetupSDK.bat.template new file mode 100644 index 0000000000..5e305dcfeb --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bat/SetupSDK.bat.template @@ -0,0 +1,42 @@ +:: Set working dir +cd %~dp0 & cd .. + +:user_configuration + +:: Static path to Flex SDK +set FLEX_SDK=$(FlexSDK) + +:: Use FD supplied SDK path if executed from FD +if exist "%FD_CUR_SDK%" set FLEX_SDK=%FD_CUR_SDK% + +set AUTO_INSTALL_IOS=yes + +:: Path to Android SDK +set ANDROID_SDK=$(AppDir)\Tools\android + +:validation +if not exist "%FLEX_SDK%\bin" goto flexsdk +if not exist "%ANDROID_SDK%\platform-tools" goto androidsdk +goto succeed + +:flexsdk +echo. +echo ERROR: incorrect path to Flex SDK in 'bat\SetupSDK.bat' +echo. +echo Looking for: %FLEX_SDK%\bin +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:androidsdk +echo. +echo ERROR: incorrect path to Android SDK in 'bat\SetupSDK.bat' +echo. +echo Looking for: %ANDROID_SDK%\platform-tools +echo. +if %PAUSE_ERRORS%==1 pause +exit + +:succeed +set PATH=%FLEX_SDK%\bin;%PATH% +set PATH=%PATH%;%ANDROID_SDK%\platform-tools diff --git a/FlashDevelop/Bin/Debug/Templates/ProjectFiles/LoomProject/Empty File.txt.fdt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bin/.empty similarity index 100% rename from FlashDevelop/Bin/Debug/Templates/ProjectFiles/LoomProject/Empty File.txt.fdt rename to External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/bin/.empty diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/cert/.empty b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/cert/.empty new file mode 100644 index 0000000000..e69de29bb2 diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_114.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_114.png new file mode 100644 index 0000000000..5fa6290732 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_114.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_120.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_120.png new file mode 100644 index 0000000000..89b32b51ee Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_120.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_144.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_144.png new file mode 100644 index 0000000000..7a951f96ef Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_144.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_152.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_152.png new file mode 100644 index 0000000000..5112cae675 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_152.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_192.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_192.png new file mode 100644 index 0000000000..f4728d262d Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_192.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_48.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_48.png new file mode 100644 index 0000000000..41fde440a2 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_48.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_57.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_57.png new file mode 100644 index 0000000000..c1e5b2b97b Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_57.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_72.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_72.png new file mode 100644 index 0000000000..3f884a977e Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_72.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_76.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_76.png new file mode 100644 index 0000000000..5f5dc25b25 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_76.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_96.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_96.png new file mode 100644 index 0000000000..4bac47c0a1 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/android/icons/icon_96.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-568h@2x.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-568h@2x.png new file mode 100644 index 0000000000..a8c9bba5f5 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-568h@2x.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-Landscape.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-Landscape.png new file mode 100644 index 0000000000..5047b30cb0 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-Landscape.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-Portrait.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-Portrait.png new file mode 100644 index 0000000000..ec4faa2845 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default-Portrait.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default.png new file mode 100644 index 0000000000..2b7b4be337 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default@2x.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default@2x.png new file mode 100644 index 0000000000..45a5563bae Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/Default@2x.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_114.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_114.png new file mode 100644 index 0000000000..5fa6290732 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_114.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_120.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_120.png new file mode 100644 index 0000000000..89b32b51ee Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_120.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_144.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_144.png new file mode 100644 index 0000000000..7a951f96ef Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_144.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_152.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_152.png new file mode 100644 index 0000000000..5112cae675 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_152.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_192.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_192.png new file mode 100644 index 0000000000..a177bd46d8 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_192.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_48.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_48.png new file mode 100644 index 0000000000..41fde440a2 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_48.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_512.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_512.png new file mode 100644 index 0000000000..5f9e4c7d53 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_512.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_57.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_57.png new file mode 100644 index 0000000000..c1e5b2b97b Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_57.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_72.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_72.png new file mode 100644 index 0000000000..3f884a977e Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_72.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_76.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_76.png new file mode 100644 index 0000000000..5f5dc25b25 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_76.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_96.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_96.png new file mode 100644 index 0000000000..4bac47c0a1 Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/icons/ios/icons/icon_96.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/src/$(PackagePath)/Main.mxml.template b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/src/$(PackagePath)/Main.mxml.template new file mode 100644 index 0000000000..cc93a3a8cf --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/src/$(PackagePath)/Main.mxml.template @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/src/$(PackagePath)/views/HomeView.mxml b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/src/$(PackagePath)/views/HomeView.mxml new file mode 100644 index 0000000000..977d37fe72 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/195 ActionScript 3 - AIR Mobile Flex App/src/$(PackagePath)/views/HomeView.mxml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.as3proj b/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.as3proj new file mode 100644 index 0000000000..1392f127d4 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.as3proj @@ -0,0 +1,57 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.png b/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.png new file mode 100644 index 0000000000..3e703a61be Binary files /dev/null and b/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.png differ diff --git a/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.txt b/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.txt new file mode 100644 index 0000000000..12611f0d22 --- /dev/null +++ b/External/Extensions/AS3Templates/$(BaseDir)/Projects/200 ActionScript 3 - Empty Project/Project.txt @@ -0,0 +1 @@ +An empty project written in ActionScript 3 for Flash 9+ Player \ No newline at end of file diff --git a/External/Extensions/AS3Templates/AS3Templates-1.00.fdz b/External/Extensions/AS3Templates/AS3Templates-1.00.fdz new file mode 100644 index 0000000000..db5ba08a44 Binary files /dev/null and b/External/Extensions/AS3Templates/AS3Templates-1.00.fdz differ diff --git a/External/Extensions/AzothExtension/$(AppDir)/Tools/azoth/azoth.exe b/External/Extensions/AzothExtension/$(AppDir)/Tools/azoth/azoth.exe old mode 100644 new mode 100755 diff --git a/External/Extensions/LoomExtension/$(BaseDir)/Plugins/LoomContext.dll b/External/Extensions/LoomExtension/$(BaseDir)/Plugins/LoomContext.dll new file mode 100755 index 0000000000..47ef4a592d Binary files /dev/null and b/External/Extensions/LoomExtension/$(BaseDir)/Plugins/LoomContext.dll differ diff --git a/FlashDevelop/Bin/Debug/Projects/520 Other - Loom App/Project.lsproj b/External/Extensions/LoomExtension/$(BaseDir)/Projects/520 Other - Loom App/Project.lsproj similarity index 100% rename from FlashDevelop/Bin/Debug/Projects/520 Other - Loom App/Project.lsproj rename to External/Extensions/LoomExtension/$(BaseDir)/Projects/520 Other - Loom App/Project.lsproj diff --git a/External/Extensions/LoomExtension/$(BaseDir)/Projects/520 Other - Loom App/Project.png b/External/Extensions/LoomExtension/$(BaseDir)/Projects/520 Other - Loom App/Project.png new file mode 100644 index 0000000000..059f16b8fa Binary files /dev/null and b/External/Extensions/LoomExtension/$(BaseDir)/Projects/520 Other - Loom App/Project.png differ diff --git a/FlashDevelop/Bin/Debug/Projects/520 Other - Loom App/Project.txt b/External/Extensions/LoomExtension/$(BaseDir)/Projects/520 Other - Loom App/Project.txt similarity index 100% rename from FlashDevelop/Bin/Debug/Projects/520 Other - Loom App/Project.txt rename to External/Extensions/LoomExtension/$(BaseDir)/Projects/520 Other - Loom App/Project.txt diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/boundaries/AccessorsMethods.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/AccessorsMethods.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/boundaries/AccessorsMethods.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/AccessorsMethods.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/boundaries/EventHandlers.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/EventHandlers.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/boundaries/EventHandlers.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/EventHandlers.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/boundaries/PrivateMethods.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/PrivateMethods.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/boundaries/PrivateMethods.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/PrivateMethods.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/boundaries/PublicMethods.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/PublicMethods.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/boundaries/PublicMethods.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/PublicMethods.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/boundaries/StaticMethods.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/StaticMethods.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/boundaries/StaticMethods.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/boundaries/StaticMethods.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/case.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/case.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/case.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/case.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/catch.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/catch.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/catch.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/catch.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/class.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/class.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/class.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/class.fds diff --git a/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/do.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/do.fds new file mode 100644 index 0000000000..12a226cb19 --- /dev/null +++ b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/do.fds @@ -0,0 +1,3 @@ +do $(CSLB){ + +} while ($(EntryPoint)); \ No newline at end of file diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/each.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/each.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/each.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/each.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/else.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/else.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/else.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/else.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/elseif.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/elseif.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/elseif.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/elseif.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/finally.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/finally.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/finally.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/finally.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/for.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/for.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/for.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/for.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/foreach.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/foreach.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/foreach.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/foreach.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/forin.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/forin.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/forin.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/forin.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/function.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/function.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/function.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/function.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/AssignVariable.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/AssignVariable.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/AssignVariable.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/AssignVariable.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/CallFunction.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/CallFunction.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/CallFunction.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/CallFunction.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/Constant.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Constant.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/Constant.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Constant.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/Constructor.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Constructor.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/Constructor.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Constructor.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/Delegate.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Delegate.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/Delegate.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Delegate.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/DelegateMethodsHeader.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/DelegateMethodsHeader.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/DelegateMethodsHeader.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/DelegateMethodsHeader.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/EventHandler.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/EventHandler.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/EventHandler.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/EventHandler.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/EventMetatag.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/EventMetatag.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/EventMetatag.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/EventMetatag.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/FieldFromParameter.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/FieldFromParameter.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/FieldFromParameter.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/FieldFromParameter.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/Function.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Function.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/Function.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Function.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/FunctionParameter.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/FunctionParameter.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/FunctionParameter.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/FunctionParameter.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/Getter.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Getter.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/Getter.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Getter.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/IFunction.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/IFunction.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/IFunction.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/IFunction.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/IGetter.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/IGetter.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/IGetter.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/IGetter.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/ISetter.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/ISetter.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/ISetter.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/ISetter.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/ImplementHeader.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/ImplementHeader.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/ImplementHeader.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/ImplementHeader.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/MethodDeclaration.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/MethodDeclaration.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/MethodDeclaration.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/MethodDeclaration.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/MethodOverride.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/MethodOverride.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/MethodOverride.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/MethodOverride.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/Setter.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Setter.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/Setter.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Setter.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/ToString.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/ToString.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/ToString.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/ToString.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/generators/Variable.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Variable.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/generators/Variable.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/generators/Variable.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/get.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/get.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/get.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/get.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/if.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/if.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/if.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/if.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/region.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/region.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/region.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/region.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/set.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/set.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/set.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/set.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/surround/().fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/().fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/surround/().fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/().fds diff --git a/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/do..while.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/do..while.fds new file mode 100644 index 0000000000..d63b442bc3 --- /dev/null +++ b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/do..while.fds @@ -0,0 +1,3 @@ +do $(CSLB){ + {0} +} while ($(EntryPoint)); \ No newline at end of file diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/surround/for..each.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/for..each.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/surround/for..each.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/for..each.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/surround/for..in.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/for..in.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/surround/for..in.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/for..in.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/surround/for.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/for.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/surround/for.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/for.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/surround/if.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/if.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/surround/if.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/if.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/surround/try..catch.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/try..catch.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/surround/try..catch.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/try..catch.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/surround/while.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/while.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/surround/while.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/surround/while.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/switch.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/switch.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/switch.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/switch.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/try.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/try.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/try.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/try.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/while.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/while.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/while.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/while.fds diff --git a/FlashDevelop/Bin/Debug/Snippets/loom/with.fds b/External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/with.fds similarity index 100% rename from FlashDevelop/Bin/Debug/Snippets/loom/with.fds rename to External/Extensions/LoomExtension/$(BaseDir)/Snippets/loom/with.fds diff --git a/FlashDevelop/Bin/Debug/Templates/ProjectFiles/LoomProject/Class.ls.fdt b/External/Extensions/LoomExtension/$(BaseDir)/Templates/ProjectFiles/LoomProject/Class.ls.fdt similarity index 100% rename from FlashDevelop/Bin/Debug/Templates/ProjectFiles/LoomProject/Class.ls.fdt rename to External/Extensions/LoomExtension/$(BaseDir)/Templates/ProjectFiles/LoomProject/Class.ls.fdt diff --git a/FlashDevelop/Bin/Debug/Templates/ProjectFiles/LoomProject/Class.ls.fdt.wizard b/External/Extensions/LoomExtension/$(BaseDir)/Templates/ProjectFiles/LoomProject/Class.ls.fdt.wizard similarity index 100% rename from FlashDevelop/Bin/Debug/Templates/ProjectFiles/LoomProject/Class.ls.fdt.wizard rename to External/Extensions/LoomExtension/$(BaseDir)/Templates/ProjectFiles/LoomProject/Class.ls.fdt.wizard diff --git a/FlashDevelop/Bin/Debug/Templates/ProjectFiles/LoomProject/Interface.ls.fdt b/External/Extensions/LoomExtension/$(BaseDir)/Templates/ProjectFiles/LoomProject/Interface.ls.fdt similarity index 100% rename from FlashDevelop/Bin/Debug/Templates/ProjectFiles/LoomProject/Interface.ls.fdt rename to External/Extensions/LoomExtension/$(BaseDir)/Templates/ProjectFiles/LoomProject/Interface.ls.fdt diff --git a/External/Extensions/LoomExtension/LoomContext-1.00.fdz b/External/Extensions/LoomExtension/LoomContext-1.00.fdz new file mode 100644 index 0000000000..049727aea8 Binary files /dev/null and b/External/Extensions/LoomExtension/LoomContext-1.00.fdz differ diff --git a/External/Extensions/Unity3DExtension/$(BaseDir)/Plugins/UnityContext.dll b/External/Extensions/Unity3DExtension/$(BaseDir)/Plugins/UnityContext.dll old mode 100644 new mode 100755 diff --git a/External/Graphics/FONTS.txt b/External/Graphics/FONTS.txt new file mode 100644 index 0000000000..59f0ebb334 --- /dev/null +++ b/External/Graphics/FONTS.txt @@ -0,0 +1,2 @@ +Helvetica-Bold +BreuerText-Bold \ No newline at end of file diff --git a/External/Graphics/Projects.psd b/External/Graphics/Projects.psd new file mode 100644 index 0000000000..1aae15c912 Binary files /dev/null and b/External/Graphics/Projects.psd differ diff --git a/External/Plugins/AS2Context/AS2Context.csproj b/External/Plugins/AS2Context/AS2Context.csproj index a5f1b01a73..f057d414b4 100644 --- a/External/Plugins/AS2Context/AS2Context.csproj +++ b/External/Plugins/AS2Context/AS2Context.csproj @@ -1,122 +1,85 @@  - - - Debug - AnyCPU - 9.0.21022 - 2.0 - {74AD0487-CEF9-43FE-9283-BC6F79539ADE} - Library - Properties - AS2Context - AS2Context - - - - - 3.5 - - - v2.0 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - true - full - false - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - TRACE - prompt - 4 - - - x86 - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - - - x86 - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - TRACE - true - - - - - - - - - - - - {61885F70-B4DC-4B44-852D-5D6D03F2A734} - PluginCore - False - - - {4EBF2653-9654-4E40-880E-0046B3D6210E} - ASCompletion - False - - - - - - - - - - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - + + + + Debug + AnyCPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE} + Library + Properties + AS2Context + AS2Context + net48 + true + false + false + false + x64;x86;AnyCPU + + + true + full + false + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + prompt + 4 + 9 + + + none + true + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + prompt + 4 + 9 + + + x86 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + 9 + + + x86 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + true + 9 + + + true + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + full + x64 + 9 + prompt + + + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + true + x64 + 9 + prompt + + + + + + + + + {61885F70-B4DC-4B44-852D-5D6D03F2A734} + PluginCore + False + + + {4EBF2653-9654-4E40-880E-0046B3D6210E} + ASCompletion + False + + \ No newline at end of file diff --git a/External/Plugins/AS2Context/AS2Settings.cs b/External/Plugins/AS2Context/AS2Settings.cs index 6ea90331ff..78739653e4 100644 --- a/External/Plugins/AS2Context/AS2Settings.cs +++ b/External/Plugins/AS2Context/AS2Settings.cs @@ -1,21 +1,17 @@ using System; -using System.Collections.Generic; -using System.Text; using System.ComponentModel; using System.Drawing.Design; -using System.Windows.Forms; -using System.Windows.Forms.Design; -using System.IO; -using ASCompletion.Context; -using PluginCore.Localization; +using ASCompletion.Settings; +using Ookii.Dialogs; using PluginCore; +using PluginCore.Localization; namespace AS2Context { public delegate void ClasspathChangedEvent(); [Serializable] - public class AS2Settings : ASCompletion.Settings.IContextSettings + public class AS2Settings : IContextSettings { [field: NonSerialized] public event ClasspathChangedEvent OnClasspathChanged; @@ -31,8 +27,8 @@ public class AS2Settings : ASCompletion.Settings.IContextSettings [LocalizedCategory("ASCompletion.Category.Documentation"), LocalizedDescription("ASCompletion.Description.DocumentationCommandLine"), DefaultValue(DEFAULT_DOC_COMMAND)] public string DocumentationCommandLine { - get { return documentationCommandLine; } - set { documentationCommandLine = value; } + get => documentationCommandLine; + set => documentationCommandLine = value; } #endregion @@ -73,7 +69,7 @@ public string DocumentationCommandLine const bool DEFAULT_FIXPACKAGEAUTOMATICALLY = true; protected bool checkSyntaxOnSave = DEFAULT_CHECKSYNTAX; - private bool lazyClasspathExploration = DEFAULT_LAZYMODE; + bool lazyClasspathExploration = DEFAULT_LAZYMODE; protected bool completionListAllTypes = DEFAULT_LISTALL; protected bool completionShowQualifiedTypes = DEFAULT_QUALIFY; protected bool completionEnabled = DEFAULT_COMPLETIONENABLED; @@ -84,42 +80,30 @@ public string DocumentationCommandLine protected InstalledSDK[] installedSDKs = null; [Browsable(false)] - public string LanguageId - { - get { return "AS2"; } - } + public string LanguageId => "AS2"; [Browsable(false)] - public string DefaultExtension - { - get { return ".as"; } - } + public string DefaultExtension => ".as"; [Browsable(false)] - public string CheckSyntaxRunning - { - get { return TextHelper.GetString("Info.MTASCRunning"); } - } + public string CheckSyntaxRunning => TextHelper.GetString("Info.MTASCRunning"); [Browsable(false)] - public string CheckSyntaxDone - { - get { return TextHelper.GetString("Info.MTASCDone"); } - } + public string CheckSyntaxDone => TextHelper.GetString("Info.MTASCDone"); [DisplayName("Check Syntax On Save")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.CheckSyntaxOnSave"), DefaultValue(DEFAULT_CHECKSYNTAX)] public bool CheckSyntaxOnSave { - get { return checkSyntaxOnSave; } - set { checkSyntaxOnSave = value; } + get => checkSyntaxOnSave; + set => checkSyntaxOnSave = value; } [DisplayName("User Classpath")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.UserClasspath")] public string[] UserClasspath { - get { return userClasspath; } + get => userClasspath; set { userClasspath = value; @@ -131,7 +115,7 @@ public string[] UserClasspath [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS2Context.Description.MtascPath")] public InstalledSDK[] InstalledSDKs { - get { return installedSDKs; } + get => installedSDKs; set { installedSDKs = value; @@ -141,9 +125,7 @@ public InstalledSDK[] InstalledSDKs public InstalledSDK GetDefaultSDK() { - if (installedSDKs == null || installedSDKs.Length == 0) - return InstalledSDK.INVALID_SDK; - + if (installedSDKs.IsNullOrEmpty()) return InstalledSDK.INVALID_SDK; foreach (InstalledSDK sdk in installedSDKs) if (sdk.IsValid) return sdk; return InstalledSDK.INVALID_SDK; @@ -153,16 +135,16 @@ public InstalledSDK GetDefaultSDK() [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.CompletionEnabled"), DefaultValue(DEFAULT_COMPLETIONENABLED)] public bool CompletionEnabled { - get { return completionEnabled; } - set { completionEnabled = value; } + get => completionEnabled; + set => completionEnabled = value; } [DisplayName("Generate Imports")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.GenerateImports"), DefaultValue(DEFAULT_GENERATEIMPORTS)] public bool GenerateImports { - get { return generateImports; } - set { generateImports = value; } + get => generateImports; + set => generateImports = value; } /// @@ -172,8 +154,8 @@ public bool GenerateImports [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.CompletionListAllTypes"), DefaultValue(DEFAULT_LISTALL)] public bool CompletionListAllTypes { - get { return completionListAllTypes; } - set { completionListAllTypes = value; } + get => completionListAllTypes; + set => completionListAllTypes = value; } /// @@ -183,8 +165,8 @@ public bool CompletionListAllTypes [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.CompletionShowQualifiedTypes"), DefaultValue(DEFAULT_QUALIFY)] public bool CompletionShowQualifiedTypes { - get { return completionShowQualifiedTypes; } - set { completionShowQualifiedTypes = value; } + get => completionShowQualifiedTypes; + set => completionShowQualifiedTypes = value; } /// @@ -194,24 +176,24 @@ public bool CompletionShowQualifiedTypes [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.LazyClasspathExploration"), DefaultValue(DEFAULT_LAZYMODE)] public bool LazyClasspathExploration { - get { return lazyClasspathExploration; } - set { lazyClasspathExploration = value; } + get => lazyClasspathExploration; + set => lazyClasspathExploration = value; } [DisplayName("Play After Build")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.PlayAfterBuild"), DefaultValue(DEFAULT_PLAY)] public bool PlayAfterBuild { - get { return playAfterBuild; } - set { playAfterBuild = value; } + get => playAfterBuild; + set => playAfterBuild = value; } [DisplayName("Fix Package Automatically")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.FixPackageAutomatically"), DefaultValue(DEFAULT_FIXPACKAGEAUTOMATICALLY)] public bool FixPackageAutomatically { - get { return fixPackageAutomatically; } - set { fixPackageAutomatically = value; } + get => fixPackageAutomatically; + set => fixPackageAutomatically = value; } #endregion @@ -222,16 +204,16 @@ public bool FixPackageAutomatically const int DEFAULT_FLASHVERSION = 9; // Flash CS3 has a specific FP9 support for AS2 const string DEFAULT_MTASCCHECKPARAMS = "-mx -wimp"; - private int flashVersion = 9; - private string mmClassPath; - private bool useMtascIntrinsic = DEFAULT_USEMTASC; - private string mtascCheckParameters = DEFAULT_MTASCCHECKPARAMS; + int flashVersion = 9; + string mmClassPath; + bool useMtascIntrinsic = DEFAULT_USEMTASC; + string mtascCheckParameters = DEFAULT_MTASCCHECKPARAMS; [DisplayName("Use MTASC Intrinsics")] [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS2Context.Description.UseMtascIntrinsic"), DefaultValue(DEFAULT_USEMTASC)] public bool UseMtascIntrinsic { - get { return useMtascIntrinsic; } + get => useMtascIntrinsic; set { useMtascIntrinsic = value; @@ -243,16 +225,16 @@ public bool UseMtascIntrinsic [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS2Context.Description.MtascCheckParameters"), DefaultValue(DEFAULT_MTASCCHECKPARAMS)] public string MtascCheckParameters { - get { return mtascCheckParameters; } - set { mtascCheckParameters = value; } + get => mtascCheckParameters; + set => mtascCheckParameters = value; } [DisplayName("Flash IDE Classpath")] [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS2Context.Description.MMClassPath")] - [Editor(typeof(FolderNameEditor), typeof(UITypeEditor))] + [Editor(typeof(VistaFolderNameEditor), typeof(UITypeEditor))] public string MMClassPath { - get { return mmClassPath; } + get => mmClassPath; set { if (value == mmClassPath) return; mmClassPath = value; @@ -264,7 +246,7 @@ public string MMClassPath [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS2Context.Description.DefaultFlashVersion"), DefaultValue(DEFAULT_FLASHVERSION)] public int DefaultFlashVersion { - get { return flashVersion; } + get => flashVersion; set { if (value == flashVersion) return; if (value >= 6 && value <= 9) @@ -278,9 +260,9 @@ public int DefaultFlashVersion #endregion [Browsable(false)] - private void FireChanged() - { - if (OnClasspathChanged != null) OnClasspathChanged(); - } + void FireChanged() => OnClasspathChanged?.Invoke(); + + [Browsable(false)] + public string AddSpaceAfter { get; set; } } } diff --git a/External/Plugins/AS2Context/Context.cs b/External/Plugins/AS2Context/Context.cs index 19547df03f..16782d10c2 100644 --- a/External/Plugins/AS2Context/Context.cs +++ b/External/Plugins/AS2Context/Context.cs @@ -1,40 +1,36 @@ using System; -using System.Collections; -using System.Collections.Specialized; using System.Collections.Generic; -using System.Text.RegularExpressions; using System.IO; -using System.Diagnostics; -using System.Windows.Forms; -using PluginCore; -using PluginCore.Managers; -using PluginCore.Controls; -using ASCompletion.Context; +using System.Text.RegularExpressions; using ASCompletion.Completion; +using ASCompletion.Context; using ASCompletion.Model; using ASCompletion.Settings; -using PluginCore.Localization; +using PluginCore; +using PluginCore.Controls; using PluginCore.Helpers; +using PluginCore.Localization; +using PluginCore.Managers; namespace AS2Context { - /// - /// Actionscript2 context - /// - public class Context: ASContext - { + /// + /// ActionScript2 context + /// + public class Context: ASContext + { #region regular_expressions_definitions - static readonly protected Regex re_CMD_BuildCommand = + protected static readonly Regex re_CMD_BuildCommand = new Regex("@mtasc[\\s]+(?.*)", RegexOptions.Compiled | RegexOptions.Multiline); - static readonly protected Regex re_SplitParams = + protected static readonly Regex re_SplitParams = new Regex("[\\s](?\\-[A-z]+)", RegexOptions.Compiled | RegexOptions.Singleline); - static protected readonly Regex re_level = + protected static readonly Regex re_level = new Regex("^_level[0-9]+$", RegexOptions.Compiled | RegexOptions.Singleline); - static protected readonly Regex re_token = + protected static readonly Regex re_token = new Regex("^[a-z$_][a-z0-9$_]*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); - static protected readonly Regex re_package = + protected static readonly Regex re_package = new Regex("^[a-z$_][a-z0-9$_.]*$", RegexOptions.IgnoreCase | RegexOptions.Compiled); - static protected readonly Regex re_lastDot = + protected static readonly Regex re_lastDot = new Regex("\\.[^<]", RegexOptions.RightToLeft | RegexOptions.Compiled); #endregion @@ -43,12 +39,12 @@ public class Context: ASContext protected bool hasLevels = true; protected string docType; - private AS2Settings as2settings; + readonly AS2Settings as2settings; public override IContextSettings Settings { - get { return settings; } - set { settings = value; } + get => settings; + set => settings = value; } /// @@ -58,7 +54,7 @@ protected Context() { } - public Context(AS2Settings initSettings) + public Context(AS2Settings initSettings) { as2settings = initSettings; @@ -98,19 +94,19 @@ public Context(AS2Settings initSettings) features.methodModifierDefault = Visibility.Public; // keywords + features.ClassKey = "class"; + features.InterfaceKey = "interface"; + features.ExtendsKey = "extends"; + features.ImplementsKey = "implements"; features.dot = "."; features.voidKey = "Void"; features.objectKey = "Object"; features.booleanKey = "Boolean"; features.numberKey = "Number"; + features.stringKey = "String"; features.arrayKey = "Array"; + features.dynamicKey = "*"; features.importKey = "import"; - features.typesPreKeys = new string[] { "import", "new", "instanceof", "extends", "implements" }; - features.codeKeywords = new string[] { - "class", "interface", "var", "function", "new", "delete", "instanceof", "return", "break", "continue", - "if", "else", "for", "in", "while", "do", "switch", "case", "default", "with", - "null", "undefined", "true", "false", "try", "catch", "finally", "throw" - }; features.varKey = "var"; features.functionKey = "function"; features.getKey = "get"; @@ -120,74 +116,82 @@ public Context(AS2Settings initSettings) features.publicKey = "public"; features.privateKey = "private"; features.intrinsicKey = "intrinsic"; - + features.ReturnKey = "return"; + features.typesPreKeys = new[] { "import", "new", "instanceof", "extends", "implements" }; + features.codeKeywords = new[] { + "var", "function", "new", "delete", "instanceof", "return", "break", "continue", + "if", "else", "for", "in", "while", "do", "switch", "case", "default", "with", + "null", "undefined", "true", "false", "try", "catch", "finally", "throw" + }; + features.accessKeywords = new[] { "override", "public", "private", "intrinsic", "static" }; + features.declKeywords = new[] { "var", "function" }; + features.typesKeywords = new[] { "import", "class", "interface" }; features.functionArguments = new MemberModel("arguments", "FunctionArguments", FlagType.Variable | FlagType.LocalVar, 0); - + features.ArithmeticOperators = new HashSet { '+', '-', '*', '/' }; + features.IncrementDecrementOperators = new[] {"++", "--"}; /* INITIALIZATION */ settings = initSettings; //BuildClassPath(); // defered to first use - } - #endregion - - #region classpath management - /// - /// Classpathes & classes cache initialisation - /// - public override void BuildClassPath() + } + #endregion + + #region classpath management + /// + /// Classpathes & classes cache initialization + /// + public override void BuildClassPath() { ReleaseClasspath(); started = true; - if (as2settings == null) throw new Exception("BuildClassPath() must be overridden"); - if (contextSetup == null) + if (as2settings is null) throw new Exception("BuildClassPath() must be overridden"); + contextSetup ??= new ContextSetupInfos { - contextSetup = new ContextSetupInfos(); - contextSetup.Lang = settings.LanguageId; - contextSetup.Platform = "Flash Player"; - contextSetup.Version = as2settings.DefaultFlashVersion + ".0"; - } + Lang = settings.LanguageId, + Platform = "Flash Player", + Version = as2settings.DefaultFlashVersion + ".0" + }; - // external version definition + // external version definition platform = contextSetup.Platform; majorVersion = as2settings.DefaultFlashVersion; minorVersion = 0; ParseVersion(contextSetup.Version, ref majorVersion, ref minorVersion); - + // - // Class pathes + // Class pathes // - classPath = new List(); + classPath = new List(); // MTASC - string mtascPath = PluginBase.CurrentProject != null + var mtascPath = PluginBase.CurrentProject != null ? PluginBase.CurrentProject.CurrentSDK : PathHelper.ResolvePath(as2settings.GetDefaultSDK().Path); if (Path.GetExtension(mtascPath) != "") mtascPath = Path.GetDirectoryName(mtascPath); string path; - if ((as2settings.UseMtascIntrinsic || String.IsNullOrEmpty(as2settings.MMClassPath)) - && !String.IsNullOrEmpty(mtascPath) && System.IO.Directory.Exists(mtascPath)) - { - try - { + if ((as2settings.UseMtascIntrinsic || string.IsNullOrEmpty(as2settings.MMClassPath)) && Directory.Exists(mtascPath)) + { + try + { if (majorVersion == 9) { path = Path.Combine(mtascPath, "std9"); - if (System.IO.Directory.Exists(path)) AddPath(path); + if (Directory.Exists(path)) AddPath(path); else majorVersion = 8; } if (majorVersion == 8) { path = Path.Combine(mtascPath, "std8"); - if (System.IO.Directory.Exists(path)) AddPath(path); + if (Directory.Exists(path)) AddPath(path); } path = Path.Combine(mtascPath, "std"); - if (System.IO.Directory.Exists(path)) AddPath(path); - } - catch {} - } - // Macromedia/Adobe - if (!String.IsNullOrEmpty(as2settings.MMClassPath) && System.IO.Directory.Exists(as2settings.MMClassPath)) + if (Directory.Exists(path)) AddPath(path); + } + catch {} + } + // Macromedia/Adobe + if (Directory.Exists(as2settings.MMClassPath)) { if (classPath.Count == 0) { @@ -196,44 +200,44 @@ public override void BuildClassPath() if (tempVersion > 8) { path = Path.Combine(as2settings.MMClassPath, "FP" + tempVersion); - if (System.IO.Directory.Exists(path)) + if (Directory.Exists(path)) AddPath(path); // now add FP8 tempVersion = 8; } path = Path.Combine(as2settings.MMClassPath, "FP" + Math.Max(7, tempVersion)); - if (System.IO.Directory.Exists(path)) + if (Directory.Exists(path)) { PathModel aPath = new PathModel(path, this); - ManualExploration(aPath, new string[] { "aso", "FP7", "FP8", "FP9" }); + ManualExploration(aPath, new[] { "aso", "FP7", "FP8", "FP9" }); AddPath(aPath); } } } - // add external pathes - List initCP = classPath; - classPath = new List(); - if (contextSetup.Classpath != null) - { - foreach (string cpath in contextSetup.Classpath) + // add external pathes + var initCP = classPath; + classPath = new List(); + if (contextSetup.Classpath != null) + { + foreach (var cpath in contextSetup.Classpath) AddPath(cpath.Trim()); - } + } // add library AddPath(Path.Combine(PathHelper.LibraryDir, "AS2/classes")); - // add user pathes from settings - if (settings.UserClasspath != null && settings.UserClasspath.Length > 0) - { - foreach(string cpath in settings.UserClasspath) AddPath(cpath.Trim()); - } - // add initial pathes - foreach(PathModel mpath in initCP) AddPath(mpath); + // add user pathes from settings + if (!settings.UserClasspath.IsNullOrEmpty()) + { + foreach(var cpath in settings.UserClasspath) AddPath(cpath.Trim()); + } + // add initial pathes + foreach(var mpath in initCP) AddPath(mpath); // parse top-level elements InitTopLevelElements(); if (cFile != null) UpdateTopLevelElements(); - + // add current temporaty path if (temporaryPath != null) { @@ -242,58 +246,50 @@ public override void BuildClassPath() SetTemporaryPath(tempPath); } FinalizeClasspath(); - } - - /// - /// Delete current class's ASO file - /// - public override void RemoveClassCompilerCache() - { - if (as2settings == null) return; - - ClassModel pClass = cFile.GetPublicClass(); - if (as2settings.MMClassPath == null || pClass.IsVoid()) - return; - string package = (cFile.Package.Length > 0) ? cFile.Package + "." : ""; - string packagePath = dirSeparator + package.Replace('.', dirSeparatorChar); - string file = Path.Combine(as2settings.MMClassPath, "aso") + packagePath + package + pClass.Name + ".aso"; - try - { - if (File.Exists(file)) File.Delete(file); - } - catch {} - } + } + + /// + /// Delete current class's ASO file + /// + public override void RemoveClassCompilerCache() + { + if (as2settings is null) return; + + var pClass = cFile.GetPublicClass(); + if (as2settings.MMClassPath is null || pClass.IsVoid()) return; + var package = (cFile.Package.Length > 0) ? cFile.Package + "." : ""; + var packagePath = dirSeparator + package.Replace('.', dirSeparatorChar); + var file = Path.Combine(as2settings.MMClassPath, "aso") + packagePath + package + pClass.Name + ".aso"; + try + { + if (File.Exists(file)) File.Delete(file); + } + catch {} + } #endregion #region class resolution - - public override ClassModel CurrentClass - { - get + + public override ClassModel CurrentClass + { + get { - if (cFile == FileModel.Ignore) + if (cFile == FileModel.Ignore) return ClassModel.VoidClass; + if (cClass is null) + { + cClass = ClassModel.VoidClass; + cFile.OutOfDate = true; + } + // update class + if (cFile.OutOfDate) { - return ClassModel.VoidClass; + if (cFile.FileName.Length > 0) UpdateCurrentFile(true); + // update "this" and "super" special vars + UpdateTopLevelElements(); } - if (cClass == null) - { - cClass = ClassModel.VoidClass; - cFile.OutOfDate = true; - } - // update class - if (cFile.OutOfDate) - { - if (cFile.FileName.Length > 0) - { - string prevClassName = cClass.Name; - UpdateCurrentFile(true); - } - // update "this" and "super" special vars - UpdateTopLevelElements(); - } - return cClass; - } - } + return cClass; + } + } /// /// Evaluates the visibility of one given type from another. @@ -304,14 +300,13 @@ public override ClassModel CurrentClass /// Completion visibility public override Visibility TypesAffinity(ClassModel inClass, ClassModel withClass) { - if (inClass == null || withClass == null) return Visibility.Public; + if (inClass is null || withClass is null) return Visibility.Public; // inheritance affinity - ClassModel tmp = inClass; - while (!tmp.IsVoid()) + var type = inClass; + while (!type.IsVoid()) { - if (tmp.Type == withClass.Type) - return Visibility.Public | Visibility.Private; - tmp = tmp.Extends; + if (type.Type == withClass.Type) return Visibility.Public | Visibility.Private; + type = type.Extends; } // public only return Visibility.Public; @@ -325,8 +320,9 @@ public override Visibility TypesAffinity(ClassModel inClass, ClassModel withClas /// Inherited type public override string DefaultInheritance(string package, string classname) { - if (package.Length == 0 && classname == features.objectKey) return features.voidKey; - else return features.objectKey; + return package.Length == 0 && classname == features.objectKey + ? features.voidKey + : features.objectKey; } /// @@ -336,51 +332,47 @@ public override string DefaultInheritance(string package, string classname) /// Response structure public override void ResolveTopLevelElement(string token, ASResult result) { - if (topLevel != null && topLevel.Members.Count > 0) + if (topLevel is null || topLevel.Members.Count == 0) return; + // current class + var inClass = Context.CurrentClass; + if (token == "this") + { + result.Member = topLevel.Members.Search("this"); + if (inClass.IsVoid()) inClass = Context.ResolveType(result.Member.Type, null); + result.Type = inClass; + result.InFile = Context.CurrentModel; + result.RelClass = Context.CurrentClass; + return; + } + if (token == "super") { - // current class - ClassModel inClass = ASContext.Context.CurrentClass; - if (token == "this") + if (inClass.IsVoid()) { - result.Member = topLevel.Members.Search("this", 0, 0); - if (inClass.IsVoid()) - inClass = ASContext.Context.ResolveType(result.Member.Type, null); - result.Type = inClass; - result.InFile = ASContext.Context.CurrentModel; - return; + var thisMember = topLevel.Members.Search("this"); + inClass = Context.ResolveType(thisMember.Type, null); } - else if (token == "super") + inClass.ResolveExtends(); + var extends = inClass.Extends; + if (!extends.IsVoid()) { - if (inClass.IsVoid()) - { - MemberModel thisMember = topLevel.Members.Search("this", 0, 0); - inClass = ASContext.Context.ResolveType(thisMember.Type, null); - } - inClass.ResolveExtends(); - ClassModel extends = inClass.Extends; - if (!extends.IsVoid()) - { - result.Member = topLevel.Members.Search("super", 0, 0); - result.Type = extends; - result.InFile = extends.InFile; - return; - } + result.Member = topLevel.Members.Search("super"); + result.Type = extends; + result.InFile = extends.InFile; + result.RelClass = Context.CurrentClass; + return; } + } - // other top-level elements - ASComplete.FindMember(token, topLevel, result, 0, 0); - if (!result.IsNull()) return; + // other top-level elements + ASComplete.FindMember(token, topLevel, result, 0, 0); + if (!result.IsNull()) return; - // special _levelN - if (hasLevels && token.StartsWith("_") && re_level.IsMatch(token)) - { - result.Member = new MemberModel(); - result.Member.Name = token; - result.Member.Flags = FlagType.Variable; - result.Member.Type = "MovieClip"; - result.Type = ResolveType("MovieClip", null); - result.InFile = topLevel; - } + // special _levelN + if (hasLevels && token.StartsWith('_') && re_level.IsMatch(token)) + { + result.Member = new MemberModel {Name = token, Flags = FlagType.Variable, Type = "MovieClip"}; + result.Type = ResolveType("MovieClip", null); + result.InFile = topLevel; } } @@ -391,15 +383,13 @@ public override void ResolveTopLevelElement(string token, ASResult result) /// Current file public override MemberList ResolveImports(FileModel inFile) { - if (inFile == cFile && completionCache.Imports != null) - return completionCache.Imports; - - MemberList imports = new MemberList(); - if (inFile == null) return imports; + if (inFile == cFile && completionCache.Imports != null) return completionCache.Imports; + var imports = new MemberList(); + if (inFile is null) return imports; bool filterImports = (inFile == cFile) && inFile.Classes.Count > 1; int lineMin = (filterImports && inPrivateSection) ? inFile.PrivateSectionIndex : 0; int lineMax = (filterImports && inPrivateSection) ? int.MaxValue : inFile.PrivateSectionIndex; - foreach (MemberModel item in inFile.Imports) + foreach (var item in inFile.Imports) { if (filterImports && (item.LineFrom < lineMin || item.LineFrom > lineMax)) continue; if (item.Name != "*") @@ -407,18 +397,18 @@ public override MemberList ResolveImports(FileModel inFile) if (settings.LazyClasspathExploration) imports.Add(item); else { - ClassModel type = ResolveType(item.Type, null); + var type = ResolveType(item.Type, null); if (!type.IsVoid()) imports.Add(type); else { // package-level declarations - int p = item.Type.LastIndexOf('.'); - if (p < 0) continue; - string package = item.Type.Substring(0, p); - string token = item.Type.Substring(p+1); - FileModel pack = ResolvePackage(package, false); - if (pack == null) continue; - MemberModel member = pack.Members.Search(token, 0, 0); + var p = item.Type.LastIndexOf('.'); + if (p == -1) continue; + var package = item.Type.Substring(0, p); + var token = item.Type.Substring(p+1); + var pack = ResolvePackage(package, false); + if (pack is null) continue; + var member = pack.Members.Search(token); if (member != null) imports.Add(member); } } @@ -426,14 +416,11 @@ public override MemberList ResolveImports(FileModel inFile) else { // classes matching wildcard - FileModel matches = ResolvePackage(item.Type.Substring(0, item.Type.Length - 2), false); - + var matches = ResolvePackage(item.Type.Substring(0, item.Type.Length - 2), false); if (matches != null) { - foreach (MemberModel import in matches.Imports) - imports.Add(import); - foreach (MemberModel member in matches.Members) - imports.Add(member); + imports.Add(matches.Imports); + imports.Add(matches.Members); } } } @@ -450,42 +437,38 @@ public override MemberList ResolveImports(FileModel inFile) /// Position in the file public override bool IsImported(MemberModel member, int atLine) { - FileModel cFile = ASContext.Context.CurrentModel; - string fullName = member.Type; - string name = member.Name; - int lineMin = (ASContext.Context.InPrivateSection) ? cFile.PrivateSectionIndex : 0; - int lineMax = atLine; + if (member == ClassModel.VoidClass) return false; + var cFile = Context.CurrentModel; + var fullName = member.Type; + var name = member.Name; + var lineMin = (Context.InPrivateSection) ? cFile.PrivateSectionIndex : 0; + var lineMax = atLine; foreach (MemberModel import in cFile.Imports) { - if (import.LineFrom >= lineMin && import.LineFrom <= lineMax && import.Name == name) - { - if (import.Type != fullName) throw new Exception("Ambiguous Type"); - return true; - } - else if (import.Name == "*" && import.Type.Replace("*", name) == fullName) + if (import.LineFrom >= lineMin && import.LineFrom <= lineMax && import.Name == name && import.Type == fullName) return true; + if (import.Name == "*" && import.Type.Replace("*", name) == fullName) return true; } return false; } - /// - /// Retrieves a class model from its name - /// - /// Class (short or full) name - /// Current file - /// A parsed class or an empty ClassModel if the class is not found + /// + /// Retrieves a class model from its name + /// + /// Class (short or full) name + /// Current file + /// A parsed class or an empty ClassModel if the class is not found public override ClassModel ResolveType(string cname, FileModel inFile) - { + { // unknown type - if (string.IsNullOrEmpty(cname) || cname == features.voidKey || classPath == null) + if (string.IsNullOrEmpty(cname) || cname == features.voidKey || classPath is null) return ClassModel.VoidClass; // typed array - if (cname.IndexOf('@') > 0) - return ResolveTypeIndex(cname, inFile); + if (cname.Contains('@')) return ResolveTypeIndex(cname, inFile); - string package = ""; - Match m = re_lastDot.Match(cname); + var package = ""; + var m = re_lastDot.Match(cname); if (m.Success) { package = cname.Substring(0, m.Index); @@ -496,7 +479,7 @@ public override ClassModel ResolveType(string cname, FileModel inFile) if (inFile != null && inFile.Classes.Count > 0) { foreach (ClassModel aClass in inFile.Classes) - if (aClass.Name == cname && (package == "" || package == inFile.Package)) + if (aClass.Name == cname && (package.Length == 0 || package == inFile.Package)) return aClass; } @@ -504,7 +487,7 @@ public override ClassModel ResolveType(string cname, FileModel inFile) string inPackage = (features.hasPackages && inFile != null) ? inFile.Package : ""; // search in imported classes - if (package == "" && inFile != null) + if (package.Length == 0 && inFile != null) { foreach (MemberModel import in inFile.Imports) { @@ -514,22 +497,22 @@ public override ClassModel ResolveType(string cname, FileModel inFile) package = import.Type.Substring(0, import.Type.Length - cname.Length - 1); break; } - else if (features.hasImportsWildcard) + if (features.hasImportsWildcard) { if (import.Name == "*" && import.Type.Length > 2) { // try wildcards - string testPackage = import.Type.Substring(0, import.Type.Length - 2); + var testPackage = import.Type.Substring(0, import.Type.Length - 2); if (settings.LazyClasspathExploration) { - ClassModel testClass = GetModel(testPackage, cname, inPackage); + var testClass = GetModel(testPackage, cname, inPackage); if (!testClass.IsVoid()) return testClass; } else { - FileModel pack = ResolvePackage(testPackage, false); - if (pack == null) continue; - MemberModel found = pack.Imports.Search(cname, 0, 0); + var pack = ResolvePackage(testPackage, false); + if (pack is null) continue; + var found = pack.Imports.Search(cname); if (found != null) return ResolveType(found.Type, null); } } @@ -538,14 +521,14 @@ public override ClassModel ResolveType(string cname, FileModel inFile) { if (settings.LazyClasspathExploration) { - ClassModel testClass = GetModel(import.Type, cname, inPackage); + var testClass = GetModel(import.Type, cname, inPackage); if (!testClass.IsVoid()) return testClass; } else { - FileModel pack = ResolvePackage(import.Type, false); - if (pack == null) continue; - MemberModel found = pack.Imports.Search(cname, 0, 0); + var pack = ResolvePackage(import.Type, false); + if (pack is null) continue; + var found = pack.Imports.Search(cname); if (found != null) return ResolveType(found.Type, null); } } @@ -556,10 +539,35 @@ public override ClassModel ResolveType(string cname, FileModel inFile) return GetModel(package, cname, inPackage); } + public override ClassModel ResolveToken(string token, FileModel inFile) + { + var tokenLength = token?.Length ?? 0; + if (tokenLength > 0) + { + if (token == "true" || token == "false") return ResolveType(features.booleanKey, inFile); + var first = token[0]; + if (char.IsDigit(token, 0) + // for example: -1, +1 + || (tokenLength > 1 && (first == '-' || first == '+') && char.IsDigit(token, 1)) + // for example: --1, ++1 + || (tokenLength > 2 && ((first == '-' && token[1] == '-') || (first == '+' && token[1] == '+')) && char.IsDigit(token, 2))) + { + if (features.IntegerKey is null) return ResolveType(features.numberKey, inFile); + if (token.Contains('.') || token.Contains('e')) return ResolveType(features.numberKey, inFile); + return ResolveType(features.IntegerKey, inFile); + } + var last = token[tokenLength - 1]; + if (first == '{' && last == '}') return ResolveType(features.objectKey, inFile); + if (first == '[' && last == ']') return ResolveType(features.arrayKey, inFile); + if (tokenLength > 1 && (first == '"' || first == '\'') && last == first) return ResolveType(features.stringKey, inFile); + } + return base.ResolveToken(token, inFile); + } + protected ClassModel ResolveTypeIndex(string cname, FileModel inFile) { int p = cname.IndexOf('@'); - if (p < 0) return ClassModel.VoidClass; + if (p == -1) return ClassModel.VoidClass; string indexType = cname.Substring(p + 1); string baseType = cname.Substring(0, p); @@ -569,22 +577,22 @@ protected ClassModel ResolveTypeIndex(string cname, FileModel inFile) ClassModel indexClass = ResolveType(indexType, inFile); - if (baseType == "Object" || baseType == "Dynamic") + if (baseType == inFile.Context.Features.dynamicKey) { - if (!indexClass.IsVoid()) return indexClass; - return MakeCustomObjectClass(originalClass, indexType); + return !indexClass.IsVoid() + ? indexClass + : MakeCustomObjectClass(originalClass, indexType); } if (indexClass.IsVoid()) return originalClass; indexType = indexClass.QualifiedName; - FileModel aFile = originalClass.InFile; + var aFile = originalClass.InFile; // is the type already cloned? - foreach (ClassModel otherClass in aFile.Classes) + foreach (var otherClass in aFile.Classes) if (otherClass.IndexType == indexType) return otherClass; // clone the type - ClassModel aClass = originalClass.Clone() as ClassModel; - + var aClass = originalClass.Clone(); aClass.Name = baseType + "@" + indexType; aClass.IndexType = indexType; @@ -596,19 +604,18 @@ protected ClassModel ResolveTypeIndex(string cname, FileModel inFile) } // replace 'Object' and '*' by the index type else - foreach (MemberModel member in aClass.Members) - { - if (member.Type == features.objectKey || member.Type == "*") member.Type = indexType; - if (member.Parameters != null) + foreach (var member in aClass.Members) { - foreach (MemberModel param in member.Parameters) + if (member.Type == features.objectKey || member.Type == "*") member.Type = indexType; + if (member.Parameters != null) { - if (param.Name == "value" - && (param.Type == features.objectKey || param.Type == "*")) - param.Type = indexType; + foreach (var param in member.Parameters) + { + if (param.Name == "value" && (param.Type == features.objectKey || param.Type == "*")) + param.Type = indexType; + } } } - } aFile.Classes.Add(aClass); return aClass; @@ -616,21 +623,24 @@ protected ClassModel ResolveTypeIndex(string cname, FileModel inFile) protected ClassModel MakeCustomObjectClass(ClassModel objectClass, string indexType) { - foreach (ClassModel c in objectClass.InFile.Classes) - if (c.IndexType == indexType) return c; - - ClassModel aClass = new ClassModel(); - aClass.Flags = objectClass.Flags; - aClass.Access = objectClass.Access; - aClass.ExtendsType = ""; - aClass.Name = objectClass.QualifiedName + "@" + indexType; - aClass.IndexType = indexType; - aClass.InFile = objectClass.InFile; + foreach (var c in objectClass.InFile.Classes) + if (c.IndexType == indexType) + return c; - FlagType flags = FlagType.Dynamic | FlagType.Variable | FlagType.AutomaticVar; - foreach (string prop in indexType.Split(',')) + var aClass = new ClassModel { - MemberModel member = new MemberModel(prop, "", flags, Visibility.Public); + Flags = objectClass.Flags, + Access = objectClass.Access, + ExtendsType = "", + Name = objectClass.QualifiedName + "@" + indexType, + IndexType = indexType, + InFile = objectClass.InFile + }; + + const FlagType flags = FlagType.Dynamic | FlagType.Variable | FlagType.AutomaticVar; + foreach (var prop in indexType.Split(',')) + { + var member = new MemberModel(prop, "", flags, Visibility.Public); aClass.Members.Add(member); } objectClass.InFile.Classes.Add(aClass); @@ -644,16 +654,16 @@ protected ClassModel MakeCustomObjectClass(ClassModel objectClass, string indexT /// Class name /// Package reference for resolution /// - public override ClassModel GetModel(string package, string cname, string inPackage) + public override ClassModel GetModel(string package, string cname, string? inPackage) { - if (!settings.LazyClasspathExploration) + if (!settings.LazyClasspathExploration) { bool testSamePackage = package.Length == 0 && features.hasPackages; bool testModule = package.Length > 0 && features.hasModules; - foreach (PathModel aPath in classPath) + foreach (var aPath in classPath) if (aPath.IsValid && !aPath.Updating) { - ClassModel found = LookupClass(package, cname, inPackage, testSamePackage, testModule, aPath); + var found = LookupClass(package, cname, inPackage, testSamePackage, testModule, aPath); if (found != null) return found; } if (classPath.Count > 0 && classPath[0].IsTemporaryPath) @@ -669,8 +679,7 @@ public override ClassModel GetModel(string package, string cname, string inPacka model = LocateClassFile(classPath[0], fileName); } catch { } - if (model != null) return model; - else return ClassModel.VoidClass; + return model ?? ClassModel.VoidClass; } } else @@ -681,68 +690,76 @@ public override ClassModel GetModel(string package, string cname, string inPacka foreach (PathModel aPath in classPath) if (aPath.IsValid && !aPath.Updating) { - ClassModel model = LocateClassFile(aPath, fileName); + var model = LocateClassFile(aPath, fileName); if (model != null) return model; } } return ClassModel.VoidClass; - } + } - private ClassModel LookupClass(string package, string cname, string inPackage, bool testSamePackage, bool testModule, PathModel aPath) + ClassModel LookupClass(string package, string cname, string? inPackage, bool testSamePackage, bool testModule, PathModel aPath) { - bool matchParentPackage = testSamePackage && features.hasFriendlyParentPackages; - - ClassModel found = null; - int pLen = inPackage.Length; - - aPath.ForeachFile((aFile) => + ClassModel result = null; + inPackage ??= string.Empty; + var matchParentPackage = testSamePackage && features.hasFriendlyParentPackages; + var pLen = inPackage.Length; + aPath.ForeachFile(aFile => { - string pkg = aFile.Package; + var count = aFile.Classes.Count; + if (count == 0) return true; + var pkg = aFile.Package; // qualified path - if (pkg == package && aFile.Classes.Count > 0) + if (pkg == package) { - foreach (ClassModel aClass in aFile.Classes) - if (aClass.Name == cname && (aFile.Module == "" || aFile.Module == aClass.Name)) + for (var i = 0; i < count; i++) + { + var aClass = aFile.Classes[i]; + if (aClass.Name == cname && (pkg == "" || aFile.Module == "" || aFile.Module == aClass.Name)) { - found = aClass; + result = aClass; return false; } + } } - else if (testModule && aFile.FullPackage == package && aFile.Classes.Count > 0) + else if (testModule && aFile.FullPackage == package) { - foreach (ClassModel aClass in aFile.Classes) + for (var i = 0; i < count; i++) + { + var aClass = aFile.Classes[i]; if (aClass.Name == cname) { - found = aClass; + result = aClass; return false; } + } } // in the same (or parent) package - else if (testSamePackage) + else if (testSamePackage && (pkg == inPackage || (matchParentPackage && pkg.Length < pLen && inPackage.StartsWithOrdinal(pkg + ".")))) { - if (inPackage == pkg || (matchParentPackage && pkg.Length < pLen && inPackage.StartsWith(pkg + "."))) - foreach (ClassModel aClass in aFile.Classes) - if (aClass.Name == cname /*&& (aFile.Module == "" || aFile.Module == aClass.Name)*/) - { - found = aClass; - return false; - } + for (var i = 0; i < count; i++) + { + var aClass = aFile.Classes[i]; + if (aClass.Name == cname) + { + result = aClass; + return false; + } + } } return true; }); - return found; + return result; } - private ClassModel LocateClassFile(PathModel aPath, string fileName) + ClassModel LocateClassFile(PathModel aPath, string fileName) { if (!aPath.IsValid) return null; try { string path = Path.Combine(aPath.Path, fileName); // cached file - if (aPath.HasFile(path)) + if (aPath.TryGetFile(path, out var nFile)) { - FileModel nFile = aPath.GetFile(path); if (nFile.Context != this) { // not associated with this context -> refresh @@ -752,9 +769,9 @@ private ClassModel LocateClassFile(PathModel aPath, string fileName) return nFile.GetPublicClass(); } // non-cached existing file - else if (File.Exists(path)) + if (File.Exists(path)) { - FileModel nFile = GetFileModel(path); + nFile = GetFileModel(path); if (nFile != null) { aPath.AddFile(nFile); @@ -782,110 +799,104 @@ public override void CheckModel(bool onFileOpen) base.CheckModel(onFileOpen); return; } - string prevPackage = (onFileOpen) ? null : cFile.Package; - string prevCname = (onFileOpen) ? null : cFile.GetPublicClass().Name; + string prevPackage = null; + string prevCname = null; + if(onFileOpen) + { + prevPackage = cFile.Package; + prevCname = cFile.GetPublicClass().Name; + } // refresh model base.CheckModel(onFileOpen); if (!MessageBar.Locked && features.checkFileName && cFile.Version > 1) { - string package = cFile.Package; - ClassModel pClass = cFile.GetPublicClass(); - if (package.Length > 0) + var package = cFile.Package; + var pClass = cFile.GetPublicClass(); + var pathname = package.Replace('.', Path.DirectorySeparatorChar); + var fullpath = Path.GetDirectoryName(cFile.FileName); + if (package.Length == 0 || !fullpath.EndsWithOrdinal(pathname)) { - string pathname = package.Replace('.', Path.DirectorySeparatorChar); - string fullpath = Path.GetDirectoryName(cFile.FileName); - if (!fullpath.ToUpper().EndsWith(pathname.ToUpper())) + if (settings.FixPackageAutomatically && PluginBase.MainForm.CurrentDocument?.SciControl is { } sci) { - if (settings.FixPackageAutomatically && CurSciControl != null) + var packagePattern = cFile.Context.Settings.LanguageId == "AS2" + ? new Regex("class\\s+(" + cFile.Package.Replace(".", "\\.") + "\\." + pClass.Name + ')') + : new Regex("package\\s+(" + cFile.Package.Replace(".", "\\.") + ')'); + + var regexPackageLine = ""; + var pos = -1; + var txt = ""; + var p = 0; + var counter = sci.Length; + while (p < counter) { - bool isAs2 = cFile.Context.Settings.LanguageId == "AS2"; - - int pos = -1; - - string txt = ""; - string regexPackageLine = ""; - - int counter = CurSciControl.Length; - int p = 0; - Regex packagePattern = null; - if (isAs2) + var c = (char) sci.CharAt(p++); + txt += c; + if (txt.Length > 5 && c <= 32) { - packagePattern = new Regex("class\\s+(" + cFile.Package.Replace(".", "\\.") + "\\." + pClass.Name + ')'); - } - else - { - packagePattern = new Regex("package\\s+(" + cFile.Package.Replace(".", "\\.") + ')'); - } - while (p < counter) - { - char c = (char)CurSciControl.CharAt(p++); - txt += c; - if (txt.Length > 5 && c <= 32) + var m = packagePattern.Match(txt); + if (m.Success) { - Match m = packagePattern.Match(txt); - if (m.Success) - { - pos = m.Groups[1].Index; - regexPackageLine = m.Value; - break; - } + pos = m.Groups[1].Index; + regexPackageLine = m.Value; + break; } } + } - if (regexPackageLine.Length > 0 && pos > -1) + if (regexPackageLine.Length > 0 && pos > -1) + { + var orgid = "Info.PackageDontMatchFilePath"; + var classpaths = Context.Classpath; + if (classpaths != null) { - string orgid = "Info.PackageDontMatchFilePath"; - List classpaths = Context.Classpath; - if (classpaths != null) + string correctPath = null; + foreach (var pm in classpaths) { - string correctPath = null; - foreach (PathModel pm in classpaths) + if (fullpath.Contains(pm.Path) && fullpath.Length > pm.Path.Length) { - if (fullpath.IndexOf(pm.Path) > -1 && fullpath.Length > pm.Path.Length) - { - correctPath = fullpath.Substring(pm.Path.Length + 1); - } - else if (fullpath.ToLower() == pm.Path.ToLower()) - { - correctPath = ""; // We are in root, no package.. - } + correctPath = fullpath.Substring(pm.Path.Length + 1); } - if (correctPath != null) + else if (fullpath.ToLower() == pm.Path.ToLower()) { - correctPath = correctPath.Replace(Path.DirectorySeparatorChar, '.'); - CurSciControl.SetSel(pos, pos + cFile.Package.Length); - CurSciControl.ReplaceSel(correctPath); - orgid = "Info.PackageDidntMatchFilePath"; + correctPath = ""; // We are in root, no package.. } } - string org = TextHelper.GetString(orgid); - string msg = String.Format(org, package) + "\n" + cFile.FileName; - MessageBar.ShowWarning(msg); + if (correctPath == "" && package.Length == 0) return; + if (correctPath != null) + { + correctPath = correctPath.Replace(Path.DirectorySeparatorChar, '.'); + sci.SetSel(pos, pos + cFile.Package.Length); + sci.ReplaceSel(correctPath); + orgid = "Info.PackageDidntMatchFilePath"; + } } - - } - else - { - string org = TextHelper.GetString("Info.PackageDontMatchFilePath"); - string msg = String.Format(org, package) + "\n" + cFile.FileName; + var org = TextHelper.GetString(orgid); + var msg = string.Format(org, package) + "\n" + cFile.FileName; MessageBar.ShowWarning(msg); } - return; } - else MessageBar.HideWarning(); + else + { + var org = TextHelper.GetString("Info.PackageDontMatchFilePath"); + var msg = string.Format(org, package) + "\n" + cFile.FileName; + MessageBar.ShowWarning(msg); + } + return; } + + MessageBar.HideWarning(); if (!pClass.IsVoid()) { string cname = pClass.Name; if (prevPackage != package || prevCname != cname) { - if (package.Length > 0) cname = package + "." + cname; - string filename = cname.Replace('.', Path.DirectorySeparatorChar) + Path.GetExtension(cFile.FileName); - if (!cFile.FileName.ToUpper().EndsWith(filename.ToUpper())) + cname = package + "." + cname; + var filename = cname.Replace('.', Path.DirectorySeparatorChar) + Path.GetExtension(cFile.FileName); + if (!cFile.FileName.ToUpper().EndsWithOrdinal(filename.ToUpper())) { string org = TextHelper.GetString("Info.TypeDontMatchFileName"); - string msg = String.Format(org, cname) + "\n" + cFile.FileName; + string msg = string.Format(org, cname) + "\n" + cFile.FileName; MessageBar.ShowWarning(msg); } else MessageBar.HideWarning(); @@ -894,50 +905,51 @@ public override void CheckModel(bool onFileOpen) } } - - /// - /// Update Flash intrinsic known vars - /// - protected override void UpdateTopLevelElements() - { - MemberModel special; - special = topLevel.Members.Search("this", 0, 0); - if (special != null) - { + /// + /// Update Flash intrinsic known vars + /// + protected override void UpdateTopLevelElements() + { + var special = topLevel.Members.Search("this"); + if (special != null) + { if (!cClass.IsVoid()) special.Type = cClass.QualifiedName; else special.Type = (cFile.Version > 1) ? features.voidKey : docType; - } - special = topLevel.Members.Search("super", 0, 0); - if (special != null) - { + } + special = topLevel.Members.Search("super"); + if (special != null) + { cClass.ResolveExtends(); - ClassModel extends = cClass.Extends; - if (!extends.IsVoid()) special.Type = extends.QualifiedName; + var extends = cClass.Extends; + if (!extends.IsVoid()) special.Type = extends.QualifiedName; else special.Type = (cFile.Version > 1) ? features.voidKey : features.objectKey; - } - } - - /// - /// Prepare AS2 intrinsic known vars/methods/classes - /// - protected override void InitTopLevelElements() - { - string filename = "toplevel.as"; + } + } + + /// + /// Prepare AS2 intrinsic known vars/methods/classes + /// + protected override void InitTopLevelElements() + { + var filename = "toplevel.as"; topLevel = new FileModel(filename); // search top-level declaration - foreach(PathModel aPath in classPath) - if (File.Exists(Path.Combine(aPath.Path, filename))) + foreach (var aPath in classPath) { - filename = Path.Combine(aPath.Path, filename); - topLevel = GetCachedFileModel(filename); - break; + var path = Path.Combine(aPath.Path, filename); + if (File.Exists(path)) + { + filename = path; + topLevel = GetCachedFileModel(filename); + break; + } } if (File.Exists(filename)) { // MTASC toplevel-style declaration: - ClassModel tlClass = topLevel.GetPublicClass(); + var tlClass = topLevel.GetPublicClass(); if (!tlClass.IsVoid()) { topLevel.Members = tlClass.Members; @@ -945,26 +957,17 @@ protected override void InitTopLevelElements() topLevel.Classes = new List(); } } - // not found - else - { - //ErrorHandler.ShowInfo("Top-level elements class not found. Please check your Program Settings."); - } - - if (topLevel.Members.Search("_root", 0, 0) == null) - topLevel.Members.Add(new MemberModel("_root", docType, FlagType.Variable, Visibility.Public)); - if (topLevel.Members.Search("_global", 0, 0) == null) - topLevel.Members.Add(new MemberModel("_global", features.objectKey, FlagType.Variable, Visibility.Public)); - if (topLevel.Members.Search("this", 0, 0) == null) - topLevel.Members.Add(new MemberModel("this", "", FlagType.Variable, Visibility.Public)); - if (topLevel.Members.Search("super", 0, 0) == null) - topLevel.Members.Add(new MemberModel("super", "", FlagType.Variable, Visibility.Public)); - if (topLevel.Members.Search(features.voidKey, 0, 0) == null) - topLevel.Members.Add(new MemberModel(features.voidKey, "", FlagType.Class | FlagType.Intrinsic, Visibility.Public)); - topLevel.Members.Sort(); - foreach (MemberModel member in topLevel.Members) + // not found + + if (!topLevel.Members.Contains("_root")) topLevel.Members.Add(new MemberModel("_root", docType, FlagType.Variable, Visibility.Public)); + if (!topLevel.Members.Contains("_global")) topLevel.Members.Add(new MemberModel("_global", features.objectKey, FlagType.Variable, Visibility.Public)); + if (!topLevel.Members.Contains("this")) topLevel.Members.Add(new MemberModel("this", string.Empty, FlagType.Variable, Visibility.Public)); + if (!topLevel.Members.Contains("super")) topLevel.Members.Add(new MemberModel("super", string.Empty, FlagType.Variable, Visibility.Public)); + if (!topLevel.Members.Contains(features.voidKey)) topLevel.Members.Add(new MemberModel(features.voidKey, string.Empty, FlagType.Class | FlagType.Intrinsic, Visibility.Public)); + topLevel.Members.Sort(); + foreach (var member in topLevel.Members) member.Flags |= FlagType.Intrinsic; - } + } /// /// Retrieves a package content @@ -973,130 +976,123 @@ protected override void InitTopLevelElements() /// Force file system exploration /// Package folders and types public override FileModel ResolvePackage(string name, bool lazyMode) - { - if (name == null) name = ""; + { + if (name is null) name = ""; else if (!re_package.IsMatch(name)) return null; - - FileModel pModel = new FileModel(); - pModel.Package = name; - pModel.OutOfDate = false; - - string packagePath = name.Replace('.', dirSeparatorChar); - foreach (PathModel aPath in classPath) if (aPath.IsValid && !aPath.Updating) - { - // explore file system - if (lazyMode || settings.LazyClasspathExploration || aPath.IsTemporaryPath) + var pModel = new FileModel {Package = name, OutOfDate = false}; + var packagePath = name.Replace('.', dirSeparatorChar); + foreach (PathModel aPath in classPath) + if (aPath.IsValid && !aPath.Updating) { - string path = Path.Combine(aPath.Path, packagePath); - if (aPath.IsValid && System.IO.Directory.Exists(path)) + // explore file system + if (lazyMode || settings.LazyClasspathExploration || aPath.IsTemporaryPath) { - try + var path = Path.Combine(aPath.Path, packagePath); + if (Directory.Exists(path)) { - PopulatePackageEntries(name, path, pModel.Imports); - PopulateClassesEntries(name, path, pModel.Imports); - } - catch (Exception ex) - { - ErrorManager.ShowError(ex); + try + { + PopulatePackageEntries(name, path, pModel.Imports); + PopulateClassesEntries(name, path, pModel.Imports); + } + catch (Exception ex) + { + ErrorManager.ShowError(ex); + } } } - } - // explore parsed models - else - { - string prevPackage = null; - string packagePrefix = name.Length > 0 ? name + "." : ""; - int nameLen = name.Length + 1; - aPath.ForeachFile((model) => + // explore parsed models + else { - if (!model.HasPackage) - return true; // skip - string package = model.Package; - if (package == name) + string prevPackage = null; + string packagePrefix = name.Length > 0 ? name + "." : ""; + int nameLen = name.Length + 1; + aPath.ForeachFile((model) => { - foreach (ClassModel type in model.Classes) + if (!model.HasPackage) + return true; // skip + string package = model.Package; + if (package == name) { - if (type.IndexType != null) continue; - MemberModel item = type.ToMemberModel(); - if (type.Access == Visibility.Private) + var count = model.Classes.Count; + for (var i = 0; i < count; i++) + { + var type = model.Classes[i]; + if (type.IndexType != null) continue; + if (type.Access != Visibility.Private) + pModel.Imports.Add(type.ToMemberModel()); + } + count = model.Members.Count; + for (var i = 0; i < count; i++) { - item.Type = item.Name; - item.Access = Visibility.Private; + pModel.Members.Add(model.Members[i].Clone()); } - pModel.Imports.Add(item); } - foreach (MemberModel member in model.Members) - pModel.Members.Add(member.Clone() as MemberModel); - } - else if (package != prevPackage - && (package.Length > name.Length && package.StartsWith(packagePrefix))) // imports - { - prevPackage = package; - if (nameLen > 1) package = package.Substring(nameLen); - int p = package.IndexOf('.'); - if (p > 0) package = package.Substring(0, p); - if (pModel.Imports.Search(package, 0, 0) == null) // sub packages + else if (package != prevPackage + && (package.Length > name.Length && package.StartsWithOrdinal(packagePrefix))) // imports { - pModel.Imports.Add(new MemberModel(package, package, FlagType.Package, Visibility.Public)); + prevPackage = package; + if (nameLen > 1) package = package.Substring(nameLen); + int p = package.IndexOf('.'); + if (p > 0) package = package.Substring(0, p); + if (!pModel.Imports.Contains(package)) // sub packages + { + pModel.Imports.Add(new MemberModel(package, package, FlagType.Package, Visibility.Public)); + } } - } - return true; - }); + return true; + }); + } } - } - // result + // result if (pModel.Imports.Count > 0 || pModel.Members.Count > 0) - { + { pModel.Imports.Sort(); - return pModel; - } - else return null; - } + return pModel; + } + return null; + } - private void PopulateClassesEntries(string package, string path, MemberList memberList) + void PopulateClassesEntries(string package, string path, MemberList memberList) { string[] fileEntries = null; try { - fileEntries = System.IO.Directory.GetFiles(path, "*" + settings.DefaultExtension); + fileEntries = Directory.GetFiles(path, "*" + settings.DefaultExtension); } catch { } - if (fileEntries == null) return; - string mname; - string type; - FlagType flag = FlagType.Class | ((package == null) ? FlagType.Intrinsic : 0); + if (fileEntries is null) return; + var flag = FlagType.Class | (package is null ? FlagType.Intrinsic : 0); foreach (string entry in fileEntries) { - mname = GetLastStringToken(entry, dirSeparator); - mname = mname.Substring(0, mname.LastIndexOf(".")); - if (mname.Length > 0 && memberList.Search(mname, 0, 0) == null && re_token.IsMatch(mname)) + var mname = GetLastStringToken(entry, dirSeparator); + mname = mname.Substring(0, mname.LastIndexOf('.')); + if (mname.Length > 0 && !memberList.Contains(mname) && re_token.IsMatch(mname)) { - type = mname; + var type = mname; if (package.Length > 0) type = package + "." + mname; memberList.Add(new MemberModel(mname, type, flag, Visibility.Public)); } } } - private void PopulatePackageEntries(string package, string path, MemberList memberList) + static void PopulatePackageEntries(string package, string path, MemberList memberList) { string[] dirEntries = null; try { - dirEntries = System.IO.Directory.GetDirectories(path); + dirEntries = Directory.GetDirectories(path); } catch { } - if (dirEntries == null) return; + if (dirEntries is null) return; - string mname; - string type; foreach (string entry in dirEntries) { - mname = GetLastStringToken(entry, dirSeparator); - if (mname.Length > 0 && memberList.Search(mname, 0, 0) == null && re_token.IsMatch(mname)) + var mname = GetLastStringToken(entry, dirSeparator); + if (mname.Length > 0 && !memberList.Contains(mname) && re_token.IsMatch(mname)) { - type = mname; + var type = mname; if (package.Length > 0) type = package + "." + mname; memberList.Add(new MemberModel(mname, type, FlagType.Package, Visibility.Public)); } @@ -1109,12 +1105,9 @@ private void PopulatePackageEntries(string package, string path, MemberList memb /// public override MemberList GetTopLevelElements() { - if (topLevel != null) - { - if (topLevel.OutOfDate) InitTopLevelElements(); - return topLevel.Members; - } - else return new MemberList(); + if (topLevel is null) return new MemberList(); + if (topLevel.OutOfDate) InitTopLevelElements(); + return topLevel.Members; } /// @@ -1122,88 +1115,79 @@ public override MemberList GetTopLevelElements() /// /// public override MemberList GetVisibleExternalElements() - { + { if (!IsFileValid) return new MemberList(); - - if (completionCache.IsDirty) + if (!completionCache.IsDirty) return completionCache.Elements; + var elements = new MemberList(); + // root types & packages + var baseElements = ResolvePackage(null, false); + if (baseElements != null) { - MemberList elements = new MemberList(); - // root types & packages - FileModel baseElements = ResolvePackage(null, false); - if (baseElements != null) - { - elements.Add(baseElements.Imports); - elements.Add(baseElements.Members); - } - elements.Add(new MemberModel(features.voidKey, features.voidKey, FlagType.Class | FlagType.Intrinsic, 0)); + elements.Add(baseElements.Imports); + elements.Add(baseElements.Members); + } + elements.Add(new MemberModel(features.voidKey, features.voidKey, FlagType.Class | FlagType.Intrinsic, 0)); - //bool qualify = Settings.CompletionShowQualifiedTypes && settings.GenerateImports; - - // other classes in same package - if (features.hasPackages && cFile.Package != "") + // other classes in same package + if (features.hasPackages && cFile.Package != "") + { + var packageElements = ResolvePackage(cFile.Package, false); + if (packageElements != null) { - FileModel packageElements = ResolvePackage(cFile.Package, false); - if (packageElements != null) + foreach (var member in packageElements.Imports) { - foreach (MemberModel member in packageElements.Imports) + if (member.Flags != FlagType.Package) { - if (member.Flags != FlagType.Package) - { - //if (qualify) member.Name = member.Type; - elements.Add(member); - } - } - foreach (MemberModel member in packageElements.Members) - { - string pkg = member.InFile.Package; - //if (qualify && pkg != "") member.Name = pkg + "." + member.Name; - member.Type = pkg != "" ? pkg + "." + member.Name : member.Name; elements.Add(member); } } + foreach (var member in packageElements.Members) + { + var pkg = member.InFile.Package; + member.Type = pkg != "" ? pkg + "." + member.Name : member.Name; + elements.Add(member); + } } - // other classes in same file - if (cFile.PrivateSectionIndex > 0) + } + // other classes in same file + if (cFile.PrivateSectionIndex > 0) + { + if (inPrivateSection && cFile.Classes.Count > 1) { - if (inPrivateSection && cFile.Classes.Count > 1) + var mainClass = cFile.GetPublicClass(); + if (!mainClass.IsVoid()) { - ClassModel mainClass = cFile.GetPublicClass(); - if (!mainClass.IsVoid()) - { - MemberModel toRemove = elements.Search(mainClass.Name, 0, 0); - if (toRemove != null && toRemove.Type == mainClass.QualifiedName) - elements.Remove(toRemove); - } + var toRemove = elements.Search(mainClass.Name); + if (toRemove != null && toRemove.Type == mainClass.QualifiedName) + elements.Remove(toRemove); } + } - MemberModel member; - foreach (ClassModel aClass in cFile.Classes) + foreach (var aClass in cFile.Classes) + { + if (features.hasMultipleDefs || aClass.Access == Visibility.Private) { - if (features.hasMultipleDefs || aClass.Access == Visibility.Private) - { - member = aClass.ToMemberModel(); - elements.Add(member); - } + elements.Add(aClass.ToMemberModel()); } } + } - // imports - elements.Add(ResolveImports(CurrentModel)); + // imports + elements.Add(ResolveImports(CurrentModel)); - // in cache - elements.Sort(); - completionCache = new CompletionCache(this, elements); + // in cache + elements.Sort(); + completionCache = new CompletionCache(this, elements); - // known classes colorization - if (!CommonSettings.DisableKnownTypesColoring && !settings.LazyClasspathExploration && CurSciControl != null) + // known classes colorization + if (!CommonSettings.DisableKnownTypesColoring && !settings.LazyClasspathExploration && PluginBase.MainForm.CurrentDocument?.SciControl is { } sci) + { + try { - try - { - CurSciControl.KeyWords(1, completionCache.Keywords); // additional-keywords index = 1 - CurSciControl.Colourise(0, -1); // re-colorize the editor - } - catch (AccessViolationException){} // catch memory errors - } + sci.KeyWords(1, completionCache.Keywords); // additional-keywords index = 1 + sci.Colourise(0, -1); // re-colorize the editor + } + catch (AccessViolationException){} // catch memory errors } return completionCache.Elements; } @@ -1218,56 +1202,50 @@ public override MemberList GetAllProjectClasses() if (!completionCache.IsDirty && completionCache.AllTypes != null) return completionCache.AllTypes; - MemberList fullList = new MemberList(); - ClassModel aClass; - MemberModel item; + var result = new MemberList(); // public classes - foreach (PathModel aPath in classPath) if (aPath.IsValid && !aPath.Updating) - { - aPath.ForeachFile((aFile) => + foreach (var aPath in classPath) + if (aPath.IsValid && !aPath.Updating) { - aClass = aFile.GetPublicClass(); - if (!aClass.IsVoid() && aClass.IndexType == null && aClass.Access == Visibility.Public) + aPath.ForeachFile(aFile => { - item = aClass.ToMemberModel(); - item.Name = item.Type; - fullList.Add(item); - } - return true; - }); - } + var aClass = aFile.GetPublicClass(); + if (!aClass.IsVoid() && aClass.IndexType is null && aClass.Access == Visibility.Public) + { + var item = aClass.ToMemberModel(); + item.Name = item.Type; + result.Add(item); + } + return true; + }); + } // void - fullList.Add(new MemberModel(features.voidKey, features.voidKey, FlagType.Class | FlagType.Intrinsic, 0)); + result.Add(new MemberModel(features.voidKey, features.voidKey, FlagType.Class | FlagType.Intrinsic, 0)); // in cache - fullList.Sort(); - completionCache.AllTypes = fullList; - return fullList; + result.Sort(); + completionCache.AllTypes = result; + return result; } - #endregion - - #region command line compiler - override public bool CanBuild - { - get { return cFile != null && cFile != FileModel.Ignore; } - } + public override string GetDefaultValue(string type) => "undefined"; + #endregion + + #region command line compiler + + public override bool CanBuild => cFile != null && cFile != FileModel.Ignore; /// /// Retrieve the context's default compiler path /// - public override string GetCompilerPath() - { - if (as2settings != null) return as2settings.GetDefaultSDK().Path; - else return null; - } + public override string GetCompilerPath() => as2settings?.GetDefaultSDK().Path; /// /// Check current file's syntax /// public override void CheckSyntax() { - if (as2settings == null) + if (as2settings is null) { ErrorManager.ShowInfo(TextHelper.GetString("Info.FeatureMissing")); return; @@ -1276,111 +1254,102 @@ public override void CheckSyntax() RunCMD(as2settings.MtascCheckParameters); } - /// - /// Run MTASC compiler in the current class's base folder with current classpath - /// - /// Additional comiler switches - public override void RunCMD(string append) - { - if (as2settings == null) + /// + /// Run MTASC compiler in the current class's base folder with current classpath + /// + /// Additional compiler switches + public override void RunCMD(string append) + { + if (as2settings is null) { ErrorManager.ShowInfo(TextHelper.GetString("Info.FeatureMissing")); return; } - if (!IsFileValid || !File.Exists(CurrentFile)) - return; + if (!IsFileValid || !File.Exists(CurrentFile)) return; if (CurrentModel.Version != 2) { MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidClass")); return; } - string mtascPath = PluginBase.CurrentProject != null - ? PluginBase.CurrentProject.CurrentSDK - : PathHelper.ResolvePath(as2settings.GetDefaultSDK().Path); + var mtascPath = PluginBase.CurrentProject != null + ? PluginBase.CurrentProject.CurrentSDK + : PathHelper.ResolvePath(as2settings.GetDefaultSDK().Path); if (!Directory.Exists(mtascPath) && !File.Exists(mtascPath)) - { + { ErrorManager.ShowInfo(TextHelper.GetString("Info.InvalidMtascPath")); - return; - } - - SetStatusText(settings.CheckSyntaxRunning); - - try - { - // save modified files if needed - if (outputFile != null) MainForm.CallCommand("SaveAllModified", null); - else MainForm.CallCommand("SaveAllModified", ".as"); - - // prepare command + return; + } + + SetStatusText(settings.CheckSyntaxRunning); + + try + { + // save modified files if needed + PluginBase.MainForm.CallCommand("SaveAllModified", outputFile != null ? null : ".as"); + + // prepare command string command = mtascPath; if (Path.GetExtension(command) == "") command = Path.Combine(command, "mtasc.exe"); else mtascPath = Path.GetDirectoryName(mtascPath); command += ";\"" + CurrentFile + "\""; - if (append == null || append.IndexOf("-swf-version") < 0) - command += " -version "+majorVersion; - // classpathes - foreach(PathModel aPath in classPath) - if (aPath.Path != temporaryPath - && !aPath.Path.StartsWith(mtascPath, StringComparison.OrdinalIgnoreCase)) - command += " -cp \"" + aPath.Path.TrimEnd('\\') + "\""; - - // run - string filePath = NormalizePath(cFile.BasePath); - if (PluginBase.CurrentProject != null) - filePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath); - string workDir = MainForm.WorkingDirectory; - MainForm.WorkingDirectory = filePath; - MainForm.CallCommand("RunProcessCaptured", command+" "+append); - MainForm.WorkingDirectory = workDir; - } - catch (Exception ex) - { + if (append is null || !append.Contains("-swf-version")) command += " -version "+majorVersion; + // classpathes + foreach(var aPath in classPath) + if (aPath.Path != temporaryPath + && !aPath.Path.StartsWith(mtascPath, StringComparison.OrdinalIgnoreCase)) + command += " -cp \"" + aPath.Path.TrimEnd('\\') + "\""; + + // run + var filePath = NormalizePath(cFile.BasePath); + if (PluginBase.CurrentProject != null) filePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath); + var workDir = PluginBase.MainForm.WorkingDirectory; + PluginBase.MainForm.WorkingDirectory = filePath; + PluginBase.MainForm.CallCommand("RunProcessCaptured", command+" "+append); + PluginBase.MainForm.WorkingDirectory = workDir; + } + catch (Exception ex) + { ErrorManager.ShowError(ex); - } - } - - /// - /// Calls RunCMD with additional parameters taken from the classes @mtasc doc tag - /// - public override bool BuildCMD(bool failSilently) - { - if (as2settings == null) + } + } + + /// + /// Calls RunCMD with additional parameters taken from the classes @mtasc doc tag + /// + public override bool BuildCMD(bool failSilently) + { + if (as2settings is null) { ErrorManager.ShowInfo(TextHelper.GetString("Info.FeatureMissing")); return false; } - if (!File.Exists(CurrentFile)) - return false; - // check if @mtasc is defined - Match mCmd = null; - ClassModel cClass = cFile.GetPublicClass(); + if (!File.Exists(CurrentFile)) return false; + // check if @mtasc is defined + Match mCmd = null; + var cClass = cFile.GetPublicClass(); if (IsFileValid && cClass.Comments != null) mCmd = re_CMD_BuildCommand.Match(cClass.Comments); - - if (CurrentModel.Version != 2 || mCmd == null || !mCmd.Success) - { - if (!failSilently) - { - MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidForQuickBuild")); - } - return false; - } - - // build command - string command = mCmd.Groups["params"].Value.Trim(); + + if (CurrentModel.Version != 2 || mCmd is null || !mCmd.Success) + { + if (!failSilently) MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidForQuickBuild")); + return false; + } + + // build command + string command = mCmd.Groups["params"].Value.Trim(); try { command = Regex.Replace(command, "[\\r\\n]\\s*\\*", "", RegexOptions.Singleline); - command = " " + MainForm.ProcessArgString(command) + " "; - if (command == null || command.Length == 0) + command = " " + PluginBase.MainForm.ProcessArgString(command) + " "; + if (string.IsNullOrEmpty(command)) { - if (!failSilently) - throw new Exception(TextHelper.GetString("Info.InvalidQuickBuildCommand")); + if (!failSilently) throw new Exception(TextHelper.GetString("Info.InvalidQuickBuildCommand")); return false; } outputFile = null; @@ -1388,18 +1357,17 @@ public override bool BuildCMD(bool failSilently) trustFileWanted = false; // get SWF url - MatchCollection mPar = re_SplitParams.Matches(command + "-eof"); - int mPlayIndex = -1; - bool noPlay = false; + var mPar = re_SplitParams.Matches(command + "-eof"); + var mPlayIndex = -1; + var noPlay = false; if (mPar.Count > 0) { - string op; for (int i = 0; i < mPar.Count; i++) { - op = mPar[i].Groups["switch"].Value; + var op = mPar[i].Groups["switch"].Value; int start = mPar[i].Index + mPar[i].Length; int end = (mPar.Count > i + 1) ? mPar[i + 1].Index : start; - if ((op == "-swf") && (outputFile == null) && (mPlayIndex < 0)) + if ((op == "-swf") && (outputFile is null) && (mPlayIndex < 0)) { if (end > start) outputFile = command.Substring(start, end - start).Trim(); @@ -1435,24 +1403,21 @@ public override bool BuildCMD(bool failSilently) } } } - if (outputFile.Length == 0) outputFile = null; + if (outputFile.IsNullOrEmpty()) outputFile = null; // cleaning custom switches if (mPlayIndex >= 0) { command = command.Substring(0, mPar[mPlayIndex].Index) + command.Substring(mPar[mPlayIndex + 1].Index); } - if (trustFileWanted) - { - command = command.Replace("-trust", ""); - } + if (trustFileWanted) command = command.Replace("-trust", ""); if (noPlay || !settings.PlayAfterBuild) { command = command.Replace("-noplay", ""); outputFile = null; runAfterBuild = false; } - else runAfterBuild = (outputFile != null); + else runAfterBuild = outputFile != null; // fixing output path if (runAfterBuild) @@ -1474,11 +1439,11 @@ public override bool BuildCMD(bool failSilently) ErrorManager.ShowError(ex); return false; } - - // run - RunCMD(command); - return true; - } + + // run + RunCMD(command); + return true; + } #endregion - } -} + } +} \ No newline at end of file diff --git a/External/Plugins/AS2Context/PluginMain.cs b/External/Plugins/AS2Context/PluginMain.cs index b0db561799..0e600c71a2 100644 --- a/External/Plugins/AS2Context/PluginMain.cs +++ b/External/Plugins/AS2Context/PluginMain.cs @@ -1,113 +1,85 @@ using System; -using System.IO; +using System.Collections.Generic; using System.ComponentModel; -using WeifenLuo.WinFormsUI; +using System.Globalization; +using System.IO; +using System.Text.RegularExpressions; +using ASCompletion.Context; +using PluginCore; +using PluginCore.Helpers; using PluginCore.Localization; using PluginCore.Managers; using PluginCore.Utilities; -using PluginCore.Helpers; -using PluginCore; -using System.Text.RegularExpressions; -using System.Collections.Generic; namespace AS2Context { public class PluginMain : IPlugin, InstalledSDKOwner { - private String pluginName = "AS2Context"; - private String pluginGuid = "1f387fab-421b-42ac-a985-72a03534f731"; - private String pluginHelp = "www.flashdevelop.org/community/"; - private String pluginDesc = "ActionScript 2 context for the ASCompletion engine."; - private String pluginAuth = "FlashDevelop Team"; - private AS2Settings settingObject; - private Context contextInstance; - private String settingFilename; + AS2Settings settingObject; + Context contextInstance; + string settingFilename; #region Required Properties /// /// Api level of the plugin /// - public Int32 Api - { - get { return 1; } - } + public int Api => 1; /// /// Name of the plugin /// - public String Name - { - get { return this.pluginName; } - } + public string Name { get; } = nameof(AS2Context); /// /// GUID of the plugin /// - public String Guid - { - get { return this.pluginGuid; } - } + public string Guid { get; } = "1f387fab-421b-42ac-a985-72a03534f731"; /// /// Author of the plugin /// - public String Author - { - get { return this.pluginAuth; } - } + public string Author { get; } = "FlashDevelop Team"; /// /// Description of the plugin /// - public String Description - { - get { return this.pluginDesc; } - } + public string Description { get; set; } = "ActionScript 2 context for the ASCompletion engine."; /// /// Web address for help /// - public String Help - { - get { return this.pluginHelp; } - } + public string Help { get; } = "https://www.flashdevelop.org/community/"; /// /// Object that contains the settings /// [Browsable(false)] - public Object Settings - { - get { return this.settingObject; } - } + public object Settings => settingObject; #endregion #region Required Methods /// - /// Initializes the plugin - /// + /// Initializes the plugin + /// public void Initialize() { - this.InitBasics(); - this.LoadSettings(); - this.AddEventHandlers(); + InitBasics(); + LoadSettings(); + AddEventHandlers(); } /// /// Disposes the plugin /// - public void Dispose() - { - this.SaveSettings(); - } + public void Dispose() => SaveSettings(); /// /// Handles the incoming events /// - public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority) + public void HandleEvent(object sender, NotifyEvent e, HandlingPriority priority) { switch (e.Type) { @@ -115,7 +87,7 @@ public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority) contextInstance = new Context(settingObject); ValidateSettings(); // Associate this context with AS2 language - ASCompletion.Context.ASContext.RegisterLanguage(contextInstance, "as2"); + ASContext.RegisterLanguage(contextInstance, "as2"); break; } } @@ -129,93 +101,81 @@ public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority) /// public void InitBasics() { - String dataPath = Path.Combine(PathHelper.DataDir, "AS2Context"); - if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath); - this.settingFilename = Path.Combine(dataPath, "Settings.fdb"); - this.pluginDesc = TextHelper.GetString("Info.Description"); + var path = Path.Combine(PathHelper.DataDir, nameof(AS2Context)); + if (!Directory.Exists(path)) Directory.CreateDirectory(path); + settingFilename = Path.Combine(path, "Settings.fdb"); + Description = TextHelper.GetString("Info.Description"); } /// /// Adds the required event handlers /// - public void AddEventHandlers() - { - EventManager.AddEventHandler(this, EventType.UIStarted); - } + public void AddEventHandlers() => EventManager.AddEventHandler(this, EventType.UIStarted); /// /// Loads the plugin settings /// public void LoadSettings() { - this.settingObject = new AS2Settings(); - if (!File.Exists(this.settingFilename)) this.SaveSettings(); + settingObject = new AS2Settings(); + if (!File.Exists(settingFilename)) SaveSettings(); else { - Object obj = ObjectSerializer.Deserialize(this.settingFilename, this.settingObject); - this.settingObject = (AS2Settings)obj; + settingObject = ObjectSerializer.Deserialize(settingFilename, settingObject); if (settingObject.InstalledSDKs != null) - foreach (InstalledSDK sdk in settingObject.InstalledSDKs) + foreach (var sdk in settingObject.InstalledSDKs) sdk.Owner = this; } - if (this.settingObject.MMClassPath == null) this.settingObject.MMClassPath = FindMMClassPath(); - if (this.settingObject.UserClasspath == null) - { - if (this.settingObject.MMClassPath != null) this.settingObject.UserClasspath = new String[] { this.settingObject.MMClassPath }; - else this.settingObject.UserClasspath = new String[] {}; - } + settingObject.MMClassPath ??= FindMMClassPath(); + settingObject.UserClasspath ??= settingObject.MMClassPath != null + ? new[] {settingObject.MMClassPath} + : Array.Empty(); } /// /// Fix some settings values when the context has been created /// - private void ValidateSettings() + void ValidateSettings() { - if (settingObject.InstalledSDKs == null || settingObject.InstalledSDKs.Length == 0) + if (settingObject.InstalledSDKs.IsNullOrEmpty()) { - List allSdks = new List(); - string includedSDK = "Tools\\mtasc"; + var allSdks = new List(); + var includedSDK = "Tools\\mtasc"; if (Directory.Exists(PathHelper.ResolvePath(includedSDK))) { - InstalledSDK sdk = new InstalledSDK(this); - sdk.Path = includedSDK; - allSdks.Add(sdk); + allSdks.Add(new InstalledSDK(this) {Path = includedSDK}); } - string appManDir = Path.Combine(PathHelper.BaseDir, @"Data\AppMan\Archive\mtasc"); + var appManDir = Path.Combine(PathHelper.BaseDir, @"Data\AppMan\Archive\mtasc"); if (Directory.Exists(appManDir)) { - string[] versionDirs = Directory.GetDirectories(appManDir); - foreach (string versionDir in versionDirs) + var versionDirs = Directory.GetDirectories(appManDir); + foreach (var versionDir in versionDirs) { - if (Directory.Exists(versionDir)) - { - InstalledSDK sdk = new InstalledSDK(this); - sdk.Path = versionDir; - allSdks.Add(sdk); - } + if (!Directory.Exists(versionDir)) continue; + allSdks.Add(new InstalledSDK(this) {Path = versionDir}); } } settingObject.InstalledSDKs = allSdks.ToArray(); } - else foreach (InstalledSDK sdk in settingObject.InstalledSDKs) ValidateSDK(sdk); + else + { + foreach (InstalledSDK sdk in settingObject.InstalledSDKs) + { + sdk.Validate(); + } + } settingObject.OnClasspathChanged += SettingObjectOnClasspathChanged; } /// /// Update the classpath if an important setting has changed /// - private void SettingObjectOnClasspathChanged() - { - if (contextInstance != null) contextInstance.BuildClassPath(); - } + void SettingObjectOnClasspathChanged() => contextInstance?.BuildClassPath(); /// /// Saves the plugin settings /// - public void SaveSettings() - { - ObjectSerializer.Serialize(this.settingFilename, this.settingObject); - } + public void SaveSettings() => ObjectSerializer.Serialize(settingFilename, settingObject); #endregion @@ -225,16 +185,15 @@ public bool ValidateSDK(InstalledSDK sdk) { sdk.Owner = this; - IProject project = PluginBase.CurrentProject; - string path = sdk.Path; - if (project != null) - path = PathHelper.ResolvePath(path, Path.GetDirectoryName(project.ProjectPath)); - else - path = PathHelper.ResolvePath(path); + var project = PluginBase.CurrentProject; + var path = sdk.Path; + path = project != null + ? PathHelper.ResolvePath(path, Path.GetDirectoryName(project.ProjectPath)) + : PathHelper.ResolvePath(path); try { - if (path == null || (!Directory.Exists(path) && !File.Exists(path))) + if (!Directory.Exists(path) && !File.Exists(path)) { ErrorManager.ShowInfo("Path not found:\n" + sdk.Path); return false; @@ -247,18 +206,18 @@ public bool ValidateSDK(InstalledSDK sdk) } if (!Directory.Exists(path)) path = Path.GetDirectoryName(path); - string descriptor = Path.Combine(path, "changes.txt"); + var descriptor = Path.Combine(path, "changes.txt"); if (File.Exists(descriptor)) { - string raw = File.ReadAllText(descriptor); - Match mVer = Regex.Match(raw, "[0-9\\-]+\\s*:\\s*([0-9.]+)"); + var text = File.ReadAllText(descriptor); + var mVer = Regex.Match(text, "[0-9\\-]+\\s*:\\s*([0-9.]+)"); if (mVer.Success) { sdk.Version = mVer.Groups[1].Value; - sdk.Name = "MTASC " + sdk.Version; + sdk.Name = $"MTASC {sdk.Version}"; return true; } - else ErrorManager.ShowInfo("Invalid changes.txt file:\n" + descriptor); + ErrorManager.ShowInfo("Invalid changes.txt file:\n" + descriptor); } else ErrorManager.ShowInfo("No changes.txt found:\n" + descriptor); return false; @@ -269,21 +228,21 @@ public bool ValidateSDK(InstalledSDK sdk) #region Macromedia/Adobe Flash IDE // locations in Application Data - static readonly private string[] MACROMEDIA_VERSIONS = { + static readonly string[] MACROMEDIA_VERSIONS = { "\\Adobe\\Flash CS5\\", "\\Adobe\\Flash CS4\\", - "\\Adobe\\Flash CS3\\", - "\\Macromedia\\Flash 8\\", - "\\Macromedia\\Flash MX 2004\\" - }; + "\\Adobe\\Flash CS3\\", + "\\Macromedia\\Flash 8\\", + "\\Macromedia\\Flash MX 2004\\" + }; /// /// Explore the possible locations for the Macromedia Flash IDE classpath /// - static private string FindMMClassPath() + static string FindMMClassPath() { bool found = false; - string deflang = System.Globalization.CultureInfo.CurrentUICulture.Name; + string deflang = CultureInfo.CurrentUICulture.Name; deflang = deflang.Substring(0, 2); string localAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string cp = ""; @@ -291,18 +250,18 @@ static private string FindMMClassPath() { cp = localAppData + path; // default language - if (System.IO.Directory.Exists(cp + deflang + "\\Configuration\\Classes\\")) + if (Directory.Exists(cp + deflang + "\\Configuration\\Classes\\")) { cp += deflang + "\\Configuration\\Classes\\"; found = true; } // look for other languages - else if (System.IO.Directory.Exists(cp)) + else if (Directory.Exists(cp)) { - string[] dirs = System.IO.Directory.GetDirectories(cp); + var dirs = Directory.GetDirectories(cp); foreach (string dir in dirs) { - if (System.IO.Directory.Exists(dir + "\\Configuration\\Classes\\")) + if (Directory.Exists(dir + "\\Configuration\\Classes\\")) { cp = dir + "\\Configuration\\Classes\\"; found = true; @@ -312,12 +271,8 @@ static private string FindMMClassPath() } if (found) break; } - if (found) return cp; - else return null; + return found ? cp : null; } #endregion - } - -} - +} \ No newline at end of file diff --git a/External/Plugins/AS2Context/Properties/AssemblyInfo.cs b/External/Plugins/AS2Context/Properties/AssemblyInfo.cs index e5fc0942da..1bef6c04ea 100644 --- a/External/Plugins/AS2Context/Properties/AssemblyInfo.cs +++ b/External/Plugins/AS2Context/Properties/AssemblyInfo.cs @@ -1,15 +1,14 @@ using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using PluginCore; // Information about this assembly is defined by the following attributes. // Change them to the information which is associated with the assembly you compile. [assembly: AssemblyTitle("AS2Context")] -[assembly: AssemblyDescription("AS2Context Plugin For ASCompletion In FlashDevelop.")] +[assembly: AssemblyDescription("AS2 Context Plugin For ASCompletion In " + DistroConfig.DISTRIBUTION_NAME)] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("FlashDevelop.org")] +[assembly: AssemblyCompany(DistroConfig.DISTRIBUTION_COMPANY)] [assembly: AssemblyProduct("AS2Context")] -[assembly: AssemblyCopyright("FlashDevelop.org 2005-2014")] +[assembly: AssemblyCopyright(DistroConfig.DISTRIBUTION_COPYRIGHT)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0.0")] diff --git a/External/Plugins/AS3Context/AS3Context.csproj b/External/Plugins/AS3Context/AS3Context.csproj index f77a5ad124..f73ae9a4b6 100644 --- a/External/Plugins/AS3Context/AS3Context.csproj +++ b/External/Plugins/AS3Context/AS3Context.csproj @@ -1,182 +1,146 @@  - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF} - Library - Properties - AS3Context - AS3Context - - - - - 3.5 - - - v2.0 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - true - full - false - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - TRACE - prompt - 4 - - - x86 - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - - - x86 - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - TRACE - true - - - - - - - - - - - - - - Component - - - - - UserControl - - - ProfilerUI.cs - - - Component - - - Component - - - - - - - - - False - ..\..\..\FlashDevelop\Bin\Debug\Aga.dll - False - - - False - ..\..\..\FlashDevelop\Bin\Debug\SwfOp.dll - False - - - - - - - - - - - - {61885F70-B4DC-4B44-852D-5D6D03F2A734} - PluginCore - False - - - {74AD0487-CEF9-43FE-9283-BC6F79539ADE} - AS2Context - False - - - {4EBF2653-9654-4E40-880E-0046B3D6210E} - ASCompletion - False - - - {D6AAF434-F4DF-4376-863D-109A8762CECA} - FlashConnect - False - - - {78101C01-E186-4954-B1DD-DEBB7905FAD8} - ProjectManager - False - - - {556F43A0-C288-471A-8CD8-A787FC7ACA34} - XMLCompletion - - - - - - - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - + + + + Debug + AnyCPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF} + Library + Properties + AS3Context + AS3Context + net48 + true + false + false + false + false + x64;x86;AnyCPU + + + true + full + false + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + prompt + 4 + 9 + + + none + true + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + prompt + 4 + 9 + + + x86 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + 9 + + + x86 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + true + 9 + + + true + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + full + x64 + 9 + prompt + + + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + true + x64 + 9 + prompt + + + + + + + + + + + + + + UserControl + + + ProfilerUI.cs + + + Component + + + + + + + + + False + ..\..\..\FlashDevelop\Bin\Debug\Aga.dll + False + + + False + ..\..\..\FlashDevelop\Bin\Debug\SwfOp.dll + False + + + + + + + + + {61885F70-B4DC-4B44-852D-5D6D03F2A734} + PluginCore + False + + + {74AD0487-CEF9-43FE-9283-BC6F79539ADE} + AS2Context + False + + + {4EBF2653-9654-4E40-880E-0046B3D6210E} + ASCompletion + False + + + {D6AAF434-F4DF-4376-863D-109A8762CECA} + FlashConnect + False + + + {78101C01-E186-4954-B1DD-DEBB7905FAD8} + ProjectManager + False + + + {556F43A0-C288-471A-8CD8-A787FC7ACA34} + XMLCompletion + False + + + + + + \ No newline at end of file diff --git a/External/Plugins/AS3Context/AS3Settings.cs b/External/Plugins/AS3Context/AS3Settings.cs index 9adbfe099c..8324303e08 100644 --- a/External/Plugins/AS3Context/AS3Settings.cs +++ b/External/Plugins/AS3Context/AS3Settings.cs @@ -1,12 +1,10 @@ using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing.Design; -using System.Windows.Forms.Design; using System.ComponentModel; -using PluginCore.Localization; +using System.Drawing.Design; +using ASCompletion.Settings; +using Ookii.Dialogs; using PluginCore; -using System.IO; +using PluginCore.Localization; namespace AS3Context { @@ -14,7 +12,7 @@ namespace AS3Context public delegate void InstalledSDKsChangedEvent(); [Serializable] - public class AS3Settings : ASCompletion.Settings.IContextSettings + public class AS3Settings : IContextSettings { [field: NonSerialized] public event ClasspathChangedEvent OnClasspathChanged; @@ -33,8 +31,8 @@ public class AS3Settings : ASCompletion.Settings.IContextSettings [LocalizedCategory("ASCompletion.Category.Documentation"), LocalizedDescription("ASCompletion.Description.DocumentationCommandLine"), DefaultValue(DEFAULT_DOC_COMMAND)] public string DocumentationCommandLine { - get { return documentationCommandLine; } - set { documentationCommandLine = value; } + get => documentationCommandLine; + set => documentationCommandLine = value; } #endregion @@ -59,46 +57,34 @@ public string DocumentationCommandLine protected bool generateImports = DEFAULT_GENERATEIMPORTS; protected bool playAfterBuild = DEFAULT_PLAY; protected bool fixPackageAutomatically = DEFAULT_FIXPACKAGEAUTOMATICALLY; - protected string[] userClasspath = null; - protected InstalledSDK[] installedSDKs = null; + protected string[] userClasspath; + protected InstalledSDK[] installedSDKs; [Browsable(false)] - public string LanguageId - { - get { return "AS3"; } - } + public string LanguageId => "AS3"; [Browsable(false)] - public string DefaultExtension - { - get { return ".as"; } - } + public string DefaultExtension => ".as"; [Browsable(false)] - public string CheckSyntaxRunning - { - get { return TextHelper.GetString("Info.MxmlcRunning"); } - } + public string CheckSyntaxRunning => TextHelper.GetString("Info.MxmlcRunning"); [Browsable(false)] - public string CheckSyntaxDone - { - get { return TextHelper.GetString("Info.MxmlcDone"); } - } + public string CheckSyntaxDone => TextHelper.GetString("Info.MxmlcDone"); [DisplayName("Check Syntax On Save")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.CheckSyntaxOnSave"), DefaultValue(DEFAULT_CHECKSYNTAX)] public bool CheckSyntaxOnSave { - get { return checkSyntaxOnSave; } - set { checkSyntaxOnSave = value; } + get => checkSyntaxOnSave; + set => checkSyntaxOnSave = value; } [DisplayName("User Classpath")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.UserClasspath"), DefaultValue(DEFAULT_AS3LIBRARY)] public string[] UserClasspath { - get { return userClasspath; } + get => userClasspath; set { userClasspath = value; @@ -110,20 +96,18 @@ public string[] UserClasspath [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS3Context.Description.FlexSDK")] public InstalledSDK[] InstalledSDKs { - get { return installedSDKs; } + get => installedSDKs; set { installedSDKs = value; FireChanged(); - if (OnInstalledSDKsChanged != null) OnInstalledSDKsChanged(); + OnInstalledSDKsChanged?.Invoke(); } } public InstalledSDK GetDefaultSDK() { - if (installedSDKs == null || installedSDKs.Length == 0) - return InstalledSDK.INVALID_SDK; - + if (installedSDKs.IsNullOrEmpty()) return InstalledSDK.INVALID_SDK; foreach (InstalledSDK sdk in installedSDKs) if (sdk.IsValid) return sdk; return InstalledSDK.INVALID_SDK; @@ -133,73 +117,73 @@ public InstalledSDK GetDefaultSDK() [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.CompletionEnabled"), DefaultValue(DEFAULT_COMPLETIONENABLED)] public bool CompletionEnabled { - get { return completionEnabled; } - set { completionEnabled = value; } + get => completionEnabled; + set => completionEnabled = value; } [DisplayName("Generate Imports")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.GenerateImports"), DefaultValue(DEFAULT_GENERATEIMPORTS)] public bool GenerateImports { - get { return generateImports; } - set { generateImports = value; } + get => generateImports; + set => generateImports = value; } [DisplayName("List All Types In Completion")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.CompletionListAllTypes"), DefaultValue(DEFAULT_LISTALL)] public bool CompletionListAllTypes { - get { return completionListAllTypes; } - set { completionListAllTypes = value; } + get => completionListAllTypes; + set => completionListAllTypes = value; } [DisplayName("Show Qualified Types In Completion")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.CompletionShowQualifiedTypes"), DefaultValue(DEFAULT_QUALIFY)] public bool CompletionShowQualifiedTypes { - get { return completionShowQualifiedTypes; } - set { completionShowQualifiedTypes = value; } + get => completionShowQualifiedTypes; + set => completionShowQualifiedTypes = value; } [DisplayName("Lazy Classpath Exploration")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.LazyClasspathExploration"), DefaultValue(DEFAULT_LAZYMODE)] public bool LazyClasspathExploration { - get { return lazyClasspathExploration; } - set { lazyClasspathExploration = value; } + get => lazyClasspathExploration; + set => lazyClasspathExploration = value; } [DisplayName("Play After Build")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.PlayAfterBuild"), DefaultValue(DEFAULT_PLAY)] public bool PlayAfterBuild { - get { return playAfterBuild; } - set { playAfterBuild = value; } + get => playAfterBuild; + set => playAfterBuild = value; } [DisplayName("Fix Package Automatically")] [LocalizedCategory("ASCompletion.Category.Common"), LocalizedDescription("ASCompletion.Description.FixPackageAutomatically"), DefaultValue(DEFAULT_FIXPACKAGEAUTOMATICALLY)] public bool FixPackageAutomatically { - get { return fixPackageAutomatically; } - set { fixPackageAutomatically = value; } + get => fixPackageAutomatically; + set => fixPackageAutomatically = value; } #endregion #region AS3 specific members - const string DEFAULT_FLASHVERSION = "10.1"; + const string DEFAULT_FLASHVERSION = "14.0"; - private string flashVersion = DEFAULT_FLASHVERSION; - private string as3ClassPath; - private string[] as3FileTypes; + string flashVersion = DEFAULT_FLASHVERSION; + string as3ClassPath; + string[] as3FileTypes; [DisplayName("Default Flash Version")] [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS3Context.Description.DefaultFlashVersion"), DefaultValue(DEFAULT_FLASHVERSION)] public string DefaultFlashVersion { - get { return flashVersion ?? DEFAULT_FLASHVERSION; } + get => flashVersion ?? DEFAULT_FLASHVERSION; set { if (value == flashVersion) return; @@ -210,10 +194,10 @@ public string DefaultFlashVersion [DisplayName("AS3 Classpath")] [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS3Context.Description.AS3Classpath"), DefaultValue(DEFAULT_AS3LIBRARY)] - [Editor(typeof(FolderNameEditor), typeof(UITypeEditor))] + [Editor(typeof(VistaFolderNameEditor), typeof(UITypeEditor))] public string AS3ClassPath { - get { return as3ClassPath; } + get => as3ClassPath; set { if (value == as3ClassPath) return; @@ -226,7 +210,7 @@ public string AS3ClassPath [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("AS3Context.Description.AS3FileTypes")] public string[] AS3FileTypes { - get { return as3FileTypes; } + get => as3FileTypes; set { if (value == as3FileTypes) return; @@ -239,23 +223,23 @@ public string[] AS3FileTypes #region Profiler settings const int DEFAULT_PROFILER_TIMEOUT = 30; - private int profilerTimeout; - private string[] customProfilers; + int profilerTimeout; + string[] customProfilers; [DisplayName("Profiler Timeout")] [LocalizedCategory("AS3Context.Category.Profiler"), LocalizedDescription("AS3Context.Description.ProfilerTimeout"), DefaultValue(DEFAULT_PROFILER_TIMEOUT)] public int ProfilerTimeout { - get { return profilerTimeout; } - set { profilerTimeout = Math.Max(5, value); } + get => profilerTimeout; + set => profilerTimeout = Math.Max(5, value); } [DisplayName("Custom Profilers")] [LocalizedCategory("AS3Context.Category.Profiler"), LocalizedDescription("AS3Context.Description.CustomProfilers")] public string[] CustomProfilers { - get { return customProfilers; } - set { customProfilers = value; } + get => customProfilers; + set => customProfilers = value; } #endregion @@ -265,39 +249,39 @@ public string[] CustomProfilers const bool DEFAULT_VERBOSEFDB = false; const bool DEFAULT_DISABLELIVECHECKING = false; - private bool disableFDB; - private bool verboseFDB; - private bool disableLiveChecking; + bool disableFDB; + bool verboseFDB; + bool disableLiveChecking; [DisplayName("Disable Flex Debugger Hosting")] [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("ASCompletion.Description.DisableFDB"), DefaultValue(DEFAULT_DISABLEFDB)] public bool DisableFDB { - get { return disableFDB; } - set { disableFDB = value; } + get => disableFDB; + set => disableFDB = value; } [DisplayName("Verbose Flex Debugger Output")] [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("ASCompletion.Description.VerboseFDB"), DefaultValue(DEFAULT_VERBOSEFDB)] public bool VerboseFDB { - get { return verboseFDB; } - set { verboseFDB = value; } + get => verboseFDB; + set => verboseFDB = value; } [DisplayName("Disable Live Syntax Checking")] [LocalizedCategory("ASCompletion.Category.Language"), LocalizedDescription("ASCompletion.Description.DisableLiveSyntaxChecking"), DefaultValue(DEFAULT_DISABLELIVECHECKING)] public bool DisableLiveChecking { - get { return disableLiveChecking; } - set { disableLiveChecking = value; } + get => disableLiveChecking; + set => disableLiveChecking = value; } #endregion - private void FireChanged() - { - if (OnClasspathChanged != null) OnClasspathChanged(); - } + void FireChanged() => OnClasspathChanged?.Invoke(); + + [Browsable(false)] + public string AddSpaceAfter { get; set; } } } diff --git a/External/Plugins/AS3Context/AbcConverter.cs b/External/Plugins/AS3Context/AbcConverter.cs index 324a69166e..fedca48311 100644 --- a/External/Plugins/AS3Context/AbcConverter.cs +++ b/External/Plugins/AS3Context/AbcConverter.cs @@ -2,76 +2,63 @@ using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Text; using System.Text.RegularExpressions; using System.Xml; using ASCompletion.Context; using ASCompletion.Model; +using PluginCore; using SwfOp; using SwfOp.Data; - namespace AS3Context { #region AbcConverter class: ABC model builder public class AbcConverter { - static public List ExcludedASDocs = getDefaultExcludedASDocs(); + public static List ExcludedASDocs = new() {"helpid", "keyword"}; - static public Regex reSafeChars = new Regex("[*\\:" + Regex.Escape(new String(Path.GetInvalidPathChars())) + "]", RegexOptions.Compiled); - static private Regex reDocFile = new Regex("[/\\\\]([-_.$a-z0-9]+)\\.xml", RegexOptions.IgnoreCase | RegexOptions.Compiled); + public static Regex reSafeChars = new Regex("[*\\:" + Regex.Escape(new string(Path.GetInvalidPathChars())) + "]", RegexOptions.Compiled); + static readonly Regex reDocFile = new Regex("[/\\\\]([-_.$a-z0-9]+)\\.xml", RegexOptions.IgnoreCase | RegexOptions.Compiled); - static public Dictionary> Docs = new Dictionary>(); + public static Dictionary> Docs = new Dictionary>(); - private static Dictionary genericTypes; - private static Dictionary imports; - private static Dictionary conflicts; - private static bool inSWF; - private static Dictionary thisDocs; - private static string docPath; - - /// - private static List getDefaultExcludedASDocs() - { - List list = new List(); - list.Add("helpid"); - list.Add("keyword"); - return list; - } + static Dictionary genericTypes; + static Dictionary imports; + static Dictionary conflicts; + static bool inSWF; + static Dictionary thisDocs; + static string docPath; /// /// Extract documentation from XML included in ASDocs-enriched SWCs /// - /// - private static void ParseDocumentation(ContentParser parser) + static void ParseDocumentation(ContentParser parser) { if (parser.Catalog != null) { - MxmlFilter.AddCatalog(parser.Filename, parser.Catalog); + MxmlFilter.AddCatalogs(parser.Filename, parser.Catalog); } if (parser.Docs.Count > 0) foreach (string docFile in parser.Docs.Keys) { - if (docFile.EndsWith(".dita.xml")) + if (docFile.EndsWithOrdinal(".dita.xml")) continue; try { - Match m = reDocFile.Match(docFile); + var m = reDocFile.Match(docFile); if (!m.Success) continue; - string package = m.Groups[1].Value; - Dictionary packageDocs = Docs.ContainsKey(package) - ? Docs[package] - : new Dictionary(); - - byte[] rawDoc = parser.Docs[docFile]; - ASDocsReader dr = new ASDocsReader(rawDoc); - dr.ExcludedASDocs = ExcludedASDocs; + var package = m.Groups[1].Value; + if (!Docs.TryGetValue(package, out var packageDocs)) + packageDocs = new Dictionary(); + var rawDoc = parser.Docs[docFile]; + var dr = new ASDocsReader(rawDoc) {ExcludedASDocs = ExcludedASDocs}; dr.Parse(packageDocs); - Docs[package] = packageDocs; } - catch (Exception) + catch { } } @@ -80,7 +67,7 @@ private static void ParseDocumentation(ContentParser parser) /// /// Create virtual FileModel objects from Abc bytecode /// - /// + /// /// /// public static void Convert(ContentParser parser, PathModel path, IASContext context) @@ -91,10 +78,12 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont ParseDocumentation(parser); // extract models - Dictionary models = new Dictionary(); - FileModel privateClasses = new FileModel(Path.Combine(path.Path, "__Private.as")); - privateClasses.Version = 3; - privateClasses.Package = "private"; + var models = new Dictionary(); + var privateClasses = new FileModel(Path.Combine(path.Path, "__Private.as")) + { + Version = 3, + Package = "private" + }; genericTypes = new Dictionary(); imports = new Dictionary(); conflicts = new Dictionary(); @@ -105,8 +94,7 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont foreach (Traits trait in abc.classes) { Traits instance = trait.itraits; - if (instance == null) - continue; + if (instance is null) continue; imports.Clear(); conflicts.Clear(); @@ -115,13 +103,11 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont model.Package = reSafeChars.Replace(instance.name.uri, "_"); model.HasPackage = true; string filename = reSafeChars.Replace(trait.name.ToString(), "_").TrimEnd('$'); - filename = Path.Combine(model.Package.Replace('.', Path.DirectorySeparatorChar), filename); - model.FileName = Path.Combine(path.Path, filename); + model.FileName = Path.Combine(path.Path, model.Package.Replace('.', Path.DirectorySeparatorChar), filename); model.Version = 3; ClassModel type = new ClassModel(); - model.Classes = new List(); - model.Classes.Add(type); + model.Classes = new List {type}; type.InFile = model; type.Type = instance.name.ToTypeString(); @@ -129,27 +115,35 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont type.Flags = FlagType.Class; conflicts.Add(type.Name, type.QualifiedName); - if (instance.flags == TraitMember.Function) + if ((instance.flags & TraitFlag.Interface) > 0) type.Flags |= FlagType.Interface; + else + { + if ((instance.flags & TraitFlag.Final) > 0) + type.Flags |= FlagType.Final; + + if ((instance.flags & TraitFlag.Sealed) == 0) + type.Flags |= FlagType.Dynamic; + + } thisDocs = GetDocs(model.Package); if (thisDocs != null) { docPath = (model.Package.Length > 0 ? model.Package + ":" : "globalClassifier:") + type.Name; - if (thisDocs.ContainsKey(docPath)) + if (thisDocs.TryGetValue(docPath, out var doc)) { - ASDocItem doc = thisDocs[docPath]; - applyASDoc(doc, type); - if (doc.Meta != null) model.MetaDatas = doc.Meta; + ApplyASDoc(doc, type); + if (doc.Meta != null) type.MetaDatas = doc.Meta; } if (model.Package.Length == 0) docPath = type.Name; } - if (instance.baseName.uri == model.Package) - type.ExtendsType = ImportType(instance.baseName.localName); - else type.ExtendsType = ImportType(instance.baseName); + type.ExtendsType = instance.baseName.uri == model.Package + ? ImportType(instance.baseName.localName) + : ImportType(instance.baseName); - if (instance.interfaces != null && instance.interfaces.Length > 0) + if (!instance.interfaces.IsNullOrEmpty()) { type.Implements = new List(); foreach (QName name in instance.interfaces) @@ -168,22 +162,22 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont type.Access = Visibility.Private; type.Namespace = "private"; string genType = type.Name; - if (type.Name.IndexOf("$") > 0) + if (type.Name.IndexOf('$') > 0) { string[] itype = type.Name.Split('$'); genType = itype[0]; type.Name = itype[0] + "$" + itype[1]; type.IndexType = itype[1]; } - if (genericTypes.ContainsKey(genType)) + if (genericTypes.TryGetValue(genType, out var inFile)) { model.Classes.Clear(); - type.InFile = genericTypes[genType]; + type.InFile = inFile; genericTypes[genType].Classes.Add(type); } else genericTypes[genType] = model; } - else if (type.Name.StartsWith("_")) + else if (type.Name.StartsWith('_') && string.IsNullOrEmpty(model.Package)) { type.Access = Visibility.Private; type.Namespace = "private"; @@ -201,7 +195,7 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont { // TODO properly support interface multiple inheritance type.ExtendsType = null; - if (type.Implements != null && type.Implements.Count > 0) + if (!type.Implements.IsNullOrEmpty()) { type.ExtendsType = type.Implements[0]; type.Implements.RemoveAt(0); @@ -230,8 +224,6 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont type.Members.Merge(result); type.Constructor = ctor.Name; } - result = null; - temp = null; } else type.Constructor = type.Name; @@ -249,37 +241,31 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont } // packages - if (abc.scripts == null) - continue; - foreach (Traits trait in abc.scripts) + if (abc.scripts is null) continue; + foreach (var trait in abc.scripts) { FileModel model = null; - foreach (MemberInfo info in trait.members) + foreach (var info in trait.members) { - if (info.kind == TraitMember.Class) - continue; - - MemberModel member = GetMember(info, 0); - if (member == null) continue; - - if (model == null || model.Package != info.name.uri) + if (info.kind == TraitMember.Class) continue; + var member = GetMember(info, 0); + if (member is null) continue; + if (model is null || model.Package != info.name.uri) { AddImports(model, imports); - - string package = info.name.uri ?? ""; - string filename = package.Length > 0 ? "package.as" : "toplevel.as"; - filename = Path.Combine(package.Replace('.', Path.DirectorySeparatorChar), filename); - filename = Path.Combine(path.Path, filename); - if (models.ContainsKey(filename)) - model = models[filename]; - else + var package = info.name.uri ?? ""; + var filename = package.Length > 0 ? "package.as" : "toplevel.as"; + filename = Path.Combine(path.Path, package.Replace('.', Path.DirectorySeparatorChar), filename); + if (!models.TryGetValue(filename, out model)) { - model = new FileModel(""); - model.Context = context; - model.Package = package; - model.HasPackage = true; - model.FileName = filename; - model.Version = 3; + model = new FileModel + { + Context = context, + Package = package, + HasPackage = true, + FileName = filename, + Version = 3 + }; models[filename] = model; } } @@ -289,20 +275,17 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont { docPath = "globalOperation:" + (model.Package.Length > 0 ? model.Package + ":" : "") + member.Name; - if (member.Access == Visibility.Public && !String.IsNullOrEmpty(member.Namespace) + if (member.Access == Visibility.Public && !string.IsNullOrEmpty(member.Namespace) && member.Namespace != "public") docPath += member.Namespace + ":"; if ((member.Flags & FlagType.Setter) > 0) docPath += ":set"; else if ((member.Flags & FlagType.Getter) > 0) docPath += ":get"; - - if (thisDocs.ContainsKey(docPath)) applyASDoc(thisDocs[docPath], member); + if (thisDocs.TryGetValue(docPath, out var doc)) ApplyASDoc(doc, member); } - member.InFile = model; member.IsPackageLevel = true; model.Members.Add(member); } - AddImports(model, imports); } } @@ -329,99 +312,82 @@ public static void Convert(ContentParser parser, PathModel path, IASContext cont /// /// old name: setDoc() /// - private static void applyASDoc(ASDocItem doc, MemberModel model) + static void ApplyASDoc(ASDocItem doc, MemberModel model) { model.Comments = doc.LongDesc; - - if (doc.IsFinal) - model.Flags |= FlagType.Final; - - if (doc.IsDynamic && (model is ClassModel)) - model.Flags |= FlagType.Dynamic; - - if (doc.Value != null) - model.Value = doc.Value; - + if (doc.IsFinal) model.Flags |= FlagType.Final; + if (doc.IsDynamic && model is ClassModel) model.Flags |= FlagType.Dynamic; + if (doc.Value != null) model.Value = doc.Value; // TODO Extract features in comments - applyTypeComment(doc, model); - applyTypeCommentToParams(doc, model); + ApplyTypeComment(doc, model); + ApplyTypeCommentToParams(doc, model); } - private static void applyTypeComment(ASDocItem doc, MemberModel model) + static void ApplyTypeComment(ASDocItem doc, MemberModel model) { - if (doc == null || model ==null) - return; - + if (doc is null || model is null) return; ASFileParserUtils.ParseTypeDefinitionInto(doc.ApiType, model, true, true); } - private static void applyTypeCommentToParams(ASDocItem doc, MemberModel model) + static void ApplyTypeCommentToParams(ASDocItem doc, MemberModel model) { - if (doc == null || model == null || model.Parameters == null) - return; - - foreach (MemberModel param in model.Parameters) - if (doc.ParamTypes != null && doc.ParamTypes.ContainsKey(param.Name)) - ASFileParserUtils.ParseTypeDefinitionInto(doc.ParamTypes[param.Name], param, true, true); + if (doc is null || model?.Parameters is null) return; + foreach (var param in model.Parameters) + if (doc.ParamTypes != null && doc.ParamTypes.TryGetValue(param.Name, out var typeDefinition)) + ASFileParserUtils.ParseTypeDefinitionInto(typeDefinition, param, true, true); } - private static void CustomFixes(string path, Dictionary models) + static void CustomFixes(string path, IDictionary models) { - string file = Path.GetFileName(path); - if (file == "playerglobal.swc" || file == "airglobal.swc") + var file = Path.GetFileName(path); + if (file != "playerglobal.swc" && file != "airglobal.swc") return; + var mathPath = Path.Combine(path, "Math"); + if (models.TryGetValue(mathPath, out var model)) { - string mathPath = Path.Combine(path, "Math"); - if (models.ContainsKey(mathPath)) + var @class = model.GetPublicClass(); + foreach (var member in @class.Members) { - ClassModel mathModel = models[mathPath].GetPublicClass(); - foreach (MemberModel member in mathModel.Members) + if (!member.Parameters.IsNullOrEmpty() && member.Parameters[0].Name == "x") { - if (member.Parameters != null && member.Parameters.Count > 0 && member.Parameters[0].Name == "x") + string n = member.Name; + if (member.Parameters.Count > 1) { - string n = member.Name; - if (member.Parameters.Count > 1) - { - if (n == "atan2") member.Parameters.Reverse(); - else if (n == "min" || n == "max") { member.Parameters[0].Name = "val1"; member.Parameters[1].Name = "val2"; } - else if (n == "pow") { member.Parameters[0].Name = "base"; member.Parameters[1].Name = "pow"; } - } - else if (n == "sin" || n == "cos" || n == "tan") member.Parameters[0].Name = "angleRadians"; - else member.Parameters[0].Name = "val"; + if (n == "atan2") member.Parameters.Reverse(); + else if (n == "min" || n == "max") { member.Parameters[0].Name = "val1"; member.Parameters[1].Name = "val2"; } + else if (n == "pow") { member.Parameters[0].Name = "base"; member.Parameters[1].Name = "pow"; } } + else if (n == "sin" || n == "cos" || n == "tan") member.Parameters[0].Name = "angleRadians"; + else member.Parameters[0].Name = "val"; } } - string objPath = Path.Combine(path, "Object"); - if (models.ContainsKey(objPath)) + } + var objPath = Path.Combine(path, "Object"); + if (models.TryGetValue(objPath, out model)) + { + var @class = model.GetPublicClass(); + if (!@class.Members.Contains("prototype")) { - ClassModel objModel = models[objPath].GetPublicClass(); - if (objModel.Members.Search("prototype", 0, 0) == null) - { - MemberModel proto = new MemberModel("prototype", "Object", FlagType.Dynamic | FlagType.Variable, Visibility.Public); - objModel.Members.Add(proto); - } + @class.Members.Add(new MemberModel("prototype", "Object", FlagType.Dynamic | FlagType.Variable, Visibility.Public)); } } } - private static void AddImports(FileModel model, Dictionary imports) + static void AddImports(FileModel model, Dictionary imports) { - if (model != null) - { - foreach (string import in imports.Keys) - model.Imports.Add(new MemberModel(imports[import], import, FlagType.Import, 0)); - - imports.Clear(); - } + if (model is null) return; + foreach (var pair in imports) + model.Imports.Add(new MemberModel(pair.Value, pair.Key, FlagType.Import, 0)); + imports.Clear(); } - private static Dictionary GetDocs(string package) + static Dictionary GetDocs(string package) { - string docPackage = package == "" ? "__Global__" : package; - if (Docs.ContainsKey(docPackage)) return Docs[docPackage]; - else return null; + var docPackage = package == "" ? "__Global__" : package; + Docs.TryGetValue(docPackage, out var result); + return result; } - private static MemberList GetMembers(List abcMembers, FlagType baseFlags, QName instName) + static MemberList GetMembers(IEnumerable abcMembers, FlagType baseFlags, QName instName) { MemberList list = new MemberList(); string package = instName.uri; @@ -430,16 +396,13 @@ private static MemberList GetMembers(List abcMembers, FlagType baseF foreach (MemberInfo info in abcMembers) { MemberModel member = GetMember(info, baseFlags); - if (member == null) continue; + if (member is null) continue; string uri = info.name.uri ?? ""; if (uri.Length > 0) { - if (uri == "private" || package == "private") - { - continue; - } - else if (uri == protect) + if (uri == "private" || package == "private") continue; + if (uri == protect) { member.Access = Visibility.Protected; member.Namespace = "protected"; @@ -482,41 +445,64 @@ private static MemberList GetMembers(List abcMembers, FlagType baseF return list; } - private static MemberModel GetMember(MemberInfo info, FlagType baseFlags) + static MemberModel GetMember(MemberInfo info, FlagType baseFlags) { - MemberModel member = new MemberModel(); - member.Name = info.name.localName; - member.Flags = baseFlags; - member.Access = Visibility.Public; - member.Namespace = "public"; + var member = new MemberModel + { + Name = info.name.localName, + Flags = baseFlags, + Access = Visibility.Public, + Namespace = "public" + }; + if (!info.metadata.IsNullOrEmpty()) + { + var metadatas = member.MetaDatas; + foreach (var metaInfo in info.metadata) + { + if (metaInfo.name == "__go_to_definition_help") continue; + var meta = new ASMetaData(metaInfo.name); + var rawParams = new StringBuilder(); + meta.Params = new Dictionary(metaInfo.Count); + foreach (var entry in metaInfo) + { + if (entry.Length != 2) continue; + meta.Params[entry[0]] = entry[1]; + if (rawParams.Length > 0) rawParams.Append(","); + rawParams.Append(entry[0] + "=\"" + entry[1] + "\""); + } + meta.RawParams = rawParams.ToString(); - if (info is SlotInfo) + metadatas ??= new List(info.metadata.Count); + metadatas.Add(meta); + } + member.MetaDatas = metadatas; + } + + if (info is SlotInfo slot) { - SlotInfo slot = info as SlotInfo; member.Flags |= FlagType.Variable; if (slot.kind == TraitMember.Const) member.Flags |= FlagType.Constant; - if (slot.value is Namespace) + if (slot.value is Namespace ns) { member.Flags |= FlagType.Namespace; - member.Value = '"' + (slot.value as Namespace).uri + '"'; + member.Value = '"' + ns.uri + '"'; } member.Type = ImportType(slot.type); } - else if (info is MethodInfo) + else if (info is MethodInfo method) { - switch (info.kind) + member.Flags |= method.kind switch { - case TraitMember.Setter: member.Flags |= FlagType.Setter; break; - case TraitMember.Getter: member.Flags |= FlagType.Getter; break; - default: member.Flags |= FlagType.Function; break; - } - MethodInfo method = info as MethodInfo; + TraitMember.Setter => FlagType.Setter, + TraitMember.Getter => FlagType.Getter, + _ => FlagType.Function, + }; QName type = method.returnType; member.Type = ImportType(type); member.Parameters = new List(); int n = method.paramTypes.Length; - int defaultValues = (method.optionalValues != null) ? n - method.optionalValues.Length : n; + int defaultValues = n - method.optionalValues?.Length ?? n; for (int i = 0; i < n; i++) { MemberModel param = new MemberModel(); @@ -536,47 +522,37 @@ private static MemberModel GetMember(MemberInfo info, FlagType baseFlags) member.Parameters.Add(param); } } - else - { - member = null; - } - + else member = null; return member; } - private static void GetMemberDoc(MemberModel member) + static void GetMemberDoc(MemberModel member) { string dPath = docPath + ":"; - if (member.Access == Visibility.Public && !String.IsNullOrEmpty(member.Namespace) + if (member.Access == Visibility.Public && !string.IsNullOrEmpty(member.Namespace) && member.Namespace != "public") dPath += member.Namespace + ":"; dPath += member.Name; if ((member.Flags & FlagType.Getter) > 0) dPath += ":get"; else if ((member.Flags & FlagType.Setter) > 0) dPath += ":set"; - - if (thisDocs.ContainsKey(dPath)) applyASDoc(thisDocs[dPath], member); + if (thisDocs.TryGetValue(dPath, out var doc)) ApplyASDoc(doc, member); } - private static string ImportType(QName type) - { - if (type == null) return "*"; - else return ImportType(type.ToTypeString()); - } + static string ImportType(QName type) => type is null ? "*" : ImportType(type.ToTypeString()); - private static string ImportType(string qname) + static string ImportType(string qname) { - if (qname == null) return "*"; + if (qname is null) return "*"; int p = qname.LastIndexOf('.'); int q = qname.LastIndexOf('<'); if (q > 0) { p = qname.IndexOf('>', q); if (p <= q) return qname; - else - return qname.Substring(0, q + 1) + ImportType(qname.Substring(q + 1, p - q - 1)) + qname.Substring(p); + return qname.Substring(0, q + 1) + ImportType(qname.Substring(q + 1, p - q - 1)) + qname.Substring(p); } if (p < 0) return qname; - if (imports.ContainsKey(qname)) return imports[qname]; + if (imports.TryGetValue(qname, out var import)) return import; string cname = qname.Substring(p + 1); if (!conflicts.ContainsKey(cname)) conflicts.Add(cname, qname); else if (conflicts[cname] != qname) @@ -585,13 +561,16 @@ private static string ImportType(string qname) return cname; } - private static void SetDefaultValue(MemberModel member, object value) + static void SetDefaultValue(MemberModel member, object value) { - if (value == null) member.Value = "null"; - else if (value is string && value.ToString() != "undefined") member.Value = '"' + value.ToString() + '"'; - else if (value is bool) member.Value = value.ToString().ToLower(); - else if (value is double) member.Value = ((double)value).ToString(CultureInfo.InvariantCulture.NumberFormat); - else member.Value = value.ToString(); + member.Value = value switch + { + null => "null", + string _ when value.ToString() != "undefined" => '"' + value.ToString() + '"', + bool _ => value.ToString().ToLower(), + double d => d.ToString(CultureInfo.InvariantCulture.NumberFormat), + _ => value.ToString(), + }; } } @@ -601,14 +580,16 @@ private static void SetDefaultValue(MemberModel member, object value) public class ASDocItem { - public bool IsFinal = false; - public bool IsDynamic = false; + public bool IsFinal; + public bool IsDynamic; + public bool IsStatic; - public string ShortDesc = null; - public string LongDesc = null; - public string Returns = null; - public string Value = null; - public string ApiType = null; + public string ShortDesc; + public string LongDesc; + public string Returns; + public string Value; + public string ApiType; + public string DeclType; public List Meta; public Dictionary Params = new Dictionary(); @@ -622,8 +603,8 @@ public class ASDocItem class ASDocsReader : XmlTextReader { - public List ExcludedASDocs = null; - private Dictionary docs; + public List ExcludedASDocs; + Dictionary docs; public ASDocsReader(byte[] raw) @@ -646,27 +627,22 @@ public void Parse(Dictionary packageDocs) //--------------------------- - // PRIMARY + // PRIMARY //--------------------------- - private void ReadDeclaration() + void ReadDeclaration(string declType) { - if (IsEmptyElement) - return; - - if (this.ExcludedASDocs == null) - this.ExcludedASDocs = new List(); - - ASDocItem doc = new ASDocItem(); - string id = GetAttribute("id"); - + if (IsEmptyElement) return; + ExcludedASDocs ??= new List(); + var doc = new ASDocItem {DeclType = declType}; + var id = GetAttribute("id"); if (id != null) { // type doubled in doc: "flash.utils:IDataOutput:flash.utils:IDataOutput:writeDouble" int colon = id.IndexOf(':') + 1; if (colon > 0) { - int dup = id.IndexOf(id.Substring(0, colon), colon); + int dup = id.IndexOfOrdinal(id.Substring(0, colon), colon); if (dup > 0) id = id.Substring(dup); } doc.ApiType = id; @@ -682,47 +658,43 @@ private void ReadDeclaration() if (id != null) { - if (doc.ApiType == "String" && doc.Value != null && !doc.Value.StartsWith("\"")) + if (doc.ApiType == "String" && doc.Value != null && !doc.Value.StartsWith('"')) doc.Value = "\"" + doc.Value + "\""; - if (doc.LongDesc == null) - doc.LongDesc = ""; + doc.LongDesc ??= ""; - if (doc.ShortDesc == null) - doc.ShortDesc = doc.LongDesc; - else - doc.LongDesc = doc.LongDesc.Trim(); + if (doc.ShortDesc is null) doc.ShortDesc = doc.LongDesc; + else doc.LongDesc = doc.LongDesc.Trim(); if (doc.LongDesc.Length == 0 && doc.ShortDesc.Length > 0) doc.LongDesc = doc.ShortDesc; - if (!this.ExcludedASDocs.Contains("param") && doc.Params != null) + if (!ExcludedASDocs.Contains("param") && doc.Params != null) foreach (string name in doc.Params.Keys) doc.LongDesc += "\n@param\t" + name + "\t" + doc.Params[name].Trim(); - if (!this.ExcludedASDocs.Contains("return") && doc.Returns != null) + if (!ExcludedASDocs.Contains("return") && doc.Returns != null) doc.LongDesc += "\n@return\t" + doc.Returns.Trim(); if (doc.ExtraAsDocs != null) - foreach (KeyValuePair extraASDoc in doc.ExtraAsDocs) - if (!this.ExcludedASDocs.Contains(extraASDoc.Key)) + foreach (var extraASDoc in doc.ExtraAsDocs) + if (!ExcludedASDocs.Contains(extraASDoc.Key)) doc.LongDesc += "\n@" + extraASDoc.Key + "\t" + extraASDoc.Value; - if (doc.ShortDesc.Length > 0 || doc.LongDesc.Length > 0) + // keep definitions including either documentation or static values + if (doc.ShortDesc.Length > 0 || doc.LongDesc.Length > 0 + || (doc.IsStatic && doc.Value != null && doc.DeclType == "apiValue")) docs[id] = doc; } } - private void ProcessDeclarationNodes(ASDocItem doc) + void ProcessDeclarationNodes(ASDocItem doc) { - if (NodeType != XmlNodeType.Element) - return; - + if (NodeType != XmlNodeType.Element) return; switch (Name) { case "apiName": break; // TODO validate event name case "apiInheritDoc": break; // TODO link inherited doc? - case "apiDetail": case "related-links": SkipContents(); break; @@ -734,7 +706,7 @@ private void ProcessDeclarationNodes(ASDocItem doc) case "apiValue": case "apiOperation": case "apiConstructor": - ReadDeclaration(); + ReadDeclaration(Name); break; case "shortdesc": doc.ShortDesc = ReadValue(); break; @@ -747,6 +719,8 @@ private void ProcessDeclarationNodes(ASDocItem doc) case "adobeApiEvent": ReadEventMeta(doc); break; case "apiFinal": doc.IsFinal = true; SkipContents(); break; + case "apiStatic": + doc.IsStatic = true; break; case "apiParam": ReadParamDesc(doc); break; case "apiReturn": ReadReturnsDesc(doc); break; @@ -761,10 +735,10 @@ private void ProcessDeclarationNodes(ASDocItem doc) //--------------------------- - // COMMONS + // COMMONS //--------------------------- - private void SkipContents() + void SkipContents() { if (IsEmptyElement) return; @@ -775,7 +749,7 @@ private void SkipContents() Read(); } - private string ReadValue() + string ReadValue() { if (IsEmptyElement) { @@ -789,11 +763,10 @@ private string ReadValue() string prefix = ""; string postfix = ""; string eon = Name; - string lcName; // name in lower case ReadStartElement(); while (Name != eon) { - lcName = Name.ToLower(); + var lcName = Name.ToLower(); // name in lower case if (lcName == "codeblock" || lcName == "listing") { if (NodeType == XmlNodeType.Element) @@ -830,10 +803,10 @@ private string ReadValue() //--------------------------- - // apiClassifierDetail + // apiClassifierDetail //--------------------------- - private void ReadApiClassifierDetail(ASDocItem doc) + void ReadApiClassifierDetail(ASDocItem doc) { doc.LongDesc = ""; @@ -852,23 +825,23 @@ private void ReadApiClassifierDetail(ASDocItem doc) break; case "apiDesc": - doc.LongDesc += this.ReadInnerXml() +"\n"; + doc.LongDesc += ReadInnerXml() +"\n"; // Read(); break; case "example": - doc.LongDesc += "\nEXAMPLE: \n\n" + this.ReadInnerXml() +"\n"; + doc.LongDesc += "\nEXAMPLE: \n\n" + ReadInnerXml() +"\n"; // Read(); break; default: - this.ReadInnerXml(); + ReadInnerXml(); break; } } } - private void ReadApiClassifierDef(ASDocItem doc) + void ReadApiClassifierDef(ASDocItem doc) { if (IsEmptyElement) return; @@ -888,31 +861,31 @@ private void ReadApiClassifierDef(ASDocItem doc) //--------------------------- - // prolog + // prolog //--------------------------- /// /// --- /// Example: /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// --- + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// --- /// /// - private void ReadProlog(ASDocItem doc) + void ReadProlog(ASDocItem doc) { if (IsEmptyElement) return; @@ -930,7 +903,7 @@ private void ReadProlog(ASDocItem doc) } } - private void ReadPrologMetadata(ASDocItem doc) + void ReadPrologMetadata(ASDocItem doc) { if (IsEmptyElement) return; @@ -941,23 +914,25 @@ private void ReadPrologMetadata(ASDocItem doc) { if (Name == "apiVersion") ReadPrologMetadataApiVersion(doc); - + else if (Name == "styles") + ReadPrologMetadataStyles(doc); + else if (Name == "DefaultProperty") + ReadPrologMetadataDefaultProperty(doc); Read(); } } - private void ReadPrologMetadataApiVersion(ASDocItem doc) + void ReadPrologMetadataApiVersion(ASDocItem doc) { if (IsEmptyElement) return; - string asdocKey; - string asdocVal; - string eon = Name; ReadStartElement(); while (Name != eon) { + string asdocVal; + string asdocKey; if (Name == "apiLanguage") { string sVers = GetAttribute("version"); @@ -994,19 +969,48 @@ private void ReadPrologMetadataApiVersion(ASDocItem doc) } } - private void ReadPrologCustoms(ASDocItem doc, string terminationNode) + void ReadPrologMetadataStyles(ASDocItem doc) { if (IsEmptyElement) return; - string asdocKey; - string asdocVal; + string eon = Name; + ReadStartElement(); + while (Name != eon) + { + if (Name == "style") + ReadStyleMeta(doc); + Read(); + } + } + + void ReadPrologMetadataDefaultProperty(ASDocItem doc) + { + ASMetaData meta = new ASMetaData("DefaultProperty"); + meta.Kind = ASMetaKind.DefaultProperty; + meta.Comments = ""; + + meta.Params = new Dictionary(); + + string defValue = GetAttribute("name"); + meta.Params["default"] = defValue; + + meta.RawParams = $"\"{defValue}\""; + + doc.Meta ??= new List(); + doc.Meta.Add(meta); + } + + void ReadPrologCustoms(ASDocItem doc, string terminationNode) + { + if (IsEmptyElement) + return; string eon = terminationNode; ReadStartElement(); while (!(Name == eon && NodeType == XmlNodeType.EndElement)) { - asdocKey = this.Name; + var asdocKey = Name; /* if (asdocKey == "maelexample") @@ -1017,7 +1021,7 @@ private void ReadPrologCustoms(ASDocItem doc, string terminationNode) else { */ - asdocVal = this.ReadInnerXml(); + var asdocVal = ReadInnerXml(); // } doc.ExtraAsDocs.Add(new KeyValuePair(asdocKey, asdocVal)); @@ -1026,30 +1030,20 @@ private void ReadPrologCustoms(ASDocItem doc, string terminationNode) //--------------------------- - // apiType + // apiType //--------------------------- - private void ReadApiType(ASDocItem doc) - { - SetApiType(doc, GetAttribute("value")); - } - - private void ReadApiTypeAsClassifier(ASDocItem doc) - { - SetApiType(doc, ReadValue()); - } - - private void SetApiType(ASDocItem doc, string apiType) - { - doc.ApiType = apiType == "any" ? "*" : apiType; - } + void ReadApiType(ASDocItem doc) => SetApiType(doc, GetAttribute("value")); + void ReadApiTypeAsClassifier(ASDocItem doc) => SetApiType(doc, ReadValue()); + static void SetApiType(ASDocItem doc, string apiType) => doc.ApiType = apiType == "any" ? "*" : apiType; + //--------------------------- - // apiOperationDetail + // apiOperationDetail //--------------------------- - private void ReadParamDesc(ASDocItem doc) + void ReadParamDesc(ASDocItem doc) { if (IsEmptyElement) return; @@ -1092,7 +1086,7 @@ private void ReadParamDesc(ASDocItem doc) } } - private void ReadReturnsDesc(ASDocItem doc) + void ReadReturnsDesc(ASDocItem doc) { if (IsEmptyElement) return; @@ -1101,7 +1095,7 @@ private void ReadReturnsDesc(ASDocItem doc) ReadStartElement(); while (Name != eon) { - switch (this.Name) + switch (Name) { case "apiDesc": doc.Returns = ReadValue(); @@ -1122,17 +1116,16 @@ private void ReadReturnsDesc(ASDocItem doc) //--------------------------- - // apiException + // apiException //--------------------------- - private void ReadApiException(ASDocItem doc) + void ReadApiException(ASDocItem doc) { if (IsEmptyElement) return; string apiDesc = ""; string apiItemName = ""; - string apiOperationClassifier = ""; string eon = Name; ReadStartElement(); @@ -1149,7 +1142,7 @@ private void ReadApiException(ASDocItem doc) break; case "apiOperationClassifier": - apiOperationClassifier = ReadValue(); + ReadValue(); break; } Read(); @@ -1160,27 +1153,24 @@ private void ReadApiException(ASDocItem doc) //--------------------------- - // Meta tags + // Meta tags //--------------------------- - private void ReadExcludeMeta(ASDocItem doc) + void ReadExcludeMeta(ASDocItem doc) { if (!HasAttributes) return; - ASMetaData meta = new ASMetaData("Style"); - meta.Kind = ASMetaKind.Exclude; + ASMetaData meta = new ASMetaData("Style") {Kind = ASMetaKind.Exclude}; string sKind = GetAttribute("kind"); string sName = GetAttribute("name"); - if (doc.Meta == null) doc.Meta = new List(); - meta.Params = new Dictionary(); - meta.Params["kind"] = sKind; - meta.Params["name"] = sName; - meta.RawParams = String.Format("kind=\"{0}\", name=\"{1}\"", sKind, sName); + doc.Meta ??= new List(); + meta.Params = new Dictionary {["kind"] = sKind, ["name"] = sName}; + meta.RawParams = $"kind=\"{sKind}\", name=\"{sName}\""; doc.Meta.Add(meta); } - private void ReadStyleMeta(ASDocItem doc) + void ReadStyleMeta(ASDocItem doc) { if (IsEmptyElement || !HasAttributes) return; @@ -1190,7 +1180,7 @@ private void ReadStyleMeta(ASDocItem doc) string sName = GetAttribute("name"); string sType = GetAttribute("type"); - //string sInherit = GetAttribute("inherit"); + string sInherit = GetAttribute("inherit"); //string sFormat = GetAttribute("format"); string sEnum = GetAttribute("enumeration"); string sDefault = null; @@ -1208,12 +1198,15 @@ private void ReadStyleMeta(ASDocItem doc) Read(); } - if (doc.Meta == null) doc.Meta = new List(); + doc.Meta ??= new List(); if (sDefault != null) meta.Comments = meta.Comments.Trim() + "\n@default\t" + sDefault; - meta.Params = new Dictionary(); - meta.Params["name"] = sName; - meta.Params["type"] = sType; - meta.RawParams = String.Format("name=\"{0}\", type=\"{1}\"", sName, sType); + meta.Params = new Dictionary {["name"] = sName, ["type"] = sType}; + meta.RawParams = $"name=\"{sName}\", type=\"{sType}\""; + if (sInherit != null) + { + meta.Params["inherit"] = sInherit; + meta.RawParams += ", inherit=\"" + sInherit + "\""; + } if (sEnum != null) { meta.Params["enumeration"] = sEnum; @@ -1222,7 +1215,7 @@ private void ReadStyleMeta(ASDocItem doc) doc.Meta.Add(meta); } - private void ReadEventMeta(ASDocItem doc) + void ReadEventMeta(ASDocItem doc) { if (IsEmptyElement) return; @@ -1249,13 +1242,11 @@ private void ReadEventMeta(ASDocItem doc) Read(); } - if (doc.Meta == null) doc.Meta = new List(); - meta.Params = new Dictionary(); - meta.Params["name"] = eName; - meta.Params["type"] = eType; + doc.Meta ??= new List(); + meta.Params = new Dictionary {["name"] = eName, ["type"] = eType}; if (eFullType != null) meta.Comments = meta.Comments.Trim() + "\n@eventType\t" + eFullType.Replace(':', '.'); - meta.RawParams = String.Format("name=\"{0}\", type=\"{1}\"", eName, eType); + meta.RawParams = $"name=\"{eName}\", type=\"{eType}\""; doc.Meta.Add(meta); } } diff --git a/External/Plugins/AS3Context/Compiler/FdbWrapper.cs b/External/Plugins/AS3Context/Compiler/FdbWrapper.cs index a86d946e02..84e22c343c 100644 --- a/External/Plugins/AS3Context/Compiler/FdbWrapper.cs +++ b/External/Plugins/AS3Context/Compiler/FdbWrapper.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -using System.Text; using System.Diagnostics; -using System.Threading; using System.IO; +using System.Text; using System.Text.RegularExpressions; +using System.Threading; using PluginCore.Helpers; -using System.Collections; namespace AS3Context.Compiler { @@ -22,17 +21,18 @@ public class FdbWrapper public void Run(string projectPath, string flexSDKPath) { flexSDKPath = PathHelper.ResolvePath(flexSDKPath, projectPath); - if (flexSDKPath != null && Directory.Exists(flexSDKPath)) + if (Directory.Exists(flexSDKPath)) { if (flexSDKPath.EndsWith("bin", StringComparison.OrdinalIgnoreCase)) flexSDKPath = Path.GetDirectoryName(flexSDKPath); } else return; - Dictionary jvmConfig = JvmConfigHelper.ReadConfig(flexSDKPath); - - if (process == null || process.HasExited) + if (process is null || process.HasExited) + { + var jvmConfig = JvmConfigHelper.ReadConfig(flexSDKPath); Initialize(flexSDKPath, jvmConfig, projectPath); + } } public void PushCommand(string cmd) @@ -65,7 +65,8 @@ bool Initialize(string flexSDKPath, Dictionary jvmConfig, string { cmdQueue = new Queue(); - string fdbPath = Path.Combine(flexSDKPath, "lib\\fdb.jar"); + var fdbPath = Path.Combine(flexSDKPath, "lib\\fdb.jar"); + if (!File.Exists(fdbPath)) fdbPath = Path.Combine(flexSDKPath, "lib\\legacy\\fdb.jar"); if (!File.Exists(fdbPath)) { process = null; @@ -80,8 +81,7 @@ bool Initialize(string flexSDKPath, Dictionary jvmConfig, string process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.FileName = JvmConfigHelper.GetJavaEXE(jvmConfig); - process.StartInfo.Arguments = jvmConfig["java.args"] - + " -Dfile.encoding=UTF-8 -Dapplication.home=\"" + flexSDKPath + "\" -jar \"" + fdbPath + "\""; + process.StartInfo.Arguments = jvmConfig["java.args"] + " -Dfile.encoding=UTF-8 -Dapplication.home=\"" + flexSDKPath + "\" -jar \"" + fdbPath + "\""; process.StartInfo.WorkingDirectory = workingDir; process.StartInfo.StandardErrorEncoding = Encoding.UTF8; process.StartInfo.StandardOutputEncoding = Encoding.UTF8; @@ -103,7 +103,7 @@ void process_Exited(object sender, EventArgs e) { keepAlive = false; Cleanup(); - if (OnOutput != null) OnOutput("[FDB halted]"); + OnOutput?.Invoke("[FDB halted]"); } public void Cleanup() @@ -112,7 +112,7 @@ public void Cleanup() if (process != null && !process.HasExited && keepAlive) { keepAlive = false; - if (OnOutput != null) OnOutput("[Shutting down FDB]"); + OnOutput?.Invoke("[Shutting down FDB]"); try { if (!process.HasExited) process.Kill(); @@ -147,13 +147,13 @@ void FdbRun() running = true; WriteToPrompt("run"); Thread.Sleep(200); - if (OnStarted != null) OnStarted(null); + OnStarted?.Invoke(null); } // send commands queue else if (cmdQueue.Count > 0) WriteToPrompt(cmdQueue.Dequeue()); // default behavior else if (connected) WriteToPrompt("continue"); - else if (!connected) + else { connectedEvent.WaitOne(250, false); connectedEvent.Reset(); @@ -162,7 +162,7 @@ void FdbRun() } if (process != null && !process.HasExited) { - if (OnOutput != null) OnOutput("[Shutting down FDB]"); + OnOutput?.Invoke("[Shutting down FDB]"); try { if (!process.HasExited) process.Kill(); @@ -176,16 +176,15 @@ void ReadErrors() while (keepAlive && !process.StandardError.EndOfStream) { string line = process.StandardError.ReadLine(); - if (OnError != null) OnError(line); + OnError?.Invoke(line); } } void WriteToPrompt(string line) { interactive = false; - if (process != null) - process.StandardInput.WriteLine(line); - if (OnOutput != null) OnOutput("(fdb) "+line); + process?.StandardInput.WriteLine(line); + OnOutput?.Invoke("(fdb) "+line); } /// @@ -200,14 +199,12 @@ void ReadUntilPrompt() void ReadUntilToken(string token) { - StringBuilder output = new StringBuilder(); - Queue queue = new Queue(); - - bool keepProcessing = true; + var output = new StringBuilder(); + var queue = new Queue(); + var keepProcessing = true; while (keepProcessing && keepAlive) { - if (process == null || process.HasExited) - keepProcessing = false; + if (process is null || process.HasExited) keepProcessing = false; else { char c = (char)process.StandardOutput.Read(); @@ -234,12 +231,12 @@ void ReadUntilToken(string token) #region Understanding - static Regex reTrace = new Regex(@"^?\[trace\]", RegexOptions.Compiled); - static Regex reFault = new Regex(@"^(\[Fault\]|Fault,) ", RegexOptions.Compiled); - static Regex reLoad = new Regex(@"^\[SWF\] ", RegexOptions.Compiled); - static Regex reUnload = new Regex(@"^\[UnloadSWF\] ", RegexOptions.Compiled); - static Regex reDisconnect = new Regex(@"^Player session terminated", RegexOptions.Compiled); - static Regex reContinue = new Regex(@"'continue'", RegexOptions.Compiled); + static readonly Regex reTrace = new Regex(@"^?\[trace\]", RegexOptions.Compiled); + static readonly Regex reFault = new Regex(@"^(\[Fault\]|Fault,) ", RegexOptions.Compiled); + static readonly Regex reLoad = new Regex(@"^\[SWF\] ", RegexOptions.Compiled); + static readonly Regex reUnload = new Regex(@"^\[UnloadSWF\] ", RegexOptions.Compiled); + static readonly Regex reDisconnect = new Regex(@"^Player session terminated", RegexOptions.Compiled); + static readonly Regex reContinue = new Regex(@"'continue'", RegexOptions.Compiled); void MatchLine(string line) { @@ -254,11 +251,11 @@ void MatchLine(string line) // [trace] Hello World! else if (reTrace.IsMatch(line)) { - if (OnTrace != null) + if (OnTrace is { } onTrace) { - string trace = line.Substring(line.IndexOf(']') + 1); - if (trace.Length > 0 && Char.IsWhiteSpace(trace[0])) OnTrace(trace.Substring(1)); - else OnTrace(trace); + var trace = line.Substring(line.IndexOf(']') + 1); + if (trace.Length > 0 && char.IsWhiteSpace(trace[0])) onTrace(trace.Substring(1)); + else onTrace(trace); return; } } @@ -267,9 +264,9 @@ void MatchLine(string line) // 20 else if (reFault.IsMatch(line)) { - if (OnError != null) + if (OnError is { } onError) { - OnError(line); + onError(line); return; } } @@ -291,7 +288,7 @@ void MatchLine(string line) keepAlive = false; } - if (OnOutput != null) OnOutput(line); + OnOutput?.Invoke(line); } #endregion } diff --git a/External/Plugins/AS3Context/Compiler/FlexDebugger.cs b/External/Plugins/AS3Context/Compiler/FlexDebugger.cs index d73def73df..4f237848b3 100644 --- a/External/Plugins/AS3Context/Compiler/FlexDebugger.cs +++ b/External/Plugins/AS3Context/Compiler/FlexDebugger.cs @@ -1,11 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Text; using PluginCore; -using System.Windows.Forms; -using PluginCore.Managers; -using System.IO; using PluginCore.Localization; +using PluginCore.Managers; namespace AS3Context.Compiler { @@ -18,14 +13,14 @@ public static bool Start(string projectPath, string flex2Path, DataEvent message if (ignoreMessage) return false; try { - if (debugger != null) debugger.Cleanup(); + debugger?.Cleanup(); startMessage = message; debugger = new FdbWrapper(); - debugger.OnStarted += new LineEvent(debugger_OnStarted); - debugger.OnTrace += new LineEvent(debugger_OnTrace); - debugger.OnError += new LineEvent(debugger_OnError); + debugger.OnStarted += debugger_OnStarted; + debugger.OnTrace += debugger_OnTrace; + debugger.OnError += debugger_OnError; if (PluginMain.Settings.VerboseFDB) - debugger.OnOutput += new LineEvent(debugger_OnOutput); + debugger.OnOutput += debugger_OnOutput; debugger.Run(projectPath, flex2Path); TraceManager.AddAsync(TextHelper.GetString("Info.CapturingTracesWithFDB")); return true; @@ -50,15 +45,14 @@ public static void Stop() #endregion - static private bool ignoreMessage; - static private FdbWrapper debugger; - static private DataEvent startMessage; + static bool ignoreMessage; + static FdbWrapper debugger; + static DataEvent startMessage; static void debugger_OnStarted(string line) { - if (startMessage == null) - return; - PluginBase.RunAsync((MethodInvoker)delegate + if (startMessage is null) return; + PluginBase.RunAsync(delegate { // send message again ignoreMessage = true; @@ -68,19 +62,10 @@ static void debugger_OnStarted(string line) }); } - static void debugger_OnError(string line) - { - TraceManager.AddAsync(line, 3); - } + static void debugger_OnError(string line) => TraceManager.AddAsync(line, 3); - static void debugger_OnOutput(string line) - { - TraceManager.AddAsync(line, 1); - } + static void debugger_OnOutput(string line) => TraceManager.AddAsync(line, 1); - static void debugger_OnTrace(string line) - { - TraceManager.AddAsync(line, 1); - } + static void debugger_OnTrace(string line) => TraceManager.AddAsync(line, 1); } } diff --git a/External/Plugins/AS3Context/Compiler/FlexShells.cs b/External/Plugins/AS3Context/Compiler/FlexShells.cs index 9378f818e5..58c8e7527c 100644 --- a/External/Plugins/AS3Context/Compiler/FlexShells.cs +++ b/External/Plugins/AS3Context/Compiler/FlexShells.cs @@ -1,122 +1,101 @@ using System; -using System.Windows.Forms; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; using System.IO; -using System.Text; +using System.Reflection; using System.Text.RegularExpressions; using System.Threading; -using System.Diagnostics; -using System.Timers; -using System.Runtime.InteropServices; +using System.Windows.Forms; +using ASCompletion.Context; +using ASCompletion.Model; using PluginCore; using PluginCore.Helpers; -using ASCompletion.Context; +using PluginCore.Localization; using PluginCore.Managers; using PluginCore.Utilities; -using PluginCore.Localization; -using ASCompletion.Model; -using System.Collections; -using System.Collections.Generic; namespace AS3Context.Compiler { public delegate void SyntaxErrorHandler(string error); - /// - /// Wrappers for Flex SDK integration - /// - public class FlexShells - { - static public event SyntaxErrorHandler SyntaxError; - - static readonly public Regex re_SplitParams = - new Regex("[\\s](?\\-[A-z0-9\\-\\.]+)", RegexOptions.Compiled | RegexOptions.Singleline); - - static private readonly string[] PATH_SWITCHES = { - "-compiler.context-root","-context-root", - "-compiler.defaults-css-url","-defaults-css-url", - "-compiler.external-library-path","-external-library-path","-el", - "-compiler.fonts.system-search-path","-system-search-path", - "-compiler.include-libraries","-include-libraries", - "-compiler.library-path","-library-path","-l", - "-compiler.source-path","-source-path","-sp", - "-compiler.services","-services", - "-compiler.theme","-theme", - "-dump-config","-file-specs","resource-bundle-list", - "-link-report","-load-config","-load-externs","-size-report", - "-output","-o","-runtime-shared-libraries","-rsl", + /// + /// Wrappers for Flex SDK integration + /// + public class FlexShells + { + public static event SyntaxErrorHandler SyntaxError; + + public static readonly Regex re_SplitParams = + new Regex("[\\s](?[-+][A-z0-9\\-\\.]+)", RegexOptions.Compiled | RegexOptions.Singleline); + + static readonly string[] PATH_SWITCHES = { + "-compiler.context-root","-context-root", + "-compiler.defaults-css-url","-defaults-css-url", + "-compiler.external-library-path","-external-library-path","-el", + "-compiler.fonts.system-search-path","-system-search-path", + "-compiler.include-libraries","-include-libraries", + "-compiler.library-path","-library-path","-l", + "-compiler.source-path","-source-path","-sp", + "-compiler.services","-services", + "-compiler.theme","-theme", + "-dump-config","-file-specs","resource-bundle-list", + "-link-report","-load-config","-load-externs","-size-report", + "-output","-o","-runtime-shared-libraries","-rsl", "-namespace","-compiler.namespaces.namespace"}; - - static private string ascPath; - static private string mxmlcPath; - static private string flexShellsJar = "Flex4Shells.jar"; - static private string flexShellsPath; - static private bool running; - static private bool silentChecking; - static private string checkedSDK; - static private bool isFlex4SDK; - static private string currentSDK; - - static private string CheckResource(string resName, string fileName) - { - string path = Path.Combine(PathHelper.DataDir, "AS3Context"); - string fullPath = Path.Combine(path, fileName); - if (!File.Exists(fullPath)) - { - string id = "AS3Context.Resources." + resName; - System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); - using (BinaryReader br = new BinaryReader(assembly.GetManifestResourceStream(id))) - { - using (FileStream bw = File.Create(fullPath)) - { - byte[] buffer = br.ReadBytes(1024); - while (buffer.Length > 0) - { - bw.Write(buffer, 0, buffer.Length); - buffer = br.ReadBytes(1024); - } - bw.Close(); - } - br.Close(); - } - } + + static string ascPath; + static string mxmlcPath; + static readonly string flexShellsJar = "Flex4Shells.jar"; + static string flexShellsPath; + static bool running; + static bool silentChecking; + static string checkedSDK; + static bool isFlex4SDK; + static string currentSDK; + + static string CheckResource(string resName, string fileName) + { + var fullPath = Path.Combine(PathHelper.DataDir, "AS3Context", fileName); + if (File.Exists(fullPath)) return fullPath; + var id = "AS3Context.Resources." + resName; + var assembly = Assembly.GetExecutingAssembly(); + using var br = new BinaryReader(assembly.GetManifestResourceStream(id)); + using var bw = File.Create(fullPath); + var buffer = br.ReadBytes(1024); + while (buffer.Length > 0) + { + bw.Write(buffer, 0, buffer.Length); + buffer = br.ReadBytes(1024); + } + bw.Close(); + br.Close(); return fullPath; - } - - static public FlexShells Instance - { - get { - if (instance == null) instance = new FlexShells(); - return instance; - } - } - - static private FlexShells instance; - - private FlexShells() - { - } - - private ProcessRunner ascRunner; - private ProcessRunner mxmlcRunner; - private string builtSWF; - private bool debugMode; - private Dictionary jvmConfig; - - public void CheckAS3(string filename, string flexPath) + } + + public static FlexShells Instance => instance ??= new FlexShells(); + + static FlexShells instance; + + FlexShells() { - CheckAS3(filename, flexPath, null); } + ProcessRunner ascRunner; + ProcessRunner mxmlcRunner; + string builtSWF; + bool debugMode; + Dictionary jvmConfig; + + public void CheckAS3(string filename, string flexPath) => CheckAS3(filename, flexPath, null); + public void CheckAS3(string filename, string flexPath, string src) - { + { if (running) return; // let other plugins preprocess source/handle checking - Hashtable data = new Hashtable(); - data["filename"] = filename; - data["src"] = src; - data["ext"] = Path.GetExtension(filename); - DataEvent de = new DataEvent(EventType.Command, "AS3Context.CheckSyntax", data); + var data = new Hashtable {["filename"] = filename, ["src"] = src, ["ext"] = Path.GetExtension(filename)}; + var de = new DataEvent(EventType.Command, "AS3Context.CheckSyntax", data); EventManager.DispatchEvent(this, de); if (de.Handled) return; @@ -126,29 +105,27 @@ public void CheckAS3(string filename, string flexPath, string src) return; string basePath = null; - if (PluginBase.CurrentProject != null) - basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath); + if (PluginBase.CurrentProject != null) basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath); flexPath = PathHelper.ResolvePath(flexPath, basePath); // asc.jar in FlexSDK if (flexPath != null && Directory.Exists(Path.Combine(flexPath, "lib"))) ascPath = Path.Combine(flexPath, "lib\\asc.jar"); // included asc.jar - if (ascPath == null || !File.Exists(ascPath)) - ascPath = PathHelper.ResolvePath(Path.Combine(PathHelper.ToolDir, "flexlibs/lib/asc.jar")); - - if (ascPath == null) + if (!File.Exists(ascPath)) ascPath = PathHelper.ResolvePath(Path.Combine(PathHelper.ToolDir, "flexlibs/lib/asc.jar")); + if (ascPath is null) { if (src != null) return; // silent checking - DialogResult result = MessageBox.Show(TextHelper.GetString("Info.SetFlex2OrCS3Path"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.YesNoCancel); - if (result == DialogResult.Yes) - { - IASContext context = ASContext.GetLanguageContext("as3"); - if (context == null) return; - PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK"); - } - else if (result == DialogResult.No) + var result = MessageBox.Show(TextHelper.GetString("Info.SetFlex2OrCS3Path"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.YesNoCancel); + switch (result) { - PluginBase.MainForm.ShowSettingsDialog("ASCompletion", "Flash"); + case DialogResult.Yes: + var context = ASContext.GetLanguageContext("as3"); + if (context is null) return; + PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK"); + break; + case DialogResult.No: + PluginBase.MainForm.ShowSettingsDialog("ASCompletion", "Flash"); + break; } return; } @@ -162,16 +139,14 @@ public void CheckAS3(string filename, string flexPath, string src) } jvmConfig = JvmConfigHelper.ReadConfig(flexPath); - - try - { + + try + { running = true; - if (src == null) EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart)); - if (ascRunner == null || !ascRunner.IsRunning || currentSDK != flexPath) - StartAscRunner(flexPath); - - notificationSent = false; - if (src == null) + if (src is null) EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart)); + if (ascRunner is null || !ascRunner.IsRunning || currentSDK != flexPath) StartAscRunner(flexPath); + notificationSent = false; + if (src is null) { silentChecking = false; //TraceManager.Add("Checking: " + filename, -1); @@ -185,37 +160,31 @@ public void CheckAS3(string filename, string flexPath, string src) ascRunner.HostedProcess.StandardInput.WriteLine(src); ascRunner.HostedProcess.StandardInput.WriteLine(filename + "$raw$"); } - } - catch(Exception ex) - { + } + catch(Exception ex) + { ErrorManager.AddToLog(TextHelper.GetString("Info.CheckError"), ex); TraceManager.AddAsync(TextHelper.GetString("Info.CheckError") + "\n" + ex.Message); - } - } + } + } public void RunMxmlc(string cmd, string flexPath) - { + { if (running) return; string basePath = null; - if (PluginBase.CurrentProject != null) - basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath); + if (PluginBase.CurrentProject != null) basePath = Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath); flexPath = PathHelper.ResolvePath(flexPath, basePath); - if (flexPath != null && Directory.Exists(flexPath)) + if (Directory.Exists(flexPath)) mxmlcPath = Path.Combine(flexPath, "lib", "mxmlc.jar"); + if (!File.Exists(mxmlcPath)) { - mxmlcPath = Path.Combine(Path.Combine(flexPath, "lib"), "mxmlc.jar"); + var result = MessageBox.Show(TextHelper.GetString("Info.OpenCompilerSettings"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.OKCancel); + if (result != DialogResult.OK) return; + var context = ASContext.GetLanguageContext("as3"); + if (context is null) return; + PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK"); + return; } - if (mxmlcPath == null || !File.Exists(mxmlcPath)) - { - DialogResult result = MessageBox.Show(TextHelper.GetString("Info.OpenCompilerSettings"), TextHelper.GetString("Title.ConfigurationRequired"), MessageBoxButtons.OKCancel); - if (result == DialogResult.OK) - { - IASContext context = ASContext.GetLanguageContext("as3"); - if (context == null) return; - PluginBase.MainForm.ShowSettingsDialog("AS3Context", "SDK"); - } - return; - } flexShellsPath = CheckResource("FlexShells.jar", flexShellsJar); if (!File.Exists(flexShellsPath)) @@ -225,68 +194,65 @@ public void RunMxmlc(string cmd, string flexPath) } jvmConfig = JvmConfigHelper.ReadConfig(flexPath); - - try - { + + try + { running = true; - EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart)); + EventManager.DispatchEvent(this, new NotifyEvent(EventType.ProcessStart)); - if (mxmlcRunner == null || !mxmlcRunner.IsRunning || currentSDK != flexPath) + if (mxmlcRunner is null || !mxmlcRunner.IsRunning || currentSDK != flexPath) StartMxmlcRunner(flexPath); - - //cmd = mainForm.ProcessArgString(cmd); - //TraceManager.Add("MxmlcShell command: "+cmd, -1); + + //cmd = mainForm.ProcessArgString(cmd); + //TraceManager.Add("MxmlcShell command: "+cmd, -1); ASContext.SetStatusText(TextHelper.GetString("Info.MxmlcRunning")); - notificationSent = false; - mxmlcRunner.HostedProcess.StandardInput.WriteLine(cmd); - } - catch(Exception ex) - { - ErrorManager.ShowError(ex); - } - } + notificationSent = false; + mxmlcRunner.HostedProcess.StandardInput.WriteLine(cmd); + } + catch(Exception ex) + { + ErrorManager.ShowError(ex); + } + } public void QuickBuild(FileModel theFile, string flex2Path, bool requireTag, bool playAfterBuild) - { + { if (running) return; - // environment + // environment string filename = theFile.FileName; string currentPath = Environment.CurrentDirectory; string buildPath = PluginBase.MainForm.ProcessArgString("$(ProjectDir)"); - if (!Directory.Exists(buildPath) + if (!Directory.Exists(buildPath) || !filename.StartsWith(buildPath, StringComparison.OrdinalIgnoreCase)) - { + { buildPath = theFile.BasePath; if (!Directory.Exists(buildPath)) - buildPath = Path.GetDirectoryName(filename); - } - // command + buildPath = Path.GetDirectoryName(filename); + } + // command debugMode = false; - bool hasOutput = false; - string cmd = ""; - Match mCmd = Regex.Match(PluginBase.MainForm.CurrentDocument.SciControl.Text, "\\s@mxmlc\\s(?.*)"); + var hasOutput = false; + var cmd = ""; + var mCmd = Regex.Match(PluginBase.MainForm.CurrentDocument?.SciControl.Text, "\\s@mxmlc\\s(?.*)"); if (mCmd.Success) { try { - // cleanup tag - string tag = mCmd.Groups["cmd"].Value; - if (tag.IndexOf("-->") > 0) tag = tag.Substring(0, tag.IndexOf("-->")); - if (tag.IndexOf("]]>") > 0) tag = tag.Substring(0, tag.IndexOf("]]>")); + var tag = mCmd.Groups["cmd"].Value; + if (tag.IndexOfOrdinal("-->") > 0) tag = tag.Substring(0, tag.IndexOfOrdinal("-->")); + if (tag.IndexOfOrdinal("]]>") > 0) tag = tag.Substring(0, tag.IndexOfOrdinal("]]>")); tag = " " + tag.Trim() + " --"; // split - MatchCollection mPar = re_SplitParams.Matches(tag); + var mPar = re_SplitParams.Matches(tag); if (mPar.Count > 0) { cmd = ""; - string op; - string arg; for (int i = 0; i < mPar.Count; i++) { - op = mPar[i].Groups["switch"].Value; + var op = mPar[i].Groups["switch"].Value; if (op == "--") break; if (op == "-noplay") { @@ -300,8 +266,8 @@ public void QuickBuild(FileModel theFile, string flex2Path, bool requireTag, boo if (end > start) { string concat = ";"; - arg = tag.Substring(start, end - start).Trim(); - if (arg.StartsWith("+=") || arg.StartsWith("=")) + var arg = tag.Substring(start, end - start).Trim(); + if (arg.StartsWithOrdinal("+=") || arg.StartsWith('=')) { concat = arg.Substring(0, arg.IndexOf('=') + 1); arg = arg.Substring(concat.Length); @@ -311,7 +277,7 @@ public void QuickBuild(FileModel theFile, string flex2Path, bool requireTag, boo { if (pswitch == op) { - if (op.EndsWith("namespace")) + if (op.EndsWithOrdinal("namespace")) { int sp = arg.IndexOf(' '); if (sp > 0) @@ -321,7 +287,11 @@ public void QuickBuild(FileModel theFile, string flex2Path, bool requireTag, boo } } isPath = true; - if (!arg.StartsWith("\\") && !Path.IsPathRooted(arg)) + // remove quotes + if (arg.StartsWith('\"') && arg.EndsWith('\"')) + arg = arg.Substring(1, arg.Length - 2); + + if (!arg.StartsWith('\\') && !Path.IsPathRooted(arg)) arg = Path.Combine(buildPath, arg); } } @@ -330,7 +300,7 @@ public void QuickBuild(FileModel theFile, string flex2Path, bool requireTag, boo builtSWF = arg; hasOutput = true; } - if (!isPath) arg = arg.Replace(" ", ";"); + if (!isPath) arg = arg.Replace(' ', ';'); cmd += op + concat + arg + ";"; } else cmd += op + ";"; @@ -345,13 +315,13 @@ public void QuickBuild(FileModel theFile, string flex2Path, bool requireTag, boo else if (requireTag) return; // Flex4 static linking - if (isFlex4SDK && cmd.IndexOf("-static-link-runtime-shared-libraries") < 0) + if (isFlex4SDK && !cmd.Contains("-static-link-runtime-shared-libraries")) cmd += ";-static-link-runtime-shared-libraries=true"; // add current class sourcepath and global classpaths cmd += ";-sp+=" + theFile.BasePath; - if (Context.Context.Settings.UserClasspath != null) - foreach (string cp in Context.Context.Settings.UserClasspath) + if (ASContext.Context.Settings.UserClasspath != null) + foreach (string cp in ASContext.Context.Settings.UserClasspath) cmd += ";-sp+=" + cp; // add output filename if (!hasOutput) @@ -363,15 +333,15 @@ public void QuickBuild(FileModel theFile, string flex2Path, bool requireTag, boo cmd += ";--;" + filename; // build - cmd = cmd.Replace(";;", ";"); + cmd = cmd.Replace(";;", ";"); RunMxmlc(cmd, flex2Path); - if (!playAfterBuild) builtSWF = null; - - // restaure working directory - Environment.CurrentDirectory = currentPath; + if (!playAfterBuild) builtSWF = null; + + // restaure working directory + Environment.CurrentDirectory = currentPath; } - private void CheckIsFlex4SDK(string flexPath) + void CheckIsFlex4SDK(string flexPath) { if (checkedSDK == flexPath) return; checkedSDK = flexPath; @@ -380,7 +350,7 @@ private void CheckIsFlex4SDK(string flexPath) if (File.Exists(flexDesc)) { string src = File.ReadAllText(flexDesc); - isFlex4SDK = src.IndexOf("4") > 0; + isFlex4SDK = src.IndexOfOrdinal("4") > 0; } else isFlex4SDK = false; } @@ -388,30 +358,44 @@ private void CheckIsFlex4SDK(string flexPath) #region Background process /// - /// Stop background processes - /// - public void Stop() - { - if (ascRunner != null && ascRunner.IsRunning) ascRunner.KillProcess(); - ascRunner = null; - if (mxmlcRunner != null && mxmlcRunner.IsRunning) mxmlcRunner.KillProcess(); - mxmlcRunner = null; - } - - /// - /// Start background process - /// - private void StartAscRunner(string flexPath) - { + /// Stop background processes + /// + public void Stop() + { + try + { + if (ascRunner != null && ascRunner.IsRunning) ascRunner.KillProcess(); + } + catch { } + finally + { + ascRunner = null; + } + try + { + if (mxmlcRunner != null && mxmlcRunner.IsRunning) mxmlcRunner.KillProcess(); + } + catch { } + finally + { + mxmlcRunner = null; + } + } + + /// + /// Start background process + /// + void StartAscRunner(string flexPath) + { currentSDK = flexPath; if (ascRunner != null && ascRunner.IsRunning) ascRunner.KillProcess(); - string cmd = "-Duser.language=en -Duser.region=US" + string cmd = jvmConfig["java.args"] + " -classpath \"" + ascPath + ";" + flexShellsPath + "\" AscShell"; TraceManager.Add(TextHelper.GetString("Info.StartAscRunner") + "\n" - + JvmConfigHelper.GetJavaEXE(jvmConfig) + " " + cmd, -1); - // run asc shell - ascRunner = new ProcessRunner(); + + JvmConfigHelper.GetJavaEXE(jvmConfig) + " " + cmd, 0); + // run asc shell + ascRunner = new ProcessRunner(); ascRunner.WorkingDirectory = Path.GetDirectoryName(ascPath); ascRunner.RedirectInput = true; ascRunner.Run(JvmConfigHelper.GetJavaEXE(jvmConfig), cmd, true); @@ -419,13 +403,13 @@ private void StartAscRunner(string flexPath) ascRunner.Error += ascRunner_Error; errorState = 0; Thread.Sleep(100); - } - - /// - /// Start background process - /// - private void StartMxmlcRunner(string flexPath) - { + } + + /// + /// Start background process + /// + void StartMxmlcRunner(string flexPath) + { currentSDK = flexPath; if (mxmlcRunner != null && mxmlcRunner.IsRunning) mxmlcRunner.KillProcess(); @@ -436,7 +420,7 @@ private void StartMxmlcRunner(string flexPath) + " -classpath \"" + mxmlcPath + ";" + flexShellsPath + "\" " + shell; TraceManager.Add(TextHelper.GetString("Info.StartMxmlcRunner") + "\n" + JvmConfigHelper.GetJavaEXE(jvmConfig) + " " + cmd, -1); - // run compiler shell + // run compiler shell mxmlcRunner = new ProcessRunner(); mxmlcRunner.WorkingDirectory = Path.Combine(flexPath, "frameworks"); mxmlcRunner.RedirectInput = true; @@ -451,13 +435,13 @@ private void StartMxmlcRunner(string flexPath) #region process output capture - private int errorState; - private string errorDesc; - private bool notificationSent; + int errorState; + string errorDesc; + bool notificationSent; - private void ascRunner_Error(object sender, string line) + void ascRunner_Error(object sender, string line) { - if (line.StartsWith("[Compiler] Error")) + if (line.StartsWithOrdinal("[Compiler] Error")) { errorState = 1; errorDesc = line.Substring(10); @@ -465,64 +449,60 @@ private void ascRunner_Error(object sender, string line) else if (errorState == 1) { line = line.Trim(); - Match mErr = Regex.Match(line, @"(?[^,]+), Ln (?[0-9]+), Col (?[0-9]+)"); + var mErr = Regex.Match(line, @"(?[^,]+), Ln (?[0-9]+), Col (?[0-9]+)"); if (mErr.Success) { - string filename = mErr.Groups["file"].Value; - try - { - if (File.Exists(filename)) - { - StringBuilder sb = new StringBuilder(1024); - GetLongPathName(filename, sb, (uint)1024); - filename = sb.ToString(); - } - } - catch {} - errorDesc = String.Format("{0}:{1}: col: {2}: {3}", filename, mErr.Groups["line"].Value, mErr.Groups["col"].Value, errorDesc); + var filename = mErr.Groups["file"].Value; + try + { + if (File.Exists(filename)) + { + filename = PathHelper.GetLongPathName(filename); + } + } + catch {} + errorDesc = $"{filename}:{mErr.Groups["line"].Value}: col: {mErr.Groups["col"].Value}: {errorDesc}"; ascRunner_OutputError(sender, errorDesc); } errorState++; } else if (errorState > 0) { - if (line.IndexOf("error found") > 0) errorState = 0; + if (line.IndexOfOrdinal("error found") > 0) errorState = 0; } else if (line.Trim().Length > 0) ascRunner_OutputError(sender, line); } - - private void ascRunner_OutputError(object sender, string line) + + void ascRunner_OutputError(object sender, string line) { - if (line == null) return; - PluginBase.RunAsync((MethodInvoker)delegate + if (line is null) return; + PluginBase.RunAsync(delegate { - if (line.StartsWith("Exception ")) + if (line.StartsWithOrdinal("Exception ")) { TraceManager.AddAsync(line, -3); return; } if (silentChecking) { - if (SyntaxError != null) SyntaxError(line); + SyntaxError?.Invoke(line); return; } TraceManager.Add(line, -3); - if (!notificationSent) - { - notificationSent = true; - TraceManager.Add("Done(1)", -2); - EventManager.DispatchEvent(this, new TextEvent(EventType.ProcessEnd, "Done(1)")); - ASContext.SetStatusText(TextHelper.GetString("Info.AscDone")); - EventManager.DispatchEvent(this, new DataEvent(EventType.Command, "ResultsPanel.ShowResults", null)); - } + if (notificationSent) return; + notificationSent = true; + TraceManager.Add("Done(1)", -2); + EventManager.DispatchEvent(this, new TextEvent(EventType.ProcessEnd, "Done(1)")); + ASContext.SetStatusText(TextHelper.GetString("Info.AscDone")); + EventManager.DispatchEvent(this, new DataEvent(EventType.Command, "ResultsPanel.ShowResults", null)); }); } - private void ascRunner_Output(object sender, string line) + void ascRunner_Output(object sender, string line) { - if (line.StartsWith("(ash)")) + if (line.StartsWithOrdinal("(ash)")) { - if (line.IndexOf("Done") > 0) + if (line.IndexOfOrdinal("Done") > 0) { running = false; if (!silentChecking && !notificationSent) @@ -537,21 +517,21 @@ private void ascRunner_Output(object sender, string line) if (!silentChecking) TraceManager.AddAsync(line, 0); } - private void ascRunner_End() + static void ascRunner_End() { TraceManager.AddAsync("Done(0)", -2); } - - private void mxmlcRunner_Error(object sender, string line) + + static void mxmlcRunner_Error(object sender, string line) { TraceManager.AddAsync(line, -3); } - private void mxmlcRunner_Output(object sender, string line) + void mxmlcRunner_Output(object sender, string line) { - PluginBase.RunAsync((MethodInvoker)delegate + PluginBase.RunAsync(delegate { - if (!notificationSent && line.StartsWith("Done(")) + if (!notificationSent && line.StartsWithOrdinal("Done(")) { running = false; TraceManager.Add(line, -2); @@ -567,16 +547,16 @@ private void mxmlcRunner_Output(object sender, string line) else TraceManager.Add(line, 0); }); } - - private void RunAfterBuild() + + void RunAfterBuild() { - if (builtSWF == null || !File.Exists(builtSWF)) + if (!File.Exists(builtSWF)) { debugMode = false; return; } - string swf = builtSWF; - builtSWF = null; + string swf = builtSWF; + builtSWF = null; // debugger if (debugMode) @@ -585,44 +565,27 @@ private void RunAfterBuild() EventManager.DispatchEvent(this, de); } - // other plugin may handle the SWF playing + // other plugin may handle the SWF playing DataEvent dePlay = new DataEvent(EventType.Command, "FlashViewer.Default", swf); EventManager.DispatchEvent(this, dePlay); - if (dePlay.Handled) return; - - try - { - // change current directory - string currentPath = System.IO.Directory.GetCurrentDirectory(); - System.IO.Directory.SetCurrentDirectory(Path.GetDirectoryName(swf)); - // run - System.Diagnostics.Process.Start(swf); - // restaure current directory - System.IO.Directory.SetCurrentDirectory(currentPath); - } - catch (Exception ex) - { - ErrorManager.ShowError(ex.Message, ex); - } + if (dePlay.Handled) return; + + try + { + // change current directory + string currentPath = Directory.GetCurrentDirectory(); + Directory.SetCurrentDirectory(Path.GetDirectoryName(swf)); + // run + Process.Start(swf); + // restaure current directory + Directory.SetCurrentDirectory(currentPath); + } + catch (Exception ex) + { + ErrorManager.ShowError(ex.Message, ex); + } } #endregion - #region Win32 - - [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError=true)] - static extern uint GetShortPathName( - [MarshalAs(UnmanagedType.LPTStr)] - string lpszLongPath, - [MarshalAs(UnmanagedType.LPTStr)] - StringBuilder lpszShortPath, - uint cchBuffer); - - [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] - static extern uint GetLongPathName( - string lpszShortPath, - [Out] StringBuilder lpszLongPath, - uint cchBuffer); - - #endregion } } diff --git a/External/Plugins/AS3Context/Completion/CodeComplete.cs b/External/Plugins/AS3Context/Completion/CodeComplete.cs new file mode 100644 index 0000000000..af864d440f --- /dev/null +++ b/External/Plugins/AS3Context/Completion/CodeComplete.cs @@ -0,0 +1,176 @@ +using System.Collections.Generic; +using System.Linq; +using ASCompletion.Completion; +using ASCompletion.Context; +using ASCompletion.Model; +using PluginCore; +using ScintillaNet; + +namespace AS3Context.Completion +{ + class CodeComplete : ASComplete + { + /// + protected override ASResult EvalExpression(string expression, ASExpr context, FileModel inFile, ClassModel inClass, bool complete, bool asFunction, bool filterVisibility) + { + if (!string.IsNullOrEmpty(expression)) + { + var ctx = ASContext.Context; + var features = ctx.Features; + // for example: 1.0., 5e-324. + if (char.IsDigit(expression, 0) + // for example: -1. + || (expression.Length > 1 && expression[0] == '-' && char.IsDigit(expression, 1)) + // for example: --1. + || (expression.Length > 2 && expression[0] == '-' && expression[1] == '-' && + char.IsDigit(expression, 2))) + { + int p; + var pe2 = -1; + if (expression.Contains("e-", out var pe1) || expression.Contains("e+", out pe2)) + { + p = expression.IndexOf('.'); + if (p == -1) p = expression.Length - 1; + else if (p < pe1 || p < pe2) + { + var p2 = expression.IndexOf('.', p + 1); + p = p2 != -1 ? p2 : expression.Length - 1; + } + } + else + { + p = expression.IndexOf('.'); + if (p == expression.Length - 1) p = -1; + else if (p != -1) + { + // for example: 1.0. + if (char.IsDigit(expression[p + 1])) + { + var p2 = expression.IndexOf('.', p + 1); + p = p2 != -1 ? p2 : expression.Length - 1; + } + // for example: -1.valueOf(). + else p = -1; + } + } + + if (p != -1) + { + expression = "Number.#." + expression.Substring(p + 1); + return base.EvalExpression(expression, context, inFile, inClass, complete, asFunction, + filterVisibility); + } + } + + if (context.SubExpressions != null) + { + var count = context.SubExpressions.Count - 1; + // transform #2~.#1~.#0~ to #2~.[].[] + for (var i = 0; i <= count; i++) + { + var subExpression = context.SubExpressions[i]; + if (subExpression.Length < 2 || subExpression[0] != '[') continue; + // for example: []. + if (expression[0] == '#' && i == count) + { + var type = ResolveType(features.arrayKey, inFile); + if (type.IsVoid()) break; + expression = type.Name + ".#" + expression.Substring(("#" + i + "~").Length); + context.SubExpressions.RemoveAt(i); + return base.EvalExpression(expression, context, inFile, inClass, complete, asFunction, + filterVisibility); + } + + expression = expression.Replace(">.#" + i + "~", ">" + subExpression); + expression = expression.Replace(".#" + i + "~", "." + subExpression); + } + } + + if (expression.Length > 1 && expression[0] is { } c && (c == '"' || c == '\'')) + { + var type = ResolveType(features.stringKey, inFile); + // for example: ""|, ''| + if (context.SubExpressions is null) expression = type.Name + ".#."; + // for example: ""., ''. + else + { + var pattern = c + ".#" + (context.SubExpressions.Count - 1) + "~"; + var startIndex = expression.IndexOfOrdinal(pattern) + pattern.Length; + expression = type.Name + ".#" + expression.Substring(startIndex); + } + } + // for example: new []. + else if (expression.Contains(">.[")) expression = expression.Replace(">.[", ">["); + // transform Vector. to Vector + else if (expression.Contains(".<")) expression = expression.Replace(".<", "<"); + // for example: /pattern/. + else if (expression.StartsWithOrdinal("#RegExp")) expression = expression.Substring(1); + else if (!context.SubExpressions.IsNullOrEmpty()) + { + var expr = context.SubExpressions.Last(); + // for example: (v as T)., (v is Complete)., ... + if (expr.Length >= 8 /*"(v as T)".Length*/ && expr[0] == '(') + { + var type = ctx.ResolveToken(expr, inFile); + if (!type.IsVoid()) + { + expression = type.Name + ".#" + + expression.Substring(("#" + (context.SubExpressions.Count - 1) + "~").Length); + context.SubExpressions.RemoveAt(context.SubExpressions.Count - 1); + if (context.SubExpressions.Count == 0) context.SubExpressions = null; + } + } + } + } + + return base.EvalExpression(expression, context, inFile, inClass, complete, asFunction, filterVisibility); + } + + /// + protected override bool HandleNewCompletion(ScintillaControl sci, string tail, bool autoHide, string keyword, List list) + { + if (keyword == "new") list.RemoveAll(it => it is MemberItem {Member: { } member} && (member.Flags & FlagType.Interface) != 0); + return base.HandleNewCompletion(sci, tail, autoHide, keyword, list); + } + + /// + protected override bool IsAvailableForToolTip(ScintillaControl sci, int position) + { + return base.IsAvailableForToolTip(sci, position) + || (sci.GetWordFromPosition(position) is { } word + && (word == "as" || word == "is" || word == "instanceof" || word == "typeof" || word == "delete")); + } + + /// + protected override string GetToolTipTextEx(ASResult expr) + { + if (expr.Member is null && expr.Context?.Value is {} s) + { + switch (s) + { + // for example: variable as$(EntryPoint) Type + case "as": + expr.Member = Context.StubAsExpression; + break; + // for example: variable is$(EntryPoint) Type + case "is": + expr.Member = Context.StubIsExpression; + break; + // for example: variable instanceof$(EntryPoint) function + case "instanceof": + expr.Member = Context.StubInstanceOfExpression; + break; + // for example: typeof(EntryPoint) expression + case "typeof": + expr.Member = Context.StubTypeOfExpression; + break; + // for example: delete$(EntryPoint) reference + case "delete": + expr.Member = Context.StubDeleteExpression; + break; + } + } + return base.GetToolTipTextEx(expr); + } + } +} \ No newline at end of file diff --git a/External/Plugins/AS3Context/Context.cs b/External/Plugins/AS3Context/Context.cs index 4900524bf0..46ea4ca287 100644 --- a/External/Plugins/AS3Context/Context.cs +++ b/External/Plugins/AS3Context/Context.cs @@ -1,41 +1,145 @@ using System; using System.Collections.Generic; -using System.Text; using System.IO; -using PluginCore.Managers; +using System.Text.RegularExpressions; +using System.Timers; +using System.Windows.Forms; +using AS3Context.Compiler; +using ASCompletion.Completion; using ASCompletion.Context; using ASCompletion.Model; using PluginCore; -using System.Collections; -using System.Text.RegularExpressions; using PluginCore.Controls; -using PluginCore.Localization; -using AS3Context.Compiler; using PluginCore.Helpers; -using System.Timers; -using ASCompletion.Completion; +using PluginCore.Localization; +using PluginCore.Managers; +using ScintillaNet; +using ScintillaNet.Enums; +using SwfOp; +using Timer = System.Timers.Timer; +using AS3Context.Completion; namespace AS3Context { public class Context : AS2Context.Context { - static readonly protected Regex re_genericType = + protected static readonly Regex re_genericType = new Regex("(?[^<]+)\\.<(?.+)>$", RegexOptions.Compiled | RegexOptions.IgnoreCase); // C:\path\to\Main.as$raw$:31: col: 1: Error #1084: Syntax error: expecting rightbrace before end of program. - static readonly protected Regex re_syntaxError = + protected static readonly Regex re_syntaxError = new Regex("(?.*)\\$raw\\$:(?[0-9]+): col: (?[0-9]+):(?.*)", RegexOptions.Compiled); - static readonly protected Regex re_customAPI = + protected static readonly Regex re_customAPI = new Regex("[/\\\\](playerglobal|airglobal|builtin)\\.swc", RegexOptions.Compiled | RegexOptions.IgnoreCase); + internal static readonly MemberModel StubAsExpression = new MemberModel("as operator", null, FlagType.Declaration, 0) + { + Comments = "\r\t * Usage" + + "\r\t * expression as datatype" + + "\r\t * " + + "\r\t * Language Version: ActionScript 3.0" + + "\r\t * Runtime Versions: Flash Player 9" + + "\r\t * " + + "\r\t * Evaluates whether an expression specified by the first operand is a member of the data type specified by the second operand." + + "\r\t * If the first operand is a member of the data type, the result is the first operand. Otherwise, the result is the value null." + + "\r\t * " + + "\r\t * The expression used for the second operand must evaluate to a data type." + + "\r\t * " + + "\r\t * Operands" + + "\r\t * expression:* The value to check against the data type specified." + + "\r\t * datatype:Class The data type used to evaluate the expression operand. The special * type, which means untyped, cannot be used." + + "\r\t * " + + "\r\t * Result" + + "\r\t * Object The result is expression if expression is a member of the data type specified in datatype. Otherwise, the result is the value null." + }; + + internal static readonly MemberModel StubIsExpression = new MemberModel("is operator", null, FlagType.Declaration, 0) + { + Comments = "\r\t * Usage" + + "\r\t * expression is datatype" + + "\r\t * " + + "\r\t * Language Version: ActionScript 3.0" + + "\r\t * Runtime Versions: Flash Player 9" + + "\r\t * " + + "\r\t * Evaluates whether an object is compatible with a specific data type, class, or interface. Use the is operator instead of the instanceof operator for type comparisons. You can also use the is operator to check whether an object implements an interface." + + "\r\t * " + + "\r\t * Result" + + "\r\t * Boolean A value of true if expression1 is compatible with the data type, class, or interface specified in expression2, and false otherwise." + }; + + internal static readonly MemberModel StubInstanceOfExpression = new MemberModel("instaceof operator", null, FlagType.Declaration, 0) + { + Comments = "\r\t * Usage" + + "\r\t * expression instanceof function" + + "\r\t * " + + "\r\t * Language Version: ActionScript 3.0" + + "\r\t * Runtime Versions: Flash Player 9" + + "\r\t * " + + "\r\t * Evaluates whether an expression's prototype chain includes the prototype object for function. The instanceof operator is included for backward compatibility with ECMAScript edition 3, and may be useful for advanced programmers who choose to use prototype-based inheritance with constructor functions instead of classes." + + "\r\t * " + + "\r\t * To check whether an object is a member of a specific data type, use the is operator." + + "\r\t * " + + "\r\t * When used with classes, the instanceof operator is similar to the is operator because a class's prototype chain includes all of its superclasses. Interfaces, however, are not included on prototype chains, so the instanceof operator always results in false when used with interfaces, whereas the is operator results in true if an object belongs to a class that implements the specified interface." + + "\r\t * " + + "\r\t * Note: The ActionScript is operator is the equivalent of the Java instanceof operator." + + "\r\t * " + + "\r\t * Operands" + + "\r\t * expression:Object The object that contains the prototype chain to evaluate." + + "\r\t * function:Object A function object (or class)." + + "\r\t * " + + "\r\t * Result" + + "\r\t * Boolean Returns true if the prototype chain of expression includes the prototype object for function, and false otherwise." + }; + + internal static readonly MemberModel StubTypeOfExpression = new MemberModel("typeof operator", null, FlagType.Declaration, 0) + { + Comments = "\r\t * Usage" + + "\r\t * typeof expression" + + "\r\t * " + + "\r\t * Language Version: ActionScript 3.0" + + "\r\t * Runtime Versions: Flash Player 9" + + "\r\t * " + + "\r\t * Evaluates expression and returns a string specifying the expression's data type. The result is limited to six possible string values: boolean, function, number, object, string, and xml. If you apply this operator to an instance of a user-defined class, the result is the string object. The typeof operator is included for backward compatibility. Use the is operator to check type compatibility." + + "\r\t * " + + "\r\t * Operands" + + "\r\t * expression:Object An object to evaluate." + + "\r\t * " + + "\r\t * Result" + + "\r\t * String A string representation of the type of expression. The following table shows the results of the typeof operator on each type of expression." + }; + + internal static readonly MemberModel StubDeleteExpression = new MemberModel("delete operator", null, FlagType.Declaration, 0) + { + Comments = "\r\t * Usage" + + "\r\t * delete reference" + + "\r\t * " + + "\r\t * Language Version: ActionScript 3.0" + + "\r\t * Runtime Versions: Flash Player 9" + + "\r\t * " + + "\r\t * Destroys the object property specified by reference; the result is true if the property does not exist after the operation completes, and false otherwise. The delete operator returns true if it is called on a nonexistent property or a dynamic property not defined in a class." + + "\r\t * " + + "\r\t * The delete operator can fail and return false if the reference parameter cannot be deleted. You cannot delete fixed properties or variables that are declared with the var statement. A fixed property is a variable or method defined in a class definition." + + "\r\t * " + + "\r\t * The delete operator cannot be used to destroy a property of a class, unless that class is a dynamic class added at runtime. Properties of sealed classes cannot be destroyed using delete. Set the property to null instead." + + "\r\t * " + + "\r\t * Note: You cannot delete an object, but you can make an object eligible for garbage collection by removing all references to the object. The most common reference to an object is a variable that points to it. You can remove such a reference by setting the variable to null. The garbage collector removes any object that has no references." + + "\r\t * " + + "\r\t * Operands" + + "\r\t * reference:* The name of the property to eliminate." + + "\r\t * " + + "\r\t * Result" + + "\r\t * Boolean The value true if the deletion succeeded and false if it failed." + }; + #region initialization - private AS3Settings as3settings; - private bool hasAIRSupport; - private bool hasMobileSupport; - private MxmlFilterContext mxmlFilterContext; // extract inlined AS3 ranges & MXML tags - private System.Timers.Timer timerCheck; - private string fileWithSquiggles; + + readonly AS3Settings as3settings; + bool hasAIRSupport; + bool hasMobileSupport; + MxmlFilterContext mxmlFilterContext; // extract inlined AS3 ranges & MXML tags + readonly Timer timerCheck; + string fileWithSquiggles; protected bool mxmlEnabled; /// @@ -81,7 +185,7 @@ public Context(AS3Settings initSettings) features.checkFileName = true; // allowed declarations access modifiers - Visibility all = Visibility.Public | Visibility.Internal | Visibility.Protected | Visibility.Private; + const Visibility all = Visibility.Public | Visibility.Internal | Visibility.Protected | Visibility.Private; features.classModifiers = all; features.varModifiers = all; features.constModifiers = all; @@ -93,19 +197,21 @@ public Context(AS3Settings initSettings) features.methodModifierDefault = Visibility.Internal; // keywords + features.ClassKey = "class"; + features.InterfaceKey = "interface"; + features.PackageKey = "package"; + features.ExtendsKey = "extends"; + features.ImplementsKey = "implements"; features.dot = "."; features.voidKey = "void"; features.objectKey = "Object"; features.booleanKey = "Boolean"; features.numberKey = "Number"; + features.IntegerKey = "int"; + features.stringKey = "String"; features.arrayKey = "Array"; + features.dynamicKey = "*"; features.importKey = "import"; - features.typesPreKeys = new string[] { "import", "new", "typeof", "is", "as", "extends", "implements" }; - features.codeKeywords = new string[] { - "class", "interface", "var", "function", "const", "new", "delete", "typeof", "is", "as", "return", - "break", "continue", "if", "else", "for", "each", "in", "while", "do", "switch", "case", "default", "with", - "null", "true", "false", "try", "catch", "finally", "throw", "use", "namespace" - }; features.varKey = "var"; features.constKey = "const"; features.functionKey = "function"; @@ -120,37 +226,56 @@ public Context(AS3Settings initSettings) features.privateKey = "private"; features.intrinsicKey = "extern"; features.namespaceKey = "namespace"; - - /* INITIALIZATION */ + features.ThisKey = "this"; + features.BaseKey = "super"; + features.ReturnKey = "return"; + features.typesPreKeys = new[] { features.importKey, "new", "typeof", "instanceof", "is", "as", features.ExtendsKey, features.ImplementsKey }; + features.codeKeywords = new[] { + "var", "function", "const", "new", "delete", "typeof", "is", "as", features.ReturnKey, + "break", "continue", "if", "else", "for", "each", "in", "while", "do", "switch", "case", "default", "with", + "null", "true", "false", "try", "catch", "finally", "throw", "use", "namespace", "instanceof", + }; + features.accessKeywords = new[] {"native", "dynamic", "final", "public", "private", "protected", "internal", "static", "override"}; + features.declKeywords = new[] {features.varKey, features.functionKey, features.constKey, features.namespaceKey, features.getKey, features.setKey}; + features.typesKeywords = new[] {features.importKey, features.ClassKey, features.InterfaceKey}; + features.ArithmeticOperators = new HashSet {'+', '-', '*', '/', '%'}; + features.IncrementDecrementOperators = new[] {"++", "--"}; + features.BitwiseOperators = new[] {"~", "&", "|", "^", "<<", ">>", ">>>"}; + features.BooleanOperators = new[] {"<", ">", "&&", "||", "!=", "==", "!==", "===", "!"}; + features.TernaryOperators = new[] {"?", ":"}; + features.Literals = new HashSet {"int", "uint"}; + features.OperatorKeywords = new HashSet + { + "case", + "in", + "throw", + "typeof", + "delete", + }; settings = initSettings; - //BuildClassPath(); // defered to first use + CodeComplete = new CodeComplete(); // live syntax checking - timerCheck = new Timer(500); - timerCheck.SynchronizingObject = PluginBase.MainForm as System.Windows.Forms.Form; - timerCheck.AutoReset = false; - timerCheck.Elapsed += new ElapsedEventHandler(timerCheck_Elapsed); - FlexShells.SyntaxError += new SyntaxErrorHandler(FlexShell_SyntaxError); + timerCheck = new Timer(500) {SynchronizingObject = PluginBase.MainForm as Form, AutoReset = false}; + timerCheck.Elapsed += timerCheck_Elapsed; + FlexShells.SyntaxError += FlexShell_SyntaxError; } #endregion #region classpath management /// - /// Classpathes & classes cache initialisation + /// Classpathes & classes cache initialization /// public override void BuildClassPath() { ReleaseClasspath(); started = true; - if (as3settings == null) throw new Exception("BuildClassPath() must be overridden"); - if (contextSetup == null) + if (as3settings is null) throw new Exception("BuildClassPath() must be overridden"); + contextSetup ??= new ContextSetupInfos { - contextSetup = new ContextSetupInfos(); - contextSetup.Lang = settings.LanguageId; - contextSetup.Platform = "Flash Player"; - contextSetup.Version = as3settings.DefaultFlashVersion; - } + Lang = settings.LanguageId, Platform = "Flash Player", Version = as3settings.DefaultFlashVersion + }; // external version definition platform = contextSetup.Platform; @@ -160,8 +285,9 @@ public override void BuildClassPath() hasAIRSupport = platform == "AIR" || platform == "AIR Mobile"; hasMobileSupport = platform == "AIR Mobile"; - string cpCheck = contextSetup.Classpath != null ? - String.Join(";", contextSetup.Classpath).Replace('\\', '/') : ""; + var cpCheck = contextSetup.Classpath != null + ? string.Join(";", contextSetup.Classpath).Replace('\\', '/') + : ""; // check if CP contains a custom playerglobal.swc bool hasCustomAPI = re_customAPI.IsMatch(cpCheck); @@ -179,22 +305,21 @@ public override void BuildClassPath() : as3settings.GetDefaultSDK().Path; char S = Path.DirectorySeparatorChar; - if (compiler == null) - compiler = Path.Combine(PathHelper.ToolDir, "flexlibs"); + compiler ??= Path.Combine(PathHelper.ToolDir, "flexlibs"); string frameworks = compiler + S + "frameworks"; string sdkLibs = frameworks + S + "libs"; - string sdkLocales = frameworks + S + "locale" + S + PluginBase.MainForm.Settings.LocaleVersion; + string sdkLocales = frameworks + S + "locale" + S + PluginBase.Settings.LocaleVersion; string fallbackLibs = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "libs"); string fallbackLocale = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "locale" + S + "en_US"); List addLibs = new List(); List addLocales = new List(); - if (!Directory.Exists(sdkLibs) && !sdkLibs.StartsWith("$")) // fallback + if (!Directory.Exists(sdkLibs) && !sdkLibs.StartsWith('$')) // fallback { sdkLibs = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "libs" + S + "player"); } - if (majorVersion > 0 && !String.IsNullOrEmpty(sdkLibs) && Directory.Exists(sdkLibs)) + if (majorVersion > 0 && Directory.Exists(sdkLibs)) { // core API SWC if (!hasCustomAPI) @@ -206,16 +331,16 @@ public override void BuildClassPath() } else { - bool swcPresent = false; - string playerglobal = MatchPlayerGlobalExact(majorVersion, minorVersion, sdkLibs); + var swcPresent = false; + var playerglobal = MatchPlayerGlobalExact(majorVersion, minorVersion, sdkLibs); if (playerglobal != null) swcPresent = true; else playerglobal = MatchPlayerGlobalExact(majorVersion, minorVersion, fallbackLibs); - if (playerglobal == null) playerglobal = MatchPlayerGlobalAny(ref majorVersion, ref minorVersion, fallbackLibs); - if (playerglobal == null) playerglobal = MatchPlayerGlobalAny(ref majorVersion, ref minorVersion, sdkLibs); + playerglobal ??= MatchPlayerGlobalAny(ref majorVersion, ref minorVersion, fallbackLibs) + ?? MatchPlayerGlobalAny(ref majorVersion, ref minorVersion, sdkLibs); if (playerglobal != null) { // add missing SWC in new SDKs - if (!swcPresent && sdkLibs.IndexOf(S + "flexlibs") < 0 && Directory.Exists(compiler)) + if (!swcPresent && !sdkLibs.Contains(S + "flexlibs") && Directory.Exists(compiler)) { string swcDir = sdkLibs + S + "player" + S; if (!Directory.Exists(swcDir + "9") && !Directory.Exists(swcDir + "10")) @@ -250,16 +375,21 @@ public override void BuildClassPath() // Flex framework if (cpCheck.IndexOf("Library/AS3/frameworks/Flex", StringComparison.OrdinalIgnoreCase) >= 0) { - addLibs.Add("framework.swc"); - addLibs.Add("mx/mx.swc"); - addLibs.Add("rpc.swc"); - addLibs.Add("datavisualization.swc"); - addLibs.Add("flash-integration.swc"); - addLocales.Add("framework_rb.swc"); - addLocales.Add("mx_rb.swc"); - addLocales.Add("rpc_rb.swc"); - addLocales.Add("datavisualization_rb.swc"); - addLocales.Add("flash-integration_rb.swc"); + bool isFlexJS = cpCheck.IndexOf("Library/AS3/frameworks/FlexJS", StringComparison.OrdinalIgnoreCase) >= 0; + + if (!isFlexJS) + { + addLibs.Add("framework.swc"); + addLibs.Add("mx/mx.swc"); + addLibs.Add("rpc.swc"); + addLibs.Add("datavisualization.swc"); + addLibs.Add("flash-integration.swc"); + addLocales.Add("framework_rb.swc"); + addLocales.Add("mx_rb.swc"); + addLocales.Add("rpc_rb.swc"); + addLocales.Add("datavisualization_rb.swc"); + addLocales.Add("flash-integration_rb.swc"); + } if (hasAIRSupport) { @@ -267,7 +397,14 @@ public override void BuildClassPath() addLocales.Add("airframework_rb.swc"); } - if (cpCheck.IndexOf("Library/AS3/frameworks/Flex4", StringComparison.OrdinalIgnoreCase) >= 0) + if (isFlexJS) + { + string flexJsLibs = frameworks + S + "as" + S + "libs"; + addLibs.Add(flexJsLibs + S + "FlexJSUI.swc"); + //addLibs.Add(flexJsLibs + S + "FlexJSJX.swc"); + MxmlFilter.AddManifest("http://ns.adobe.com/mxml/2009", as3Fmk + S + "FlexJS" + S + "manifest.xml"); + } + else if (cpCheck.IndexOf("Library/AS3/frameworks/Flex4", StringComparison.OrdinalIgnoreCase) >= 0) { addLibs.Add("spark.swc"); addLibs.Add("spark_dmv.swc"); @@ -312,17 +449,14 @@ public override void BuildClassPath() } // intrinsics (deprecated, excepted for FP10 Vector.) - string fp9cp = as3settings.AS3ClassPath + S + "FP9"; - AddPath(PathHelper.ResolvePath(fp9cp)); - if (majorVersion > 9) + // add from the highest version number (FP11 > FP10 > FP9) + string fp = as3settings.AS3ClassPath + S + "FP"; + for (int i = majorVersion; i >= 9; i--) { - string fp10cp = as3settings.AS3ClassPath + S + "FP" + majorVersion; - AddPath(PathHelper.ResolvePath(fp10cp)); - string fp101cp = as3settings.AS3ClassPath + S + "FP" + majorVersion + "." + minorVersion; - AddPath(PathHelper.ResolvePath(fp101cp)); + AddPath(PathHelper.ResolvePath(fp + i)); } - // add external pathes + // add external paths List initCP = classPath; classPath = new List(); if (contextSetup.Classpath != null) @@ -333,20 +467,20 @@ public override void BuildClassPath() // add library AddPath(PathHelper.LibraryDir + S + "AS3" + S + "classes"); - // add user pathes from settings - if (settings.UserClasspath != null && settings.UserClasspath.Length > 0) + // add user paths from settings + if (!settings.UserClasspath.IsNullOrEmpty()) { foreach (string cpath in settings.UserClasspath) AddPath(cpath.Trim()); } - // add initial pathes + // add initial paths foreach (PathModel mpath in initCP) AddPath(mpath); // parse top-level elements InitTopLevelElements(); if (cFile != null) UpdateTopLevelElements(); - // add current temporaty path + // add current temporary path if (temporaryPath != null) { string tempPath = temporaryPath; @@ -359,11 +493,10 @@ public override void BuildClassPath() /// /// Find any playerglobal.swc /// - private string MatchPlayerGlobalAny(ref int majorVersion, ref int minorVersion, string sdkLibs) + string MatchPlayerGlobalAny(ref int majorVersion, ref int minorVersion, string sdkLibs) { char S = Path.DirectorySeparatorChar; string libPlayer = sdkLibs + S + "player"; - string playerglobal = null; for (int i = minorVersion; i >= 0; i--) { string version = majorVersion + "." + i; @@ -373,10 +506,11 @@ private string MatchPlayerGlobalAny(ref int majorVersion, ref int minorVersion, return libPlayer + S + version + S + "playerglobal.swc"; } } - if (playerglobal == null && Directory.Exists(libPlayer + S + majorVersion)) + string playerglobal = null; + if (Directory.Exists(libPlayer + S + majorVersion)) playerglobal = "player" + S + majorVersion + S + "playerglobal.swc"; - if (playerglobal == null && majorVersion > 9) + if (playerglobal is null && majorVersion > 9) { int tempMajor = majorVersion - 1; int tempMinor = 9; @@ -395,7 +529,7 @@ private string MatchPlayerGlobalAny(ref int majorVersion, ref int minorVersion, /// /// Find version-matching playerglobal.swc /// - private string MatchPlayerGlobalExact(int majorVersion, int minorVersion, string sdkLibs) + string MatchPlayerGlobalExact(int majorVersion, int minorVersion, string sdkLibs) { string playerglobal = null; char S = Path.DirectorySeparatorChar; @@ -412,25 +546,22 @@ private string MatchPlayerGlobalExact(int majorVersion, int minorVersion, string /// public override string[] GetExplorerMask() { - string[] mask = as3settings.AS3FileTypes; - if (mask == null || mask.Length == 0 || (mask.Length == 1 && mask[1] == "")) + var mask = as3settings.AS3FileTypes; + if (mask.IsNullOrEmpty() || (mask.Length == 1 && mask[0] == "")) { - as3settings.AS3FileTypes = mask = new string[] { "*.as", "*.mxml" }; + as3settings.AS3FileTypes = mask = new[] { "*.as", "*.mxml" }; return mask; } - else + var patterns = new List(); + foreach (var it in mask) { - List patterns = new List(); - for (int i = 0; i < mask.Length; i++) - { - string m = mask[i]; - if (string.IsNullOrEmpty(m)) continue; - if (m[1] != '.' && m[0] != '.') m = '.' + m; - if (m[0] != '*') m = '*' + m; - patterns.Add(m); - } - return patterns.ToArray(); + string m = it; + if (string.IsNullOrEmpty(m)) continue; + if (m[1] != '.' && m[0] != '.') m = '.' + m; + if (m[0] != '*') m = '*' + m; + patterns.Add(m); } + return patterns.ToArray(); } /// @@ -456,7 +587,7 @@ public override void ExploreVirtualPath(PathModel path) lock (path) { path.WasExplored = true; - SwfOp.ContentParser parser = new SwfOp.ContentParser(path.Path); + ContentParser parser = new ContentParser(path.Path); parser.Run(); AbcConverter.Convert(parser, path, this); } @@ -483,30 +614,29 @@ public override void ExploreVirtualPath(PathModel path) public override void RemoveClassCompilerCache() { // not implemented - is there any? - } - - /// - /// Create a new file model without parsing file - /// - /// Full path - /// File model - public override FileModel CreateFileModel(string fileName) - { - if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName)) - return new FileModel(fileName); - - fileName = PathHelper.GetLongPathName(fileName); - if (mxmlEnabled && fileName.EndsWith(".mxml", StringComparison.OrdinalIgnoreCase)) - { - FileModel nFile = new FileModel(fileName); - nFile.Context = this; - nFile.HasFiltering = true; - return nFile; - } - else return base.CreateFileModel(fileName); } - private void GuessPackage(string fileName, FileModel nFile) + /// + /// Create a new file model without parsing file + /// + /// Full path + /// File model + public override FileModel CreateFileModel(string fileName) + { + if (!File.Exists(fileName)) return new FileModel(fileName); + fileName = PathHelper.GetLongPathName(fileName); + if (mxmlEnabled && fileName.EndsWith(".mxml", StringComparison.OrdinalIgnoreCase)) + { + FileModel nFile = new FileModel(fileName); + nFile.Context = this; + nFile.HasFiltering = true; + return nFile; + } + + return base.CreateFileModel(fileName); + } + + void GuessPackage(string fileName, FileModel nFile) { foreach(PathModel aPath in classPath) if (fileName.StartsWith(aPath.Path, StringComparison.OrdinalIgnoreCase)) @@ -519,15 +649,6 @@ private void GuessPackage(string fileName, FileModel nFile) } } - /// - /// Build the file DOM - /// - /// File path - protected override void GetCurrentFileModel(string fileName) - { - base.GetCurrentFileModel(fileName); - } - /// /// Refresh the file model /// @@ -546,16 +667,6 @@ public override void UpdateCurrentFile(bool updateUI) } } - /// - /// Update the class/member context for the given line number. - /// Be carefull to restore the context after calling it with a custom line number - /// - /// - public override void UpdateContext(int line) - { - base.UpdateContext(line); - } - /// /// Called if a FileModel needs filtering /// - define inline AS3 ranges @@ -586,11 +697,12 @@ public override void FilterSource(FileModel model) internal void OnFileOperation(NotifyEvent e) { timerCheck.Stop(); - foreach (ITabbedDocument doc in PluginBase.MainForm.Documents) - if (doc.FileName == fileWithSquiggles) ClearSquiggles(doc.SciControl); + foreach (var doc in PluginBase.MainForm.Documents) + if (doc.SciControl is { } sci && sci.FileName == fileWithSquiggles) + ClearSquiggles(sci); } - public override void TrackTextChange(ScintillaNet.ScintillaControl sender, int position, int length, int linesAdded) + public override void TrackTextChange(ScintillaControl sender, int position, int length, int linesAdded) { base.TrackTextChange(sender, position, length, linesAdded); if (as3settings != null && !as3settings.DisableLiveChecking && IsFileValid) @@ -600,39 +712,39 @@ public override void TrackTextChange(ScintillaNet.ScintillaControl sender, int p } } - private void timerCheck_Elapsed(object sender, ElapsedEventArgs e) - { - BackgroundSyntaxCheck(); - } + void timerCheck_Elapsed(object sender, ElapsedEventArgs e) => BackgroundSyntaxCheck(); /// /// Checking syntax of current file /// - private void BackgroundSyntaxCheck() + void BackgroundSyntaxCheck() { if (!IsFileValid) return; - ScintillaNet.ScintillaControl sci = CurSciControl; - if (sci == null) return; + var sci = PluginBase.MainForm.CurrentDocument?.SciControl; + if (sci is null) return; ClearSquiggles(sci); - string src = CurSciControl.Text; - string sdk = PluginBase.CurrentProject != null && PluginBase.CurrentProject.Language == "as3" + var sdk = PluginBase.CurrentProject != null && PluginBase.CurrentProject.Language == "as3" ? PluginBase.CurrentProject.CurrentSDK : as3settings.GetDefaultSDK().Path; - FlexShells.Instance.CheckAS3(CurrentFile, sdk, src); + FlexShells.Instance.CheckAS3(CurrentFile, sdk, sci.Text); + } + + void AddSquiggles(ScintillaControl sci, int line, int start, int end) + { + if (sci is null) return; + fileWithSquiggles = CurrentFile; + int position = sci.PositionFromLine(line) + start; + sci.AddHighlight(2, (int)IndicatorStyle.Squiggle, 0x000000ff, position, end - start); } - private void ClearSquiggles(ScintillaNet.ScintillaControl sci) + void ClearSquiggles(ScintillaControl sci) { - if (sci == null) return; + if (sci is null) return; try { - int es = sci.EndStyled; - int mask = (1 << sci.StyleBits); - sci.StartStyling(0, mask); - sci.SetStyling(sci.TextLength, 0); - sci.StartStyling(es, mask - 1); + sci.RemoveHighlights(2); } finally { @@ -640,26 +752,25 @@ private void ClearSquiggles(ScintillaNet.ScintillaControl sci) } } - private void FlexShell_SyntaxError(string error) + void FlexShell_SyntaxError(string error) { if (!IsFileValid) return; - Match m = re_syntaxError.Match(error); + var document = PluginBase.MainForm.CurrentDocument; + if (document is null || !document.IsEditable) return; + var m = re_syntaxError.Match(error); if (!m.Success) return; - ITabbedDocument document = PluginBase.MainForm.CurrentDocument; - if (document == null || !document.IsEditable) return; - - ScintillaNet.ScintillaControl sci = document.SplitSci1; - ScintillaNet.ScintillaControl sci2 = document.SplitSci2; + var sci1 = document.SplitSci1; + var sci2 = document.SplitSci2; if (m.Groups["filename"].Value != CurrentFile) return; try { int line = int.Parse(m.Groups["line"].Value) - 1; - if (sci.LineCount < line) return; - int start = MBSafeColumn(sci, line, int.Parse(m.Groups["col"].Value) - 1); - if (line == sci.LineCount && start == 0 && line > 0) start = -1; - AddSquiggles(sci, line, start, start + 1); + if (sci1.LineCount < line) return; + int start = MBSafeColumn(sci1, line, int.Parse(m.Groups["col"].Value) - 1); + if (line == sci1.LineCount && start == 0 && line > 0) start = -1; + AddSquiggles(sci1, line, start, start + 1); AddSquiggles(sci2, line, start, start + 1); } catch { } @@ -668,26 +779,13 @@ private void FlexShell_SyntaxError(string error) /// /// Convert multibyte column to byte length /// - private int MBSafeColumn(ScintillaNet.ScintillaControl sci, int line, int length) + static int MBSafeColumn(ScintillaControl sci, int line, int length) { - String text = sci.GetLine(line) ?? ""; + var text = sci.GetLine(line) ?? ""; length = Math.Min(length, text.Length); return sci.MBSafeTextLength(text.Substring(0, length)); } - private void AddSquiggles(ScintillaNet.ScintillaControl sci, int line, int start, int end) - { - if (sci == null) return; - fileWithSquiggles = CurrentFile; - int position = sci.PositionFromLine(line) + start; - int es = sci.EndStyled; - int mask = 1 << sci.StyleBits; - sci.SetIndicStyle(0, (int)ScintillaNet.Enums.IndicatorStyle.Squiggle); - sci.SetIndicFore(0, 0x000000ff); - sci.StartStyling(position, mask); - sci.SetStyling(end - start, mask); - sci.StartStyling(es, mask - 1); - } #endregion #region class resolution @@ -700,27 +798,27 @@ private void AddSquiggles(ScintillaNet.ScintillaControl sci, int line, int start /// Completion visibility public override Visibility TypesAffinity(ClassModel inClass, ClassModel withClass) { - if (inClass == null || withClass == null) return Visibility.Public; + if (inClass is null || withClass is null) return Visibility.Public; // same file if (inClass.InFile == withClass.InFile) return Visibility.Public | Visibility.Internal | Visibility.Protected | Visibility.Private; // same package - Visibility acc = Visibility.Public; - if (inClass.InFile.Package == withClass.InFile.Package) acc |= Visibility.Internal; + var result = Visibility.Public; + if (inClass.InFile.Package == withClass.InFile.Package) result |= Visibility.Internal; // inheritance affinity - ClassModel tmp = inClass; + var tmp = inClass; while (!tmp.IsVoid()) { if (tmp.Type == withClass.Type) { - acc |= Visibility.Protected; + result |= Visibility.Protected; break; } tmp = tmp.Extends; } - return acc; + return result; } /// @@ -733,49 +831,49 @@ public override MemberList GetAllProjectClasses() if (!completionCache.IsDirty && completionCache.AllTypes != null) return completionCache.AllTypes; - MemberList fullList = new MemberList(); + var fullList = new MemberList(); ClassModel aClass; MemberModel item; // public & internal classes - string package = CurrentModel.Package; - foreach (PathModel aPath in classPath) if (aPath.IsValid && !aPath.Updating) - { - aPath.ForeachFile((aFile) => + string package = CurrentModel?.Package; + foreach (var aPath in classPath) + if (aPath.IsValid && !aPath.Updating) { - if (!aFile.HasPackage) - return true; // skip - - aClass = aFile.GetPublicClass(); - if (!aClass.IsVoid() && aClass.IndexType == null) + aPath.ForeachFile((aFile) => { - if (aClass.Access == Visibility.Public - || (aClass.Access == Visibility.Internal && aFile.Package == package)) + if (!aFile.HasPackage) + return true; // skip + + aClass = aFile.GetPublicClass(); + if (!aClass.IsVoid() && aClass.IndexType is null) { - item = aClass.ToMemberModel(); - item.Name = item.Type; - fullList.Add(item); + if (aClass.Access == Visibility.Public + || (aClass.Access == Visibility.Internal && aFile.Package == package)) + { + item = aClass.ToMemberModel(); + item.Name = item.Type; + fullList.Add(item); + } } - } - if (aFile.Package.Length > 0 && aFile.Members.Count > 0) - { - foreach (MemberModel member in aFile.Members) + if (aFile.Package.Length > 0 && aFile.Members.Count > 0) { - item = member.Clone() as MemberModel; - item.Name = aFile.Package + "." + item.Name; - fullList.Add(item); + foreach (var member in aFile.Members) + { + item = member.Clone(); + item.Name = aFile.Package + "." + item.Name; + fullList.Add(item); + } } - } - else if (aFile.Members.Count > 0) - { - foreach (MemberModel member in aFile.Members) + else if (aFile.Members.Count > 0) { - item = member.Clone() as MemberModel; - fullList.Add(item); + foreach (var member in aFile.Members) + { + fullList.Add(member.Clone()); + } } - } - return true; - }); - } + return true; + }); + } // void fullList.Add(new MemberModel(features.voidKey, features.voidKey, FlagType.Class | FlagType.Intrinsic, 0)); // private classes @@ -787,59 +885,43 @@ public override MemberList GetAllProjectClasses() return fullList; } - public override bool OnCompletionInsert(ScintillaNet.ScintillaControl sci, int position, string text, char trigger) + public override bool OnCompletionInsert(ScintillaControl sci, int position, string text, char trigger) { - if (text == "Vector") + if (text != "Vector") return text.StartsWithOrdinal("Vector.<"); + string insert = null; + var line = sci.GetLine(sci.LineFromPosition(position)); + var m = Regex.Match(line, @"\s*=\s*new"); + if (m.Success) { - string insert = null; - string line = sci.GetLine(sci.LineFromPosition(position)); - Match m = Regex.Match(line, @"\svar\s+(?.+)\s*:\s*Vector\.<(?.+)(?=(>\s*=))"); - if (m.Success) - { - insert = String.Format(".<{0}>", m.Groups["indextype"].Value); - } - else - { - m = Regex.Match(line, @"\s*=\s*new"); - if (m.Success) - { - ASResult result = ASComplete.GetExpressionType(sci, sci.PositionFromLine(sci.LineFromPosition(position)) + m.Index); - if (result != null && !result.IsNull() && result.Member != null && result.Member.Type != null) - { - m = Regex.Match(result.Member.Type, @"(?<=<).+(?=>)"); - if (m.Success) - { - insert = String.Format(".<{0}>", m.Value); - } - } - } - if (insert == null) - { - if (trigger == '.' || trigger == '(') return true; - insert = ".<>"; - sci.InsertText(position + text.Length, insert); - sci.CurrentPos = position + text.Length + 2; - sci.SetSel(sci.CurrentPos, sci.CurrentPos); - ASComplete.HandleAllClassesCompletion(sci, "", false, true); - return true; - } - } - if (insert == null) return false; - if (trigger == '.') + var result = ASComplete.GetExpressionType(sci, sci.PositionFromLine(sci.LineFromPosition(position)) + m.Index); + if (result != null && !result.IsNull() && result.Member?.Type != null) { - sci.InsertText(position + text.Length, insert.Substring(1)); - sci.CurrentPos = position + text.Length; - } - else - { - sci.InsertText(position + text.Length, insert); - sci.CurrentPos = position + text.Length + insert.Length; + m = Regex.Match(result.Member.Type, @"(?<=<).+(?=>)"); + if (m.Success) insert = $".<{m.Value}>"; } + } + if (insert is null) + { + if (trigger == '.' || trigger == '(') return true; + insert = ".<>"; + sci.InsertText(position + text.Length, insert); + sci.CurrentPos = position + text.Length + 2; sci.SetSel(sci.CurrentPos, sci.CurrentPos); + ASComplete.HandleAllClassesCompletion(sci, "", false, true); return true; } - - return false; + if (trigger == '.') + { + sci.InsertText(position + text.Length, insert.Substring(1)); + sci.CurrentPos = position + text.Length; + } + else + { + sci.InsertText(position + text.Length, insert); + sci.CurrentPos = position + text.Length + insert.Length; + } + sci.SetSel(sci.CurrentPos, sci.CurrentPos); + return true; } /// @@ -851,74 +933,142 @@ public override bool OnCompletionInsert(ScintillaNet.ScintillaControl sci, int p /// Position in the file public override bool IsImported(MemberModel member, int atLine) { - FileModel cFile = ASContext.Context.CurrentModel; - // same package is auto-imported - string package = member.Type.Length > member.Name.Length + if (member == ClassModel.VoidClass) return false; + var package = member.InFile?.Package; + if (string.IsNullOrEmpty(package)) package = null; + package ??= member.Type.Length > member.Name.Length ? member.Type.Substring(0, member.Type.Length - member.Name.Length - 1) - : ""; - if (package == cFile.Package) return true; - return base.IsImported(member, atLine); + : string.Empty; + if (package == "globalClassifier") return true; + // same package is auto-imported + return package == Context.CurrentModel.Package || base.IsImported(member, atLine); } /// /// Retrieves a class model from its name /// /// Class (short or full) name - /// Current file + /// Current file /// A parsed class or an empty ClassModel if the class is not found public override ClassModel ResolveType(string cname, FileModel inFile) { // handle generic types - if (cname != null && cname.IndexOf('<') > 0) + if (!string.IsNullOrEmpty(cname)) { - Match genType = re_genericType.Match(cname); - if (genType.Success) - return ResolveGenericType(genType.Groups["gen"].Value, genType.Groups["type"].Value, inFile); - else return ClassModel.VoidClass; + var index = cname.IndexOf('<'); + if (index != -1) + { + if (index == 0) + { + // transform [] to Vector. + cname = Regex.Replace(cname, @">\[.*", ">"); + cname = "Vector." + cname; + } + // transform Vector to Vector. + if (cname.Contains("Vector<")) cname = cname.Replace("Vector<", "Vector.<"); + var genType = re_genericType.Match(cname); + return genType.Success + ? ResolveGenericType(genType.Groups["gen"].Value, genType.Groups["type"].Value, inFile) + : ClassModel.VoidClass; + } } return base.ResolveType(cname, inFile); } + static readonly Regex re_asExpr = new Regex(@"\((?.+)\s(?as)\s+(?\w+)\)"); + static readonly Regex re_isExpr = new Regex(@"\((?.+)\s(?is)\s+(?\w+)\)"); + + public override ClassModel ResolveToken(string token, FileModel inFile) + { + var tokenLength = token?.Length ?? 0; + if (tokenLength > 0) + { + if (token.StartsWithOrdinal("0x")) return ResolveType("uint", inFile); + var first = token[0]; + if (first == '<' && tokenLength >= 3 && token[tokenLength - 2] == '/' && token[tokenLength - 1] == '>') return ResolveType("XML", inFile); + if (first == '(' && token[token.Length - 1] == ')') + { + if (re_isExpr.IsMatch(token)) return ResolveType(features.booleanKey, inFile); + var m = re_asExpr.Match(token); + if (m.Success) return ResolveType(m.Groups["rv"].Value.Trim(), inFile); + } + if (char.IsLetter(first)) + { + var index = token.IndexOf(' '); + if (index != -1) + { + var word = token.Substring(0, index); + if (word == "new") + { + var dot = ' '; + var parCount = 0; + for (var i = 0; i < tokenLength; i++) + { + var c = token[i]; + if (c == '(') parCount++; + else if (c == ')') + { + parCount--; + if (parCount == 0) dot = '.'; + } + else if (dot != ' ' && c == dot) return ClassModel.VoidClass; + } + token = token.Substring(index + 1); + if (token[token.Length - 1] == ')') token = Regex.Replace(token, @"\(.*", string.Empty); + return ResolveType(token, inFile); + } + } + } + } + return base.ResolveToken(token, inFile); + } + /// /// Retrieve/build typed copies of generic types /// - private ClassModel ResolveGenericType(string baseType, string indexType, FileModel inFile) + ClassModel ResolveGenericType(string baseType, string indexType, FileModel inFile) { - ClassModel originalClass = base.ResolveType(baseType, inFile); + var originalClass = base.ResolveType(baseType, inFile); if (originalClass.IsVoid()) return originalClass; + if (indexType == "*") + { + originalClass.IndexType = "*"; + return originalClass; + } - ClassModel indexClass = ResolveType(indexType, inFile); + var indexClass = ResolveType(indexType, inFile); if (indexClass.IsVoid()) return originalClass; indexType = indexClass.QualifiedName; FileModel aFile = originalClass.InFile; // is the type already cloned? - foreach (ClassModel otherClass in aFile.Classes) + foreach (var otherClass in aFile.Classes) if (otherClass.IndexType == indexType) return otherClass; // clone the type - ClassModel aClass = originalClass.Clone() as ClassModel; - + var aClass = originalClass.Clone(); aClass.Name = baseType + ".<" + indexType + ">"; aClass.IndexType = indexType; string typed = "<" + indexType + ">"; - foreach (MemberModel member in aClass.Members) + foreach (var member in aClass.Members) { if (member.Name == baseType) member.Name = baseType.Replace("", typed); - if (member.Type != null && member.Type.IndexOf('T') >= 0) + if (member.Type != null && member.Type.Contains('T')) { - if (member.Type == "T") member.Type = indexType; - else member.Type = member.Type.Replace("", typed); + member.Type = member.Type == "T" + ? indexType + : member.Type.Replace("", typed); } if (member.Parameters != null) { - foreach (MemberModel param in member.Parameters) + foreach (var param in member.Parameters) { - if (param.Type != null && param.Type.IndexOf('T') >= 0) + if (param.Type != null && param.Type.Contains('T')) { - if (param.Type == "T") param.Type = indexType; - else param.Type = param.Type.Replace("", typed); + param.Type = param.Type == "T" + ? indexType + : param.Type.Replace("", typed); } } } @@ -930,19 +1080,20 @@ private ClassModel ResolveGenericType(string baseType, string indexType, FileMod protected MemberList GetPrivateClasses() { - MemberList list = new MemberList(); + var list = new MemberList(); // private classes - foreach(ClassModel model in cFile.Classes) - if (model.Access == Visibility.Private) - { - MemberModel item = model.ToMemberModel(); - item.Type = item.Name; - item.Access = Visibility.Private; - list.Add(item); - } + if (cFile != null) + foreach (var model in cFile.Classes) + if (model.Access == Visibility.Private) + { + var item = model.ToMemberModel(); + item.Type = item.Name; + item.Access = Visibility.Private; + list.Add(item); + } // 'Class' members if (cClass != null) - foreach (MemberModel member in cClass.Members) + foreach (var member in cClass.Members) if (member.Type == "Class") list.Add(member); return list; } @@ -952,18 +1103,60 @@ protected MemberList GetPrivateClasses() /// protected override void InitTopLevelElements() { - string filename = "toplevel.as"; + const string filename = "toplevel.as"; topLevel = new FileModel(filename); - - if (topLevel.Members.Search("this", 0, 0) == null) - topLevel.Members.Add(new MemberModel("this", "", FlagType.Variable | FlagType.Intrinsic, Visibility.Public)); - if (topLevel.Members.Search("super", 0, 0) == null) - topLevel.Members.Add(new MemberModel("super", "", FlagType.Variable | FlagType.Intrinsic, Visibility.Public)); - if (topLevel.Members.Search(features.voidKey, 0, 0) == null) - topLevel.Members.Add(new MemberModel(features.voidKey, "", FlagType.Intrinsic, Visibility.Public)); + if (!topLevel.Members.Contains(features.ThisKey)) topLevel.Members.Add(new MemberModel(features.ThisKey, string.Empty, FlagType.Variable | FlagType.Intrinsic, Visibility.Public)); + if (!topLevel.Members.Contains(features.BaseKey)) topLevel.Members.Add(new MemberModel(features.BaseKey, string.Empty, FlagType.Variable | FlagType.Intrinsic, Visibility.Public)); + if (!topLevel.Members.Contains(features.voidKey)) topLevel.Members.Add(new MemberModel(features.voidKey, string.Empty, FlagType.Intrinsic, Visibility.Public)); topLevel.Members.Sort(); } + public override string GetDefaultValue(string type) + { + if (string.IsNullOrEmpty(type) || type == features.voidKey) return null; + if (type == features.dynamicKey) return "undefined"; + return type switch + { + "int" => "0", + "uint" => "0", + "Number" => "NaN", + "Boolean" => "false", + _ => "null", + }; + } + + public override IEnumerable DecomposeTypes(IEnumerable types) + { + var characterClass = ScintillaControl.Configuration.GetLanguage("as3").characterclass.Characters; + var result = new HashSet(); + foreach (var type in types) + { + if (string.IsNullOrEmpty(type)) result.Add("*"); + else if (type.Contains("<")) + { + var length = type.Length; + var pos = 0; + for (var i = 0; i < length; i++) + { + var c = type[i]; + if (c == '.' || characterClass.Contains(c)) continue; + if (c == '<') + { + result.Add(type.Substring(pos, i - pos - 1)); + pos = i + 1; + } + else if (c == '>') + { + result.Add(type.Substring(pos, i - pos)); + break; + } + } + } + else result.Add(type); + } + return result; + } + #endregion #region Command line compiler @@ -971,25 +1164,19 @@ protected override void InitTopLevelElements() /// /// Retrieve the context's default compiler path /// - public override string GetCompilerPath() - { - return as3settings.GetDefaultSDK().Path ?? "Tools\\flexsdk"; - } + public override string GetCompilerPath() => as3settings.GetDefaultSDK().Path ?? "Tools\\flexsdk"; /// /// Check current file's syntax /// public override void CheckSyntax() { - if (IsFileValid && cFile.InlinedIn == null) - { - PluginBase.MainForm.CallCommand("Save", null); - - string sdk = PluginBase.CurrentProject != null - ? PluginBase.CurrentProject.CurrentSDK - : PathHelper.ResolvePath(as3settings.GetDefaultSDK().Path); - FlexShells.Instance.CheckAS3(cFile.FileName, sdk); - } + if (!IsFileValid || cFile.InlinedIn != null) return; + PluginBase.MainForm.CallCommand("Save", null); + var sdk = PluginBase.CurrentProject != null + ? PluginBase.CurrentProject.CurrentSDK + : PathHelper.ResolvePath(as3settings.GetDefaultSDK().Path); + FlexShells.Instance.CheckAS3(cFile.FileName, sdk); } /// @@ -1003,15 +1190,11 @@ public override void RunCMD(string append) MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidClass")); return; } - - string command = (append ?? "") + " -- " + CurrentFile; + var command = (append ?? "") + " -- " + CurrentFile; FlexShells.Instance.RunMxmlc(command, as3settings.GetDefaultSDK().Path); } - private bool IsCompilationTarget() - { - return (!MainForm.CurrentDocument.IsUntitled && CurrentModel.Version >= 3); - } + bool IsCompilationTarget() => (!PluginBase.MainForm.CurrentDocument.IsUntitled && CurrentModel.Version >= 3); /// /// Calls RunCMD with additional parameters taken from the classes @mxmlc doc tag @@ -1023,15 +1206,108 @@ public override bool BuildCMD(bool failSilently) MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidClass")); return false; } - - MainForm.CallCommand("SaveAllModified", null); - - string sdk = PluginBase.CurrentProject != null + PluginBase.MainForm.CallCommand("SaveAllModified", null); + var sdk = PluginBase.CurrentProject != null ? PluginBase.CurrentProject.CurrentSDK : as3settings.GetDefaultSDK().Path; FlexShells.Instance.QuickBuild(CurrentModel, sdk, failSilently, as3settings.PlayAfterBuild); return true; } #endregion + + #region Custom behavior of Scintilla + + /// + public override void OnBraceMatch(ScintillaControl sci) + { + if (!sci.IsBraceMatching || sci.SelTextSize != 0) return; + var position = sci.CurrentPos - 1; + var character = (char) sci.CharAt(position); + if (character != '<' && character != '>') + { + position = sci.CurrentPos; + character = (char) sci.CharAt(position); + } + if (character == '<' || character == '>') + { + if (!sci.PositionIsOnComment(position)) + { + var bracePosStart = position; + var bracePosEnd = BraceMatch(sci, position); + if (bracePosEnd != -1) sci.BraceHighlight(bracePosStart, bracePosEnd); + if (sci.UseHighlightGuides) + { + var line = sci.LineFromPosition(position); + sci.HighlightGuide = sci.GetLineIndentation(line); + } + } + else + { + sci.BraceHighlight(-1, -1); + sci.HighlightGuide = 0; + } + } + } + + /// + /// Find the position of a matching '<' and '>' or INVALID_POSITION if no match. + /// + protected internal int BraceMatch(ScintillaControl sci, int position) + { + if (sci.PositionIsOnComment(position) || sci.PositionIsInString(position)) return -1; + var language = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage); + if (language is null) return -1; + var characters = language.characterclass.Characters; + var sub = 0; + switch (sci.CharAt(position)) + { + case '<': + var length = sci.TextLength; + while (position < length) + { + position++; + if (sci.PositionIsOnComment(position)) continue; + var c = sci.CharAt(position); + if (c == ' ') continue; + if (c == '<') sub++; + else if (c == '>') + { + sub--; + if (sub < 0) return position; + } + else if (c != '.' + // Vector> + && !characters.Contains((char) c)) + { + return -1; + } + } + break; + case '>': + while (position >= 0) + { + position--; + if (sci.PositionIsOnComment(position)) continue; + var c = sci.CharAt(position); + if (c == ' ') continue; + if (c == '>') sub++; + else if (c == '<') + { + sub--; + if (sub < 0) return position; + } + else if (c != '.' + // Vector> + && !characters.Contains((char) c)) + { + return -1; + } + } + break; + } + return -1; + } + + #endregion } -} +} \ No newline at end of file diff --git a/External/Plugins/AS3Context/Controls/ObjectRefsGrid.cs b/External/Plugins/AS3Context/Controls/ObjectRefsGrid.cs index aeec8fad67..d834aa5127 100644 --- a/External/Plugins/AS3Context/Controls/ObjectRefsGrid.cs +++ b/External/Plugins/AS3Context/Controls/ObjectRefsGrid.cs @@ -1,22 +1,20 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Aga.Controls.Tree; +using Aga.Controls.Tree; using Aga.Controls.Tree.NodeControls; using PluginCore; using PluginCore.Helpers; +using System.Drawing; namespace AS3Context.Controls { public class ObjectRefsGrid:TreeViewAdv { - NodeTextBox methodTB; - NodeTextBox fileTB; - NodeTextBox lineTB; + readonly NodeTextBox methodTB; + readonly NodeTextBox fileTB; + readonly NodeTextBox lineTB; public ObjectRefsGrid() { - BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + BorderStyle = System.Windows.Forms.BorderStyle.None; Dock = System.Windows.Forms.DockStyle.Fill; GridLineStyle = GridLineStyle.HorizontalAndVertical; Font = PluginBase.Settings.DefaultFont; @@ -46,15 +44,25 @@ public ObjectRefsGrid() NodeControls.Add(methodTB); NodeControls.Add(fileTB); NodeControls.Add(lineTB); + + this.CustomDrawHeaders = PluginBase.MainForm.GetThemeColor("ColumnHeader.BorderColor") != Color.Empty; + this.ColumnHeaderBackColor = PluginBase.MainForm.GetThemeColor("ColumnHeader.BackColor", SystemColors.Control); + this.ColumnHeaderTextColor = PluginBase.MainForm.GetThemeColor("ColumnHeader.TextColor", SystemColors.ControlText); + this.ColumnHeaderBorderColor = PluginBase.MainForm.GetThemeColor("ColumnHeader.BorderColor", SystemColors.ActiveBorder); + this.LineColor = PluginBase.MainForm.GetThemeColor("DataTreeControl.LineColor", SystemColors.ActiveBorder); + this.LineColor2 = PluginBase.MainForm.GetThemeColor("DataTreeControl.LineColor", SystemColors.ActiveBorder); + this.DragDropMarkColor = PluginBase.MainForm.GetThemeColor("DataTreeControl.ForeColor", SystemColors.WindowText); + this.ForeColor = PluginBase.MainForm.GetThemeColor("TreeViewAdv.ForeColor", SystemColors.ControlText); + this.BackColor = PluginBase.MainForm.GetThemeColor("TreeViewAdv.BackColor", SystemColors.Control); } } public class ObjectRefsNode : Node { - string method; - string path; - string file; - string line; + readonly string method; + readonly string path; + readonly string file; + readonly string line; public ObjectRefsNode(string method, string file, string line) { @@ -66,22 +74,13 @@ public ObjectRefsNode(string method, string file, string line) this.line = line; } - public String Method - { - get { return method; } - } - public String Path - { - get { return path; } - } - public String File - { - get { return file; } - } - public String Line - { - get { return line; } - } + public string Method => method; + + public string Path => path; + + public string File => file; + + public string Line => line; } public class ObjectRefsModel : TreeModel diff --git a/External/Plugins/AS3Context/Controls/ProfilerLiveObjectsView.cs b/External/Plugins/AS3Context/Controls/ProfilerLiveObjectsView.cs index 86aeaddcf4..2229fbcfff 100644 --- a/External/Plugins/AS3Context/Controls/ProfilerLiveObjectsView.cs +++ b/External/Plugins/AS3Context/Controls/ProfilerLiveObjectsView.cs @@ -1,9 +1,9 @@ using System; +using System.Collections; using System.Collections.Generic; -using System.Text; using System.Windows.Forms; -using System.Collections; using PluginCore; +using PluginCore.Localization; namespace AS3Context.Controls { @@ -13,67 +13,62 @@ class ProfilerLiveObjectsView { public event ViewObjectEvent OnViewObject; - ListViewXP listView; - private Dictionary items; - private Dictionary finished = new Dictionary(); - private TypeItemComparer comparer; - private ToolStripMenuItem viewObjectsItem; + Dictionary items; + readonly TypeItemComparer comparer; + readonly ToolStripMenuItem viewObjectsItem; - public ProfilerLiveObjectsView(ListViewXP view) + public ListView ListView { get; } + + public ProfilerLiveObjectsView(ListView view) { // config - listView = view; + ListView = view; comparer = new TypeItemComparer(); comparer.SortColumn = TypeItem.COL_COUNT; comparer.Sorting = SortOrder.Descending; - listView.ListViewItemSorter = comparer; - listView.ColumnClick += new ColumnClickEventHandler(listView_ColumnClick); + ListView.ListViewItemSorter = comparer; + ListView.ColumnClick += ListView_ColumnClick; // action - viewObjectsItem = new ToolStripMenuItem(PluginCore.Localization.TextHelper.GetString("Label.ViewObjectsItem")); - viewObjectsItem.Click += new EventHandler(onViewObjects); + viewObjectsItem = new ToolStripMenuItem(TextHelper.GetString("Label.ViewObjectsItem")); + viewObjectsItem.Click += OnViewObjects; - listView.ContextMenuStrip = new ContextMenuStrip(); - listView.ContextMenuStrip.Font = PluginBase.Settings.DefaultFont; - listView.ContextMenuStrip.Renderer = new DockPanelStripRenderer(false); - listView.ContextMenuStrip.Items.Add(viewObjectsItem); + ListView.ContextMenuStrip = new ContextMenuStrip(); + ListView.ContextMenuStrip.Font = PluginBase.Settings.DefaultFont; + ListView.ContextMenuStrip.Renderer = new DockPanelStripRenderer(false); + ListView.ContextMenuStrip.Items.Add(viewObjectsItem); - listView.DoubleClick += new EventHandler(onViewObjects); + ListView.DoubleClick += OnViewObjects; } - void listView_ColumnClick(object sender, ColumnClickEventArgs e) + void ListView_ColumnClick(object sender, ColumnClickEventArgs e) { if (comparer.SortColumn == e.Column) { - if (comparer.Sorting == SortOrder.Ascending) - comparer.Sorting = SortOrder.Descending; - else comparer.Sorting = SortOrder.Ascending; + comparer.Sorting = comparer.Sorting == SortOrder.Ascending ? SortOrder.Descending : SortOrder.Ascending; } else { comparer.SortColumn = e.Column; - if (e.Column >= 2) - comparer.Sorting = SortOrder.Descending; - else comparer.Sorting = SortOrder.Ascending; + comparer.Sorting = e.Column >= 2 ? SortOrder.Descending : SortOrder.Ascending; } - listView.Sort(); + ListView.Sort(); } - private void onViewObjects(object sender, EventArgs e) + void OnViewObjects(object sender, EventArgs e) { - if (listView.SelectedItems.Count == 1) + if (ListView.SelectedItems.Count == 1) { - if (OnViewObject != null) - OnViewObject(listView.SelectedItems[0].Tag as TypeItem); + OnViewObject?.Invoke(ListView.SelectedItems[0].Tag as TypeItem); } } public void Clear() { items = new Dictionary(); - listView.Items.Clear(); + ListView.Items.Clear(); } /// @@ -82,8 +77,7 @@ public void Clear() /// public void UpdateTypeGrid(string[] lines) { - listView.SetExStyles(); - listView.BeginUpdate(); + ListView.BeginUpdate(); foreach (TypeItem item in items.Values) item.Zero(); @@ -97,44 +91,42 @@ public void UpdateTypeGrid(string[] lines) { item = new TypeItem(parts[3]); items[parts[0]] = item; - listView.Items.Add(item.ListItem); + ListView.Items.Add(item.ListItem); } else if (!items.ContainsKey(parts[0])) continue; else item = items[parts[0]]; item.Update(parts[1], parts[2]); } - listView.Sort(); + ListView.Sort(); } finally { - listView.EndUpdate(); + ListView.EndUpdate(); } } } - #region Model - class TypeItemComparer : IComparer + class TypeItemComparer : IComparer, IComparer { - public int SortColumn = 0; + public int SortColumn; public SortOrder Sorting; - int IComparer.Compare(object x, object y) - { - TypeItem a = (TypeItem)((ListViewItem)x).Tag; - TypeItem b = (TypeItem)((ListViewItem)y).Tag; + public int Compare(object x, object y) => Compare((ListViewItem) x, (ListViewItem) y); - int comp; - switch (SortColumn) + public int Compare(ListViewItem x, ListViewItem y) + { + var a = (TypeItem)x.Tag; + var b = (TypeItem)y.Tag; + var comp = SortColumn switch { - case TypeItem.COL_PKG: comp = a.Package.CompareTo(b.Package); break; - case TypeItem.COL_MAX: comp = a.Maximum.CompareTo(b.Maximum); break; - case TypeItem.COL_COUNT: comp = a.Count.CompareTo(b.Count); break; - case TypeItem.COL_MEM: comp = a.Memory.CompareTo(b.Memory); break; - default: comp = a.Name.CompareTo(b.Name); break; - } - + TypeItem.COL_PKG => a.Package.CompareTo(b.Package), + TypeItem.COL_MAX => a.Maximum.CompareTo(b.Maximum), + TypeItem.COL_COUNT => a.Count.CompareTo(b.Count), + TypeItem.COL_MEM => a.Memory.CompareTo(b.Memory), + _ => a.Name.CompareTo(b.Name), + }; return Sorting == SortOrder.Ascending ? comp : -comp; } } @@ -159,15 +151,13 @@ class TypeItem public TypeItem(string fullName) { QName = fullName; - int p = fullName.IndexOf(':'); - if (p >= 0) + if (fullName.Contains(':', out var p)) { Name = fullName.Substring(p + 2); Package = fullName.Substring(0, p); } else Name = fullName; - ListItem = new ListViewItem(Name); - ListItem.Tag = this; + ListItem = new ListViewItem(Name) {Tag = this}; ListItem.SubItems.Add(new ListViewItem.ListViewSubItem(ListItem, Package)); ListItem.SubItems.Add(new ListViewItem.ListViewSubItem(ListItem, "0")); ListItem.SubItems.Add(new ListViewItem.ListViewSubItem(ListItem, "0")); @@ -201,4 +191,4 @@ public void Zero() } #endregion -} +} \ No newline at end of file diff --git a/External/Plugins/AS3Context/Controls/ProfilerMemView.cs b/External/Plugins/AS3Context/Controls/ProfilerMemView.cs index 1609e020b9..4f1f17f5eb 100644 --- a/External/Plugins/AS3Context/Controls/ProfilerMemView.cs +++ b/External/Plugins/AS3Context/Controls/ProfilerMemView.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using System.Text; using System.Windows.Forms; using PluginCore.Localization; using System.Drawing; @@ -9,43 +8,41 @@ namespace AS3Context.Controls { class ProfilerMemView { - ToolStripLabel memLabel; - Label statsLabel; - ComboBox scaleCombo; - const int MAX_WIDTH = 1000; - const int MAX_HEIGHT = 400; - private MemGraph graph; - - public ProfilerMemView(ToolStripLabel label, Label stats, ComboBox scale, TabPage memoryPage) + readonly ToolStripLabel memLabel; + readonly Label statsLabel; + readonly ComboBox scaleCombo; + + public MemGraph Graph { get; } + + public ProfilerMemView(ToolStripLabel label, Label stats, ComboBox scale, Control memoryPage) { - graph = new MemGraph(); - graph.Dock = DockStyle.Fill; - memoryPage.Controls.Add(graph); - graph.BringToFront(); + Graph = new MemGraph {Dock = DockStyle.Fill}; + memoryPage.Controls.Add(Graph); + Graph.BringToFront(); memLabel = label; statsLabel = stats; scaleCombo = scale; scaleCombo.SelectedIndex = scaleCombo.Items.Count - 1; - scaleCombo.SelectedIndexChanged += new EventHandler(scaleCombo_SelectedIndexChanged); - graph.TimeScale = scaleCombo.SelectedIndex + 1; + scaleCombo.SelectedIndexChanged += scaleCombo_SelectedIndexChanged; + Graph.TimeScale = scaleCombo.SelectedIndex + 1; Clear(); } void scaleCombo_SelectedIndexChanged(object sender, EventArgs e) { - graph.TimeScale = scaleCombo.SelectedIndex + 1; - graph.Invalidate(); + Graph.TimeScale = scaleCombo.SelectedIndex + 1; + Graph.Invalidate(); } public void Clear() { - graph.Values = new List(); - graph.MaxValue = 1; - memLabel.Text = String.Format(TextHelper.GetString("Label.MemoryDisplay"), FormatMemory(0), FormatMemory(0)); - statsLabel.Text = String.Format(TextHelper.GetString("Label.MemoryStats"), "\n", FormatMemory(0), FormatMemory(0)); + Graph.Values = new List(); + Graph.MaxValue = 1; + memLabel.Text = string.Format(TextHelper.GetString("Label.MemoryDisplay"), FormatMemory(0), FormatMemory(0)); + statsLabel.Text = string.Format(TextHelper.GetString("Label.MemoryStats"), "\n", FormatMemory(0), FormatMemory(0)); } /// @@ -54,18 +51,17 @@ public void Clear() /// public void UpdateStats(string[] info) { - int mem = 0; - int.TryParse(info[1], out mem); - graph.Values.Add((float)mem); - if (mem > graph.MaxValue) graph.MaxValue = mem; + int.TryParse(info[1], out var mem); + Graph.Values.Add(mem); + if (mem > Graph.MaxValue) Graph.MaxValue = mem; string raw = TextHelper.GetString("Label.MemoryDisplay"); - memLabel.Text = String.Format(raw, FormatMemory(mem), FormatMemory((int)graph.MaxValue)); + memLabel.Text = string.Format(raw, FormatMemory(mem), FormatMemory((int)Graph.MaxValue)); raw = TextHelper.GetString("Label.MemoryStats"); - statsLabel.Text = String.Format(raw, "\n", FormatMemory(mem), FormatMemory((int)graph.MaxValue)); - graph.Invalidate(); + statsLabel.Text = string.Format(raw, "\n", FormatMemory(mem), FormatMemory((int)Graph.MaxValue)); + Graph.Invalidate(); } - private string FormatMemory(int mem) + string FormatMemory(int mem) { double m = mem / 1024.0; return (Math.Round(m * 10.0) / 10.0).ToString("N0"); @@ -77,13 +73,25 @@ class MemGraph : Control public List Values = new List(); public float MaxValue = 1; public int TimeScale = 4; + Color back; + Color rect; + Color norm; + Color peak; + Color cur; public MemGraph() { - this.SetStyle( - ControlStyles.UserPaint | - ControlStyles.AllPaintingInWmPaint | - ControlStyles.OptimizedDoubleBuffer, true); + SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); + UpdateColors(); + } + + public void UpdateColors() + { + rect = PluginCore.PluginBase.MainForm.GetThemeColor("MemGraph.ForeColor", Color.Gray); + back = PluginCore.PluginBase.MainForm.GetThemeColor("MemGraph.BackColor", Color.White); + norm = PluginCore.PluginBase.MainForm.GetThemeColor("MemGraph.NormalColor", Color.LightGray); + peak = PluginCore.PluginBase.MainForm.GetThemeColor("MemGraph.PeakColor", Color.Red); + cur = PluginCore.PluginBase.MainForm.GetThemeColor("MemGraph.CurrentColor", Color.Blue); } protected override void OnPaint(PaintEventArgs pe) @@ -91,8 +99,8 @@ protected override void OnPaint(PaintEventArgs pe) Graphics g = pe.Graphics; Rectangle r = pe.ClipRectangle; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; - g.FillRectangle(Brushes.White, r); - g.DrawRectangle(Pens.Gray, 0, 0, Width - 1, Height - 1); + g.FillRectangle(new SolidBrush(back), r); + g.DrawRectangle(new Pen(rect), 0, 0, Width - 1, Height - 1); if (Width < 8 || Height < 8) return; @@ -103,11 +111,10 @@ protected override void OnPaint(PaintEventArgs pe) int diff = Math.Min(Width / TimeScale, n); int x0 = Width - diff * TimeScale; int i = Math.Max(0, n - diff); - float h = (float)Height; - Pen line; + float h = Height; // peak - line = new Pen(Brushes.LightGray, 1); + var line = new Pen(norm, 1); float step = 25000000f; while (step * 4 < MaxValue) step *= 2; float top = step; @@ -118,21 +125,22 @@ protected override void OnPaint(PaintEventArgs pe) g.DrawLine(line, 1f, y, Width - 2, y); top += step; } - line = new Pen(Brushes.Red, 1); + line = new Pen(peak, 1); y = (float)Math.Round(h * 0.1f); g.DrawLine(line, 0f, y, Width - 1, y); // graph - List points = new List(); + var points = new List(); while (i < n) { points.Add(new PointF(x0, h * (1f - 0.9f * Values[i] / MaxValue))); i++; x0 += TimeScale; } - line = new Pen(Brushes.Blue, 2); - line.LineJoin = System.Drawing.Drawing2D.LineJoin.Round; + line = new Pen(cur, 2) {LineJoin = System.Drawing.Drawing2D.LineJoin.Round}; g.DrawLines(line, points.ToArray()); } + } + } diff --git a/External/Plugins/AS3Context/Controls/ProfilerObjectsView.cs b/External/Plugins/AS3Context/Controls/ProfilerObjectsView.cs index abc95f6f75..61fd012a61 100644 --- a/External/Plugins/AS3Context/Controls/ProfilerObjectsView.cs +++ b/External/Plugins/AS3Context/Controls/ProfilerObjectsView.cs @@ -1,82 +1,70 @@ using System; -using System.Collections.Generic; -using System.Text; -using Aga.Controls.Tree; +using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; using PluginCore; -using System.IO; +using PluginCore.Localization; namespace AS3Context.Controls { class ProfilerObjectsView { - ObjectRefsGrid objectsGrid; - Regex reStep = new Regex("([^\\[]+)\\[(.*):([0-9]+)\\]"); - ObjectRefsModel model = new ObjectRefsModel(); - ToolStripMenuItem openItem; + readonly Regex reStep = new Regex("([^\\[]+)\\[(.*):([0-9]+)\\]"); + readonly ObjectRefsModel model = new ObjectRefsModel(); string fileToOpen; int lineToOpen; - Timer delayOpen; + readonly Timer delayOpen; + + public ObjectRefsGrid ObjectsGrid { get; } public ProfilerObjectsView(ObjectRefsGrid grid) { - objectsGrid = grid; + ObjectsGrid = grid; delayOpen = new Timer(); delayOpen.Interval = 100; - delayOpen.Tick += new EventHandler(delayOpen_Tick); + delayOpen.Tick += delayOpen_Tick; // action - openItem = new ToolStripMenuItem(PluginCore.Localization.TextHelper.GetString("Label.OpenMethodFile")); - openItem.Click += new EventHandler(objectsGrid_Open); + var openItem = new ToolStripMenuItem(TextHelper.GetString("Label.OpenMethodFile")); + openItem.Click += objectsGrid_Open; - objectsGrid.ContextMenuStrip = new ContextMenuStrip(); - objectsGrid.ContextMenuStrip.Font = PluginBase.Settings.DefaultFont; - objectsGrid.ContextMenuStrip.Renderer = new DockPanelStripRenderer(false); - objectsGrid.ContextMenuStrip.Items.Add(openItem); - objectsGrid.DoubleClick += new EventHandler(objectsGrid_Open); + ObjectsGrid.ContextMenuStrip = new ContextMenuStrip(); + ObjectsGrid.ContextMenuStrip.Font = PluginBase.Settings.DefaultFont; + ObjectsGrid.ContextMenuStrip.Renderer = new DockPanelStripRenderer(false); + ObjectsGrid.ContextMenuStrip.Items.Add(openItem); + ObjectsGrid.DoubleClick += objectsGrid_Open; } void delayOpen_Tick(object sender, EventArgs e) { delayOpen.Stop(); - if (fileToOpen != null) + if (fileToOpen is null) return; + if (File.Exists(fileToOpen)) { - if (File.Exists(fileToOpen)) + PluginBase.MainForm.OpenEditableDocument(fileToOpen, false); + if (PluginBase.MainForm.CurrentDocument is {IsEditable: true, SciControl: { } sci} doc + && doc.FileName.Equals(fileToOpen, StringComparison.OrdinalIgnoreCase)) { - PluginBase.MainForm.OpenEditableDocument(fileToOpen, false); - if (PluginBase.MainForm.CurrentDocument.IsEditable - && PluginBase.MainForm.CurrentDocument.FileName.Equals(fileToOpen, StringComparison.OrdinalIgnoreCase)) - { - ScintillaNet.ScintillaControl sci = PluginBase.MainForm.CurrentDocument.SciControl; - int pos = sci.PositionFromLine(lineToOpen); - sci.SetSel(pos, pos); - sci.EnsureVisible(lineToOpen); - } + var pos = sci.PositionFromLine(lineToOpen); + sci.SetSel(pos, pos); + sci.EnsureVisibleEnforcePolicy(lineToOpen); } - fileToOpen = null; } + fileToOpen = null; } void objectsGrid_Open(object sender, EventArgs e) { - if (objectsGrid.SelectedNode != null) + if (ObjectsGrid.SelectedNode?.Tag is ObjectRefsNode node && node.Line.Length > 0) { - ObjectRefsNode node = objectsGrid.SelectedNode.Tag as ObjectRefsNode; - if (node != null && node.Line.Length > 0) - { - fileToOpen = node.Path.Replace(';', System.IO.Path.DirectorySeparatorChar); - lineToOpen = int.Parse(node.Line) - 1; - delayOpen.Start(); - } + fileToOpen = node.Path.Replace(';', Path.DirectorySeparatorChar); + lineToOpen = int.Parse(node.Line) - 1; + delayOpen.Start(); } } - public void Clear() - { - model.Root.Nodes.Clear(); - } + public void Clear() => model.Root.Nodes.Clear(); public void Display(string qname, string[] info) { @@ -103,7 +91,7 @@ public void Display(string qname, string[] info) model.Root.Nodes.Add(node); } - objectsGrid.Model = model; + ObjectsGrid.Model = model; } } } diff --git a/External/Plugins/AS3Context/Controls/ProfilerUI.Designer.cs b/External/Plugins/AS3Context/Controls/ProfilerUI.Designer.cs index 214edd588f..3c35cd20d9 100644 --- a/External/Plugins/AS3Context/Controls/ProfilerUI.Designer.cs +++ b/External/Plugins/AS3Context/Controls/ProfilerUI.Designer.cs @@ -29,14 +29,14 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.container = new System.Windows.Forms.Panel(); - this.tabControl = new System.Windows.Forms.TabControl(); + this.tabControl = new System.Windows.Forms.TabControlEx(); this.memoryPage = new System.Windows.Forms.TabPage(); this.memStatsPanel = new System.Windows.Forms.Panel(); this.memStatsLabel = new System.Windows.Forms.Label(); this.memScaleLabel = new System.Windows.Forms.Label(); - this.memScaleCombo = new System.Windows.Forms.ComboBox(); + this.memScaleCombo = new System.Windows.Forms.FlatCombo(); this.liveObjectsPage = new System.Windows.Forms.TabPage(); - this.listView = new AS3Context.Controls.ListViewXP(); + this.listView = new System.Windows.Forms.ListViewEx(); this.typeColumn = new System.Windows.Forms.ColumnHeader(); this.pkgColumn = new System.Windows.Forms.ColumnHeader(); this.maxColumn = new System.Windows.Forms.ColumnHeader(); @@ -67,7 +67,7 @@ private void InitializeComponent() this.container.Dock = System.Windows.Forms.DockStyle.Fill; this.container.Location = new System.Drawing.Point(1, 26); this.container.Name = "container"; - this.container.Padding = new System.Windows.Forms.Padding(3, 3, 2, 2); + this.container.Padding = new System.Windows.Forms.Padding(5, 6, 5, 6); this.container.Size = new System.Drawing.Size(488, 338); this.container.TabIndex = 0; // @@ -88,7 +88,7 @@ private void InitializeComponent() this.memoryPage.Controls.Add(this.memStatsPanel); this.memoryPage.Location = new System.Drawing.Point(4, 22); this.memoryPage.Name = "memoryPage"; - this.memoryPage.Padding = new System.Windows.Forms.Padding(3); + this.memoryPage.Padding = new System.Windows.Forms.Padding(5); this.memoryPage.Size = new System.Drawing.Size(475, 307); this.memoryPage.TabIndex = 2; this.memoryPage.Text = "Memory"; @@ -144,7 +144,7 @@ private void InitializeComponent() this.liveObjectsPage.Controls.Add(this.listView); this.liveObjectsPage.Location = new System.Drawing.Point(4, 22); this.liveObjectsPage.Name = "liveObjectsPage"; - this.liveObjectsPage.Padding = new System.Windows.Forms.Padding(2, 3, 3, 2); + this.liveObjectsPage.Padding = new System.Windows.Forms.Padding(0); this.liveObjectsPage.Size = new System.Drawing.Size(475, 307); this.liveObjectsPage.TabIndex = 0; this.liveObjectsPage.Text = "Live Objects Count"; @@ -152,7 +152,7 @@ private void InitializeComponent() // // listView // - this.listView.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; + this.listView.BorderStyle = System.Windows.Forms.BorderStyle.None; this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.typeColumn, this.pkgColumn, @@ -201,7 +201,7 @@ private void InitializeComponent() // this.objectsPage.Location = new System.Drawing.Point(4, 22); this.objectsPage.Name = "objectsPage"; - this.objectsPage.Padding = new System.Windows.Forms.Padding(2, 3, 3, 2); + this.objectsPage.Padding = new System.Windows.Forms.Padding(0); this.objectsPage.Size = new System.Drawing.Size(475, 307); this.objectsPage.TabIndex = 1; this.objectsPage.Text = "Objects"; @@ -318,7 +318,7 @@ private void InitializeComponent() #endregion - private ListViewXP listView; + private System.Windows.Forms.ListView listView; private System.Windows.Forms.Panel container; private System.Windows.Forms.ToolStrip toolStrip; private System.Windows.Forms.ToolStripLabel memLabel; diff --git a/External/Plugins/AS3Context/Controls/ProfilerUI.cs b/External/Plugins/AS3Context/Controls/ProfilerUI.cs index 652ad12b78..9628d14ff5 100644 --- a/External/Plugins/AS3Context/Controls/ProfilerUI.cs +++ b/External/Plugins/AS3Context/Controls/ProfilerUI.cs @@ -1,7 +1,5 @@ using System; -using System.ComponentModel; using System.Drawing; -using System.Data; using System.Text; using System.Windows.Forms; using PluginCore; @@ -12,52 +10,45 @@ using System.Net.Sockets; using System.Text.RegularExpressions; using System.Collections.Generic; +using System.Linq; using WeifenLuo.WinFormsUI.Docking; namespace AS3Context.Controls { - public partial class ProfilerUI : DockPanelControl + public partial class ProfilerUI : DockPanelControl, IThemeHandler { - static private readonly Byte[] RESULT_OK = Encoding.Default.GetBytes("\0"); - static private readonly Byte[] RESULT_IGNORED = Encoding.Default.GetBytes("\0"); - static private readonly Byte[] RESULT_GC = Encoding.Default.GetBytes("\0"); + static readonly byte[] RESULT_OK = Encoding.Default.GetBytes("\0"); + static readonly byte[] RESULT_IGNORED = Encoding.Default.GetBytes("\0"); + static readonly byte[] RESULT_GC = Encoding.Default.GetBytes("\0"); - static private ProfilerUI instance; - static private bool gcWanted; - static private byte[] snapshotWanted; + static ProfilerUI instance; + static bool gcWanted; + static byte[] snapshotWanted; public DockContent PanelRef; - private bool autoStart; - private bool running; - private string current; - private List previous = new List(); - private ObjectRefsGrid objectRefsGrid; - private ProfilerLiveObjectsView liveObjectsView; - private ProfilerMemView memView; - private ProfilerObjectsView objectRefsView; - private Timer detectDisconnect; - private List profilerItems; - private string profilerItemsCheck; - private string profilerSWF; - - public bool AutoStart - { - get { return autoStart; } - } + bool running; + string current; + readonly List previous = new List(); + readonly ObjectRefsGrid objectRefsGrid; + readonly ProfilerLiveObjectsView liveObjectsView; + readonly ProfilerMemView memView; + readonly ProfilerObjectsView objectRefsView; + readonly Timer detectDisconnect; + List profilerItems; + string profilerItemsCheck; + string profilerSWF; + + public bool AutoStart { get; private set; } public static void HandleFlashConnect(object sender, object data) { - Socket client = sender as Socket; - - if (instance == null || data == null || !instance.running) + var client = (Socket) sender; + if (instance is null || data is null || !instance.running) { if (client.Connected) client.Send(RESULT_IGNORED); return; } - instance.OnProfileData((string)data); - if (client.Connected) client.Send(RESULT_OK); - if (gcWanted) { if (client.Connected) client.Send(RESULT_GC); @@ -75,6 +66,7 @@ public static void HandleFlashConnect(object sender, object data) public ProfilerUI() { instance = this; + AutoKeyHandling = true; InitializeComponent(); objectRefsGrid = new ObjectRefsGrid(); @@ -92,7 +84,7 @@ public ProfilerUI() if (PluginMain.Settings.ProfilerTimeout == 0) PluginMain.Settings.ProfilerTimeout = 30; detectDisconnect = new Timer(); detectDisconnect.Interval = Math.Max(5, PluginMain.Settings.ProfilerTimeout) * 1000; - detectDisconnect.Tick += new EventHandler(detectDisconnect_Tick); + detectDisconnect.Tick += detectDisconnect_Tick; memView = new ProfilerMemView(memLabel, memStatsLabel, memScaleCombo, memoryPage); @@ -100,14 +92,24 @@ public ProfilerUI() column.Width = ScaleHelper.Scale(column.Width); liveObjectsView = new ProfilerLiveObjectsView(listView); - liveObjectsView.OnViewObject += new ViewObjectEvent(liveObjectsView_OnViewObject); + liveObjectsView.OnViewObject += liveObjectsView_OnViewObject; objectRefsView = new ProfilerObjectsView(objectRefsGrid); - configureProfilerChooser(); + ConfigureProfilerChooser(); StopProfiling(); } + /// + /// Lets do some theming fixes + /// + public void AfterTheming() + { + this.memStatsPanel.BackColor = Color.Empty; + this.container.BackColor = PluginBase.MainForm.GetThemeColor("Form.BackColor", SystemColors.Control); + this.memView.Graph.UpdateColors(); + } + void liveObjectsView_OnViewObject(TypeItem item) { snapshotWanted = Encoding.Default.GetBytes("\0"); @@ -115,7 +117,7 @@ void liveObjectsView_OnViewObject(TypeItem item) tabControl.SelectedTab = objectsPage; } - private void InitializeLocalization() + void InitializeLocalization() { this.labelTarget.Text = ""; this.autoButton.Text = TextHelper.GetString("Label.AutoStartProfilerOFF"); @@ -145,13 +147,13 @@ public void Cleanup() SetProfilerCfg(false); } - private void runButton_Click(object sender, EventArgs e) + void runButton_Click(object sender, EventArgs e) { if (running) StopProfiling(); else StartProfiling(); } - private void gcButton_Click(object sender, EventArgs e) + void gcButton_Click(object sender, EventArgs e) { if (running && current != null) gcWanted = true; } @@ -183,50 +185,48 @@ public void StartProfiling() gcButton.Enabled = false; if (!SetProfilerCfg(true)) StopProfiling(); - else if (autoStart) + else if (AutoStart) { detectDisconnect.Interval = 5000; // expecting connection before 5s detectDisconnect.Start(); } } - private void autoButton_Click(object sender, EventArgs e) + void autoButton_Click(object sender, EventArgs e) { - autoStart = !autoStart; - autoButton.Image = PluginBase.MainForm.FindImage(autoStart ? "510" : "514"); - autoButton.Text = TextHelper.GetString(autoStart ? "Label.AutoStartProfilerON" : "Label.AutoStartProfilerOFF"); + AutoStart = !AutoStart; + autoButton.Image = PluginBase.MainForm.FindImage(AutoStart ? "510" : "514"); + autoButton.Text = TextHelper.GetString(AutoStart ? "Label.AutoStartProfilerON" : "Label.AutoStartProfilerOFF"); } #endregion #region Profiler selector - private void configureProfilerChooser() + void ConfigureProfilerChooser() { profilerChooser.Image = PluginBase.MainForm.FindImage("274"); - profilerChooser.DropDownOpening += new EventHandler(profilerChooser_DropDownOpening); + profilerChooser.DropDownOpening += ProfilerChooser_DropDownOpening; profilerItems = new List(); defaultToolStripMenuItem.Checked = true; - defaultToolStripMenuItem.Click += new EventHandler(changeProfiler_Click); + defaultToolStripMenuItem.Click += ChangeProfiler_Click; profilerSWF = null; // default - string active = Path.Combine(Path.Combine(PathHelper.DataDir, "AS3Context"), "activeProfiler.txt"); + var active = Path.Combine(PathHelper.DataDir, "AS3Context", "activeProfiler.txt"); if (File.Exists(active)) { - string src = File.ReadAllText(active).Trim(); - if (src.Length > 0 && File.Exists(src)) - profilerSWF = src; + var src = File.ReadAllText(active).Trim(); + if (File.Exists(src)) profilerSWF = src; } } - void profilerChooser_DropDownOpening(object sender, EventArgs e) + void ProfilerChooser_DropDownOpening(object sender, EventArgs e) { - string[] swfs = PluginMain.Settings.CustomProfilers; - if (swfs == null || swfs.Length == 0) return; + var swfs = PluginMain.Settings.CustomProfilers; + if (swfs.IsNullOrEmpty()) return; - string check = ""; - foreach(string swf in swfs) check += swf; + var check = swfs.Aggregate("", (current1, swf) => current1 + swf); if (check == profilerItemsCheck) return; profilerItemsCheck = check; @@ -239,7 +239,7 @@ void profilerChooser_DropDownOpening(object sender, EventArgs e) { ToolStripMenuItem item = new ToolStripMenuItem(Path.GetFileNameWithoutExtension(swf)); item.Tag = swf; - item.Click += new EventHandler(changeProfiler_Click); + item.Click += ChangeProfiler_Click; profilerItems.Add(item); } } @@ -247,24 +247,24 @@ void profilerChooser_DropDownOpening(object sender, EventArgs e) profilerChooser.DropDownItems.AddRange(profilerItems.ToArray()); defaultToolStripMenuItem.Checked = false; foreach (ToolStripMenuItem item in profilerItems) - if (item.Tag as String == profilerSWF) + if (item.Tag as string == profilerSWF) { item.Checked = true; break; } } - void changeProfiler_Click(object sender, EventArgs e) + void ChangeProfiler_Click(object sender, EventArgs e) { - ToolStripMenuItem item = sender as ToolStripMenuItem; - if (item == null || item.Checked) return; + var item = sender as ToolStripMenuItem; + if (item is null || item.Checked) return; - foreach (ToolStripMenuItem it in profilerItems) + foreach (var it in profilerItems) it.Checked = false; item.Checked = true; - profilerSWF = item.Tag as String; + profilerSWF = item.Tag as string; - string active = Path.Combine(Path.Combine(PathHelper.DataDir, "AS3Context"), "activeProfiler.txt"); + var active = Path.Combine(PathHelper.DataDir, "AS3Context", "activeProfiler.txt"); File.WriteAllText(active, profilerSWF ?? ""); } @@ -318,14 +318,13 @@ internal bool OnProfileData(string data) #region MM configuration - private bool SetProfilerCfg(bool active) + bool SetProfilerCfg(bool active) { try { - String mmCfg = PathHelper.ResolveMMConfig(); + var mmCfg = PathHelper.ResolveMMConfig(); if (!File.Exists(mmCfg)) CreateDefaultCfg(mmCfg); - - string src = File.ReadAllText(mmCfg).Trim(); + var src = File.ReadAllText(mmCfg).Trim(); src = Regex.Replace(src, "PreloadSwf=.*", "").Trim(); if (active) { @@ -340,67 +339,59 @@ private bool SetProfilerCfg(bool active) return true; } - private string AddDefaultProfiler() + static string AddDefaultProfiler() { string swfPath = ResolvePath(CheckResource("Profiler5.swf", "Profiler.swf")); ASCompletion.Commands.CreateTrustFile.Run("FDProfiler.cfg", Path.GetDirectoryName(swfPath)); - FlashConnect.Settings settings = GetFlashConnectSettings(); + var settings = GetFlashConnectSettings(); return "\r\nPreloadSwf=" + swfPath + "?host=" + settings.Host + "&port=" + settings.Port + "\r\n"; } - private string AddCustomProfiler() + string AddCustomProfiler() { - string swfPath = ResolvePath(profilerSWF); - if (swfPath == null) return null; - ASCompletion.Commands.CreateTrustFile.Run("FDProfiler.cfg", Path.GetDirectoryName(swfPath)); - return "\r\nPreloadSwf=" + swfPath + "\r\n"; + var path = ResolvePath(profilerSWF); + if (path is null) return null; + ASCompletion.Commands.CreateTrustFile.Run("FDProfiler.cfg", Path.GetDirectoryName(path)); + return "\r\nPreloadSwf=" + path + "\r\n"; } - private string ResolvePath(string path) + static string ResolvePath(string path) { - if (PluginBase.CurrentProject != null) - return PathHelper.ResolvePath(path, Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath)); - else - return PathHelper.ResolvePath(path); + return PluginBase.CurrentProject != null + ? PathHelper.ResolvePath(path, Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath)) + : PathHelper.ResolvePath(path); } - private FlashConnect.Settings GetFlashConnectSettings() + static FlashConnect.Settings GetFlashConnectSettings() { - IPlugin flashConnect = PluginBase.MainForm.FindPlugin("425ae753-fdc2-4fdf-8277-c47c39c2e26b"); - return flashConnect != null ? (FlashConnect.Settings)flashConnect.Settings : new FlashConnect.Settings(); + var plugin = PluginBase.MainForm.FindPlugin("425ae753-fdc2-4fdf-8277-c47c39c2e26b"); + return plugin != null ? (FlashConnect.Settings)plugin.Settings : new FlashConnect.Settings(); } - static private string CheckResource(string fileName, string resName) + static string CheckResource(string fileName, string resName) { - string path = Path.Combine(PathHelper.DataDir, "AS3Context"); - string fullPath = Path.Combine(path, fileName); - if (!File.Exists(fullPath)) + var fullPath = Path.Combine(PathHelper.DataDir, "AS3Context", fileName); + if (File.Exists(fullPath)) return fullPath; + var id = "AS3Context.Resources." + resName; + var assembly = System.Reflection.Assembly.GetExecutingAssembly(); + using var br = new BinaryReader(assembly.GetManifestResourceStream(id)); + using var bw = File.Create(fullPath); + var buffer = br.ReadBytes(1024); + while (buffer.Length > 0) { - string id = "AS3Context.Resources." + resName; - System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly(); - using (BinaryReader br = new BinaryReader(assembly.GetManifestResourceStream(id))) - { - using (FileStream bw = File.Create(fullPath)) - { - byte[] buffer = br.ReadBytes(1024); - while (buffer.Length > 0) - { - bw.Write(buffer, 0, buffer.Length); - buffer = br.ReadBytes(1024); - } - bw.Close(); - } - br.Close(); - } + bw.Write(buffer, 0, buffer.Length); + buffer = br.ReadBytes(1024); } + bw.Close(); + br.Close(); return fullPath; } - private void CreateDefaultCfg(string mmCfg) + static void CreateDefaultCfg(string mmCfg) { try { - String contents = "PolicyFileLog=1\r\nPolicyFileLogAppend=0\r\nErrorReportingEnable=1\r\nTraceOutputFileEnable=1\r\n"; + const string contents = "PolicyFileLog=1\r\nPolicyFileLogAppend=0\r\nErrorReportingEnable=1\r\nTraceOutputFileEnable=1\r\n"; FileHelper.WriteFile(mmCfg, contents, Encoding.UTF8); } catch (Exception ex) @@ -412,7 +403,4 @@ private void CreateDefaultCfg(string mmCfg) #endregion } - - - -} +} \ No newline at end of file diff --git a/External/Plugins/AS3Context/Controls/Win32.cs b/External/Plugins/AS3Context/Controls/Win32.cs index 56995cda80..a2a1d30c6f 100644 --- a/External/Plugins/AS3Context/Controls/Win32.cs +++ b/External/Plugins/AS3Context/Controls/Win32.cs @@ -6,77 +6,66 @@ namespace AS3Context.Controls { - #region LVS_EX + public enum LVM + { + LVM_FIRST =0x1000, + LVM_SETEXTENDEDLISTVIEWSTYLE=(LVM_FIRST + 54), + LVM_GETEXTENDEDLISTVIEWSTYLE=(LVM_FIRST + 55), + } public enum LVS_EX - { - LVS_EX_GRIDLINES =0x00000001, - LVS_EX_SUBITEMIMAGES =0x00000002, - LVS_EX_CHECKBOXES =0x00000004, - LVS_EX_TRACKSELECT =0x00000008, - LVS_EX_HEADERDRAGDROP =0x00000010, - LVS_EX_FULLROWSELECT =0x00000020, - LVS_EX_ONECLICKACTIVATE =0x00000040, - LVS_EX_TWOCLICKACTIVATE =0x00000080, - LVS_EX_FLATSB =0x00000100, - LVS_EX_REGIONAL =0x00000200, - LVS_EX_INFOTIP =0x00000400, - LVS_EX_UNDERLINEHOT =0x00000800, - LVS_EX_UNDERLINECOLD =0x00001000, - LVS_EX_MULTIWORKAREAS =0x00002000, - LVS_EX_LABELTIP =0x00004000, - LVS_EX_BORDERSELECT =0x00008000, - LVS_EX_DOUBLEBUFFER =0x00010000, - LVS_EX_HIDELABELS =0x00020000, - LVS_EX_SINGLEROW =0x00040000, - LVS_EX_SNAPTOGRID =0x00080000, - LVS_EX_SIMPLESELECT =0x00100000 - } - #endregion + { + LVS_EX_GRIDLINES =0x00000001, + LVS_EX_SUBITEMIMAGES =0x00000002, + LVS_EX_CHECKBOXES =0x00000004, + LVS_EX_TRACKSELECT =0x00000008, + LVS_EX_HEADERDRAGDROP =0x00000010, + LVS_EX_FULLROWSELECT =0x00000020, + LVS_EX_ONECLICKACTIVATE =0x00000040, + LVS_EX_TWOCLICKACTIVATE =0x00000080, + LVS_EX_FLATSB =0x00000100, + LVS_EX_REGIONAL =0x00000200, + LVS_EX_INFOTIP =0x00000400, + LVS_EX_UNDERLINEHOT =0x00000800, + LVS_EX_UNDERLINECOLD =0x00001000, + LVS_EX_MULTIWORKAREAS =0x00002000, + LVS_EX_LABELTIP =0x00004000, + LVS_EX_BORDERSELECT =0x00008000, + LVS_EX_DOUBLEBUFFER =0x00010000, + LVS_EX_HIDELABELS =0x00020000, + LVS_EX_SINGLEROW =0x00040000, + LVS_EX_SNAPTOGRID =0x00080000, + LVS_EX_SIMPLESELECT =0x00100000 + } - #region LVM - public enum LVM - { - LVM_FIRST =0x1000, - LVM_SETEXTENDEDLISTVIEWSTYLE=(LVM_FIRST + 54), - LVM_GETEXTENDEDLISTVIEWSTYLE=(LVM_FIRST + 55), - } - #endregion + [ToolboxBitmap(typeof(System.Windows.Forms.ListViewEx))] + public class ListViewXP : System.Windows.Forms.ListViewEx + { + private LVS_EX styles; + public ListViewXP(){} - [ToolboxBitmap(typeof(System.Windows.Forms.ListView))] - public class ListViewXP :System.Windows.Forms.ListView - { - [DllImport("user32.dll", CharSet=CharSet.Auto)] - public static extern int SendMessage(IntPtr handle, int messg, int wparam, int lparam); + /// + /// Sets Double_Buffering and BorderSelect style + /// + public void SetExStyles() + { + if (!PluginCore.Win32.ShouldUseWin32()) return; + styles = (LVS_EX)PluginCore.Win32.SendMessage(this.Handle, (int) LVM.LVM_GETEXTENDEDLISTVIEWSTYLE, 0,0); + styles |= LVS_EX.LVS_EX_DOUBLEBUFFER | LVS_EX.LVS_EX_BORDERSELECT; + PluginCore.Win32.SendMessage(this.Handle, (int)LVM.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, (int)styles); + } - - private LVS_EX styles; - - public ListViewXP() - { - - } - - /// - /// Sets Double_Buffering and BorderSelect style - /// - public void SetExStyles() - { - styles = (LVS_EX)SendMessage(this.Handle, (int) LVM.LVM_GETEXTENDEDLISTVIEWSTYLE, 0,0); - styles |= LVS_EX.LVS_EX_DOUBLEBUFFER | LVS_EX.LVS_EX_BORDERSELECT; - SendMessage(this.Handle, (int) LVM.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, (int) styles); - } - - /// - /// Sets ListViewExtended Styles - /// - /// The Styles you wish to set. - public void SetExStyles(LVS_EX exStyle) - { - styles = (LVS_EX)SendMessage(this.Handle, (int) LVM.LVM_GETEXTENDEDLISTVIEWSTYLE, 0,0); - styles |= exStyle; - SendMessage(this.Handle, (int) LVM.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, (int) styles); - } - - } + /// + /// Sets ListViewExtended Styles + /// + /// The Styles you wish to set. + public void SetExStyles(LVS_EX exStyle) + { + if (!PluginCore.Win32.ShouldUseWin32()) return; + styles = (LVS_EX)PluginCore.Win32.SendMessage(this.Handle, (int)LVM.LVM_GETEXTENDEDLISTVIEWSTYLE, 0, 0); + styles |= exStyle; + PluginCore.Win32.SendMessage(this.Handle, (int)LVM.LVM_SETEXTENDEDLISTVIEWSTYLE, 0, (int)styles); + } + + } } diff --git a/External/Plugins/AS3Context/Grammar/AS3Lexer.cs b/External/Plugins/AS3Context/Grammar/AS3Lexer.cs index 46d7a62cd9..1cb597c58d 100644 --- a/External/Plugins/AS3Context/Grammar/AS3Lexer.cs +++ b/External/Plugins/AS3Context/Grammar/AS3Lexer.cs @@ -34,2898 +34,2898 @@ namespace AS3Context.Grammar { - // Generate header specific to lexer CSharp file - using System; - using Stream = System.IO.Stream; - using TextReader = System.IO.TextReader; - using Hashtable = System.Collections.Hashtable; - using Comparer = System.Collections.Comparer; - - using TokenStreamException = antlr.TokenStreamException; - using TokenStreamIOException = antlr.TokenStreamIOException; - using TokenStreamRecognitionException = antlr.TokenStreamRecognitionException; - using CharStreamException = antlr.CharStreamException; - using CharStreamIOException = antlr.CharStreamIOException; - using ANTLRException = antlr.ANTLRException; - using CharScanner = antlr.CharScanner; - using InputBuffer = antlr.InputBuffer; - using ByteBuffer = antlr.ByteBuffer; - using CharBuffer = antlr.CharBuffer; - using Token = antlr.Token; - using IToken = antlr.IToken; - using CommonToken = antlr.CommonToken; - using SemanticException = antlr.SemanticException; - using RecognitionException = antlr.RecognitionException; - using NoViableAltForCharException = antlr.NoViableAltForCharException; - using MismatchedCharException = antlr.MismatchedCharException; - using TokenStream = antlr.TokenStream; - using LexerSharedInputState = antlr.LexerSharedInputState; - using BitSet = antlr.collections.impl.BitSet; - - public class AS3Lexer : antlr.CharScanner , TokenStream - { - public const int EOF = 1; - public const int NULL_TREE_LOOKAHEAD = 3; - public const int COMPILATION_UNIT = 4; - public const int IMPORT = 5; - public const int CLASS_DEF = 6; - public const int INTERFACE_DEF = 7; - public const int EXTENDS_CLAUSE = 8; - public const int IMPLEMENTS_CLAUSE = 9; - public const int TYPE_BLOCK = 10; - public const int MODIFIERS = 11; - public const int VARIABLE_DEF = 12; - public const int METHOD_DEF = 13; - public const int NAMESPACE_DEF = 14; - public const int PARAMS = 15; - public const int PARAM = 16; - public const int TYPE_SPEC = 17; - public const int BLOCK = 18; - public const int EXPR = 19; - public const int ELIST = 20; - public const int EXPR_STMNT = 21; - public const int NEW_EXPR = 22; - public const int ENCPS_EXPR = 23; - public const int VAR_INIT = 24; - public const int METHOD_CALL = 25; - public const int ARRAY_ACC = 26; - public const int UNARY_PLUS = 27; - public const int UNARY_MINUS = 28; - public const int POST_INC = 29; - public const int POST_DEC = 30; - public const int ARRAY_LITERAL = 31; - public const int ELEMENT = 32; - public const int OBJECT_LITERAL = 33; - public const int OBJECT_FIELD = 34; - public const int FUNC_DEF = 35; - public const int FOR_INIT = 36; - public const int FOR_CONDITION = 37; - public const int FOR_ITERATOR = 38; - public const int LITERAL_package = 39; - public const int LCURLY = 40; - public const int SEMI = 41; - public const int RCURLY = 42; - public const int LITERAL_import = 43; - public const int LBRACK = 44; - public const int COMMA = 45; - public const int RBRACK = 46; - public const int LPAREN = 47; - public const int RPAREN = 48; - public const int LITERAL_class = 49; - public const int LITERAL_interface = 50; - public const int LITERAL_extends = 51; - public const int LITERAL_implements = 52; - public const int LITERAL_function = 53; - public const int LITERAL_get = 54; - public const int LITERAL_set = 55; - // "/n" = 56 - // "/r" = 57 - public const int IDENT = 58; - public const int LITERAL_namespace = 59; - public const int LITERAL_var = 60; - public const int LITERAL_const = 61; - public const int ASSIGN = 62; - public const int REST = 63; - public const int LITERAL_while = 64; - public const int LITERAL_do = 65; - public const int LITERAL_with = 66; - public const int LITERAL_if = 67; - public const int LITERAL_else = 68; - public const int LITERAL_throw = 69; - public const int LITERAL_return = 70; - public const int LITERAL_continue = 71; - public const int LITERAL_break = 72; - public const int LITERAL_switch = 73; - public const int LITERAL_case = 74; - public const int COLON = 75; - public const int LITERAL_default = 76; - public const int LITERAL_for = 77; - public const int LITERAL_each = 78; - public const int LITERAL_in = 79; - public const int DOT = 80; - public const int STAR = 81; - public const int LITERAL_public = 82; - public const int LITERAL_private = 83; - public const int LITERAL_protected = 84; - public const int LITERAL_internal = 85; - public const int LITERAL_static = 86; - public const int LITERAL_final = 87; - public const int LITERAL_enumerable = 88; - public const int LITERAL_explicit = 89; - public const int LITERAL_override = 90; - public const int LITERAL_dynamic = 91; - public const int NUMBER = 92; - public const int STAR_ASSIGN = 93; - public const int DIV_ASSIGN = 94; - public const int MOD_ASSIGN = 95; - public const int PLUS_ASSIGN = 96; - public const int MINUS_ASSIGN = 97; - public const int SL_ASSIGN = 98; - public const int SR_ASSIGN = 99; - public const int BSR_ASSIGN = 100; - public const int BAND_ASSIGN = 101; - public const int BXOR_ASSIGN = 102; - public const int BOR_ASSIGN = 103; - public const int LAND_ASSIGN = 104; - public const int LOR_ASSIGN = 105; - public const int QUESTION = 106; - public const int LOR = 107; - public const int LAND = 108; - public const int BOR = 109; - public const int BXOR = 110; - public const int BAND = 111; - public const int STRICT_EQUAL = 112; - public const int STRICT_NOT_EQUAL = 113; - public const int NOT_EQUAL = 114; - public const int EQUAL = 115; - public const int LWT = 116; - public const int GT = 117; - public const int LE = 118; - public const int GE = 119; - public const int LITERAL_is = 120; - public const int LITERAL_as = 121; - public const int SL = 122; - public const int SR = 123; - public const int BSR = 124; - public const int PLUS = 125; - public const int MINUS = 126; - public const int DIV = 127; - public const int MOD = 128; - public const int INC = 129; - public const int DEC = 130; - public const int LITERAL_delete = 131; - public const int LITERAL_typeof = 132; - public const int LNOT = 133; - public const int BNOT = 134; - public const int E4X_DESC = 135; - public const int E4X_ATTRI = 136; - public const int LITERAL_null = 137; - public const int LITERAL_true = 138; - public const int LITERAL_false = 139; - public const int LITERAL_undefined = 140; - public const int STRING_LITERAL = 141; - public const int REGEX_LITERAL = 142; - public const int XML_LITERAL = 143; - public const int LITERAL_new = 144; - public const int DBL_COLON = 145; - public const int XML_ATTRIBUTE = 146; - public const int XML_BINDING = 147; - public const int XML_AS3_EXPRESSION = 148; - public const int XML_TEXTNODE = 149; - public const int XML_COMMENT = 150; - public const int XML_CDATA = 151; - public const int REGEX_BODY = 152; - public const int WS = 153; - public const int NL = 154; - public const int BOM = 155; - public const int SL_COMMENT = 156; - public const int ML_COMMENT = 157; - public const int EXPONENT = 158; - public const int HEX_DIGIT = 159; - public const int ESC = 160; - - public AS3Lexer(Stream ins) : this(new ByteBuffer(ins)) - { - } - - public AS3Lexer(TextReader r) : this(new CharBuffer(r)) - { - } - - public AS3Lexer(InputBuffer ib) : this(new LexerSharedInputState(ib)) - { - } - - public AS3Lexer(LexerSharedInputState state) : base(state) - { - initialize(); - } - private void initialize() - { - caseSensitiveLiterals = true; - setCaseSensitive(true); - literals = new Hashtable(100, (float) 0.4, null, Comparer.Default); - literals.Add("public", 82); - literals.Add("namespace", 59); - literals.Add("case", 74); - literals.Add("break", 72); - literals.Add("while", 64); - literals.Add("delete", 131); - literals.Add("new", 144); - literals.Add("/r", 57); - literals.Add("implements", 52); - literals.Add("typeof", 132); - literals.Add("const", 61); - literals.Add("package", 39); - literals.Add("return", 70); - literals.Add("throw", 69); - literals.Add("var", 60); - literals.Add("null", 137); - literals.Add("protected", 84); - literals.Add("class", 49); - literals.Add("do", 65); - literals.Add("function", 53); - literals.Add("each", 78); - literals.Add("with", 66); - literals.Add("set", 55); - literals.Add("/n", 56); - literals.Add("dynamic", 91); - literals.Add("interface", 50); - literals.Add("is", 120); - literals.Add("internal", 85); - literals.Add("final", 87); - literals.Add("explicit", 89); - literals.Add("if", 67); - literals.Add("override", 90); - literals.Add("as", 121); - literals.Add("for", 77); - literals.Add("extends", 51); - literals.Add("private", 83); - literals.Add("default", 76); - literals.Add("false", 139); - literals.Add("static", 86); - literals.Add("undefined", 140); - literals.Add("get", 54); - literals.Add("continue", 71); - literals.Add("enumerable", 88); - literals.Add("else", 68); - literals.Add("import", 43); - literals.Add("in", 79); - literals.Add("switch", 73); - literals.Add("true", 138); - } - - override public IToken nextToken() //throws TokenStreamException - { - IToken theRetToken = null; + // Generate header specific to lexer CSharp file + using System; + using Stream = System.IO.Stream; + using TextReader = System.IO.TextReader; + using Hashtable = System.Collections.Hashtable; + using Comparer = System.Collections.Comparer; + + using TokenStreamException = antlr.TokenStreamException; + using TokenStreamIOException = antlr.TokenStreamIOException; + using TokenStreamRecognitionException = antlr.TokenStreamRecognitionException; + using CharStreamException = antlr.CharStreamException; + using CharStreamIOException = antlr.CharStreamIOException; + using ANTLRException = antlr.ANTLRException; + using CharScanner = antlr.CharScanner; + using InputBuffer = antlr.InputBuffer; + using ByteBuffer = antlr.ByteBuffer; + using CharBuffer = antlr.CharBuffer; + using Token = antlr.Token; + using IToken = antlr.IToken; + using CommonToken = antlr.CommonToken; + using SemanticException = antlr.SemanticException; + using RecognitionException = antlr.RecognitionException; + using NoViableAltForCharException = antlr.NoViableAltForCharException; + using MismatchedCharException = antlr.MismatchedCharException; + using TokenStream = antlr.TokenStream; + using LexerSharedInputState = antlr.LexerSharedInputState; + using BitSet = antlr.collections.impl.BitSet; + + public class AS3Lexer : antlr.CharScanner , TokenStream + { + public const int EOF = 1; + public const int NULL_TREE_LOOKAHEAD = 3; + public const int COMPILATION_UNIT = 4; + public const int IMPORT = 5; + public const int CLASS_DEF = 6; + public const int INTERFACE_DEF = 7; + public const int EXTENDS_CLAUSE = 8; + public const int IMPLEMENTS_CLAUSE = 9; + public const int TYPE_BLOCK = 10; + public const int MODIFIERS = 11; + public const int VARIABLE_DEF = 12; + public const int METHOD_DEF = 13; + public const int NAMESPACE_DEF = 14; + public const int PARAMS = 15; + public const int PARAM = 16; + public const int TYPE_SPEC = 17; + public const int BLOCK = 18; + public const int EXPR = 19; + public const int ELIST = 20; + public const int EXPR_STMNT = 21; + public const int NEW_EXPR = 22; + public const int ENCPS_EXPR = 23; + public const int VAR_INIT = 24; + public const int METHOD_CALL = 25; + public const int ARRAY_ACC = 26; + public const int UNARY_PLUS = 27; + public const int UNARY_MINUS = 28; + public const int POST_INC = 29; + public const int POST_DEC = 30; + public const int ARRAY_LITERAL = 31; + public const int ELEMENT = 32; + public const int OBJECT_LITERAL = 33; + public const int OBJECT_FIELD = 34; + public const int FUNC_DEF = 35; + public const int FOR_INIT = 36; + public const int FOR_CONDITION = 37; + public const int FOR_ITERATOR = 38; + public const int LITERAL_package = 39; + public const int LCURLY = 40; + public const int SEMI = 41; + public const int RCURLY = 42; + public const int LITERAL_import = 43; + public const int LBRACK = 44; + public const int COMMA = 45; + public const int RBRACK = 46; + public const int LPAREN = 47; + public const int RPAREN = 48; + public const int LITERAL_class = 49; + public const int LITERAL_interface = 50; + public const int LITERAL_extends = 51; + public const int LITERAL_implements = 52; + public const int LITERAL_function = 53; + public const int LITERAL_get = 54; + public const int LITERAL_set = 55; + // "/n" = 56 + // "/r" = 57 + public const int IDENT = 58; + public const int LITERAL_namespace = 59; + public const int LITERAL_var = 60; + public const int LITERAL_const = 61; + public const int ASSIGN = 62; + public const int REST = 63; + public const int LITERAL_while = 64; + public const int LITERAL_do = 65; + public const int LITERAL_with = 66; + public const int LITERAL_if = 67; + public const int LITERAL_else = 68; + public const int LITERAL_throw = 69; + public const int LITERAL_return = 70; + public const int LITERAL_continue = 71; + public const int LITERAL_break = 72; + public const int LITERAL_switch = 73; + public const int LITERAL_case = 74; + public const int COLON = 75; + public const int LITERAL_default = 76; + public const int LITERAL_for = 77; + public const int LITERAL_each = 78; + public const int LITERAL_in = 79; + public const int DOT = 80; + public const int STAR = 81; + public const int LITERAL_public = 82; + public const int LITERAL_private = 83; + public const int LITERAL_protected = 84; + public const int LITERAL_internal = 85; + public const int LITERAL_static = 86; + public const int LITERAL_final = 87; + public const int LITERAL_enumerable = 88; + public const int LITERAL_explicit = 89; + public const int LITERAL_override = 90; + public const int LITERAL_dynamic = 91; + public const int NUMBER = 92; + public const int STAR_ASSIGN = 93; + public const int DIV_ASSIGN = 94; + public const int MOD_ASSIGN = 95; + public const int PLUS_ASSIGN = 96; + public const int MINUS_ASSIGN = 97; + public const int SL_ASSIGN = 98; + public const int SR_ASSIGN = 99; + public const int BSR_ASSIGN = 100; + public const int BAND_ASSIGN = 101; + public const int BXOR_ASSIGN = 102; + public const int BOR_ASSIGN = 103; + public const int LAND_ASSIGN = 104; + public const int LOR_ASSIGN = 105; + public const int QUESTION = 106; + public const int LOR = 107; + public const int LAND = 108; + public const int BOR = 109; + public const int BXOR = 110; + public const int BAND = 111; + public const int STRICT_EQUAL = 112; + public const int STRICT_NOT_EQUAL = 113; + public const int NOT_EQUAL = 114; + public const int EQUAL = 115; + public const int LWT = 116; + public const int GT = 117; + public const int LE = 118; + public const int GE = 119; + public const int LITERAL_is = 120; + public const int LITERAL_as = 121; + public const int SL = 122; + public const int SR = 123; + public const int BSR = 124; + public const int PLUS = 125; + public const int MINUS = 126; + public const int DIV = 127; + public const int MOD = 128; + public const int INC = 129; + public const int DEC = 130; + public const int LITERAL_delete = 131; + public const int LITERAL_typeof = 132; + public const int LNOT = 133; + public const int BNOT = 134; + public const int E4X_DESC = 135; + public const int E4X_ATTRI = 136; + public const int LITERAL_null = 137; + public const int LITERAL_true = 138; + public const int LITERAL_false = 139; + public const int LITERAL_undefined = 140; + public const int STRING_LITERAL = 141; + public const int REGEX_LITERAL = 142; + public const int XML_LITERAL = 143; + public const int LITERAL_new = 144; + public const int DBL_COLON = 145; + public const int XML_ATTRIBUTE = 146; + public const int XML_BINDING = 147; + public const int XML_AS3_EXPRESSION = 148; + public const int XML_TEXTNODE = 149; + public const int XML_COMMENT = 150; + public const int XML_CDATA = 151; + public const int REGEX_BODY = 152; + public const int WS = 153; + public const int NL = 154; + public const int BOM = 155; + public const int SL_COMMENT = 156; + public const int ML_COMMENT = 157; + public const int EXPONENT = 158; + public const int HEX_DIGIT = 159; + public const int ESC = 160; + + public AS3Lexer(Stream ins) : this(new ByteBuffer(ins)) + { + } + + public AS3Lexer(TextReader r) : this(new CharBuffer(r)) + { + } + + public AS3Lexer(InputBuffer ib) : this(new LexerSharedInputState(ib)) + { + } + + public AS3Lexer(LexerSharedInputState state) : base(state) + { + initialize(); + } + private void initialize() + { + caseSensitiveLiterals = true; + setCaseSensitive(true); + literals = new Hashtable(100, (float) 0.4, null, Comparer.Default); + literals.Add("public", 82); + literals.Add("namespace", 59); + literals.Add("case", 74); + literals.Add("break", 72); + literals.Add("while", 64); + literals.Add("delete", 131); + literals.Add("new", 144); + literals.Add("/r", 57); + literals.Add("implements", 52); + literals.Add("typeof", 132); + literals.Add("const", 61); + literals.Add("package", 39); + literals.Add("return", 70); + literals.Add("throw", 69); + literals.Add("var", 60); + literals.Add("null", 137); + literals.Add("protected", 84); + literals.Add("class", 49); + literals.Add("do", 65); + literals.Add("function", 53); + literals.Add("each", 78); + literals.Add("with", 66); + literals.Add("set", 55); + literals.Add("/n", 56); + literals.Add("dynamic", 91); + literals.Add("interface", 50); + literals.Add("is", 120); + literals.Add("internal", 85); + literals.Add("final", 87); + literals.Add("explicit", 89); + literals.Add("if", 67); + literals.Add("override", 90); + literals.Add("as", 121); + literals.Add("for", 77); + literals.Add("extends", 51); + literals.Add("private", 83); + literals.Add("default", 76); + literals.Add("false", 139); + literals.Add("static", 86); + literals.Add("undefined", 140); + literals.Add("get", 54); + literals.Add("continue", 71); + literals.Add("enumerable", 88); + literals.Add("else", 68); + literals.Add("import", 43); + literals.Add("in", 79); + literals.Add("switch", 73); + literals.Add("true", 138); + } + + override public IToken nextToken() //throws TokenStreamException + { + IToken theRetToken = null; tryAgain: - for (;;) - { - IToken _token = null; - int _ttype = Token.INVALID_TYPE; - resetText(); - try // for char stream error handling - { - try // for lexical error handling - { - switch ( cached_LA1 ) - { - case '?': - { - mQUESTION(true); - theRetToken = returnToken_; - break; - } - case '(': - { - mLPAREN(true); - theRetToken = returnToken_; - break; - } - case ')': - { - mRPAREN(true); - theRetToken = returnToken_; - break; - } - case '[': - { - mLBRACK(true); - theRetToken = returnToken_; - break; - } - case ']': - { - mRBRACK(true); - theRetToken = returnToken_; - break; - } - case '{': - { - mLCURLY(true); - theRetToken = returnToken_; - break; - } - case '}': - { - mRCURLY(true); - theRetToken = returnToken_; - break; - } - case ',': - { - mCOMMA(true); - theRetToken = returnToken_; - break; - } - case '~': - { - mBNOT(true); - theRetToken = returnToken_; - break; - } - case '@': - { - mE4X_ATTRI(true); - theRetToken = returnToken_; - break; - } - case ';': - { - mSEMI(true); - theRetToken = returnToken_; - break; - } - case '$': case 'A': case 'B': case 'C': - case 'D': case 'E': case 'F': case 'G': - case 'H': case 'I': case 'J': case 'K': - case 'L': case 'M': case 'N': case 'O': - case 'P': case 'Q': case 'R': case 'S': - case 'T': case 'U': case 'V': case 'W': - case 'X': case 'Y': case 'Z': case '_': - case 'a': case 'b': case 'c': case 'd': - case 'e': case 'f': case 'g': case 'h': - case 'i': case 'j': case 'k': case 'l': - case 'm': case 'n': case 'o': case 'p': - case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': - case 'y': case 'z': - { - mIDENT(true); - theRetToken = returnToken_; - break; - } - case '"': case '\'': - { - mSTRING_LITERAL(true); - theRetToken = returnToken_; - break; - } - case '\t': case '\n': case '\u000c': case '\r': - case ' ': - { - mWS(true); - theRetToken = returnToken_; - break; - } - case '.': case '0': case '1': case '2': - case '3': case '4': case '5': case '6': - case '7': case '8': case '9': - { - mNUMBER(true); - theRetToken = returnToken_; - break; - } - case '\u00bb': case '\u00bf': case '\u00ef': - { - mBOM(true); - theRetToken = returnToken_; - break; - } - default: - if ((cached_LA1=='>') && (cached_LA2=='>') && (LA(3)=='>') && (LA(4)=='=')) - { - mBSR_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='=') && (cached_LA2=='=') && (LA(3)=='=')) { - mSTRICT_EQUAL(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='!') && (cached_LA2=='=') && (LA(3)=='=')) { - mSTRICT_NOT_EQUAL(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='>') && (cached_LA2=='>') && (LA(3)=='=')) { - mSR_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='>') && (cached_LA2=='>') && (LA(3)=='>') && (true)) { - mBSR(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='<') && (cached_LA2=='<') && (LA(3)=='=')) { - mSL_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='&') && (cached_LA2=='&') && (LA(3)=='=')) { - mLAND_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='|') && (cached_LA2=='|') && (LA(3)=='=')) { - mLOR_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='/') && (tokenSet_0_.member(cached_LA2)) && (tokenSet_1_.member(LA(3)))) { - mREGEX_LITERAL(true); - theRetToken = returnToken_; - } - else if ((cached_LA1==':') && (cached_LA2==':')) { - mDBL_COLON(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='=') && (cached_LA2=='=') && (true)) { - mEQUAL(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='!') && (cached_LA2=='=') && (true)) { - mNOT_EQUAL(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='/') && (cached_LA2=='=') && (true)) { - mDIV_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='+') && (cached_LA2=='=')) { - mPLUS_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='+') && (cached_LA2=='+')) { - mINC(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='-') && (cached_LA2=='=')) { - mMINUS_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='-') && (cached_LA2=='-')) { - mDEC(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='*') && (cached_LA2=='=')) { - mSTAR_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='%') && (cached_LA2=='=')) { - mMOD_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='>') && (cached_LA2=='>') && (true)) { - mSR(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='>') && (cached_LA2=='=')) { - mGE(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='<') && (cached_LA2=='<') && (true)) { - mSL(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='<') && (cached_LA2=='=')) { - mLE(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='^') && (cached_LA2=='=')) { - mBXOR_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='|') && (cached_LA2=='=')) { - mBOR_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='|') && (cached_LA2=='|') && (true)) { - mLOR(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='&') && (cached_LA2=='=')) { - mBAND_ASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='&') && (cached_LA2=='&') && (true)) { - mLAND(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='<') && (tokenSet_2_.member(cached_LA2))) { - mXML_LITERAL(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='/') && (cached_LA2=='/')) { - mSL_COMMENT(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='/') && (cached_LA2=='*')) { - mML_COMMENT(true); - theRetToken = returnToken_; - } - else if ((cached_LA1==':') && (true)) { - mCOLON(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='=') && (true)) { - mASSIGN(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='!') && (true)) { - mLNOT(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='/') && (true)) { - mDIV(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='+') && (true)) { - mPLUS(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='-') && (true)) { - mMINUS(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='*') && (true)) { - mSTAR(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='%') && (true)) { - mMOD(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='>') && (true)) { - mGT(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='<') && (true)) { - mLWT(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='^') && (true)) { - mBXOR(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='|') && (true)) { - mBOR(true); - theRetToken = returnToken_; - } - else if ((cached_LA1=='&') && (true)) { - mBAND(true); - theRetToken = returnToken_; - } - else - { - if (cached_LA1==EOF_CHAR) { uponEOF(); returnToken_ = makeToken(Token.EOF_TYPE); } - else {throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());} - } - break; } - if ( null==returnToken_ ) goto tryAgain; // found SKIP token - _ttype = returnToken_.Type; - returnToken_.Type = _ttype; - return returnToken_; - } - catch (RecognitionException e) { - throw new TokenStreamRecognitionException(e); - } - } - catch (CharStreamException cse) { - if ( cse is CharStreamIOException ) { - throw new TokenStreamIOException(((CharStreamIOException)cse).io); - } - else { - throw new TokenStreamException(cse.Message); - } - } - } - } - - public void mQUESTION(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = QUESTION; - - match('?'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LPAREN; - - match('('); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mRPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = RPAREN; - - match(')'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLBRACK(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LBRACK; - - match('['); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mRBRACK(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = RBRACK; - - match(']'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLCURLY(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LCURLY; - - match('{'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mRCURLY(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = RCURLY; - - match('}'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mCOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = COLON; - - match(':'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mDBL_COLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = DBL_COLON; - - match("::"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mCOMMA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = COMMA; - - match(','); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = ASSIGN; - - match('='); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mEQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = EQUAL; - - match("=="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSTRICT_EQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = STRICT_EQUAL; - - match("==="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLNOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LNOT; - - match('!'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBNOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BNOT; - - match('~'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mNOT_EQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = NOT_EQUAL; - - match("!="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSTRICT_NOT_EQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = STRICT_NOT_EQUAL; - - match("!=="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mDIV(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = DIV; - - match('/'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mDIV_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = DIV_ASSIGN; - - match("/="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mPLUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = PLUS; - - match('+'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mPLUS_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = PLUS_ASSIGN; - - match("+="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mINC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = INC; - - match("++"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mMINUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = MINUS; - - match('-'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mMINUS_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = MINUS_ASSIGN; - - match("-="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mDEC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = DEC; - - match("--"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSTAR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = STAR; - - match('*'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSTAR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = STAR_ASSIGN; - - match("*="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mMOD(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = MOD; - - match('%'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mMOD_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = MOD_ASSIGN; - - match("%="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = SR; - - match(">>"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = SR_ASSIGN; - - match(">>="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBSR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BSR; - - match(">>>"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBSR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BSR_ASSIGN; - - match(">>>="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mGE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = GE; - - match(">="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mGT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = GT; - - match('>'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = SL; - - match("<<"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSL_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = SL_ASSIGN; - - match("<<="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LE; - - match("<="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLWT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LWT; - - match('<'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBXOR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BXOR; - - match('^'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBXOR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BXOR_ASSIGN; - - match("^="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBOR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BOR; - - match('|'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBOR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BOR_ASSIGN; - - match("|="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLOR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LOR; - - match("||"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBAND(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BAND; - - match('&'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBAND_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BAND_ASSIGN; - - match("&="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLAND(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LAND; - - match("&&"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLAND_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LAND_ASSIGN; - - match("&&="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mLOR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = LOR_ASSIGN; - - match("||="); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mE4X_ATTRI(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = E4X_ATTRI; - - match('@'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSEMI(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = SEMI; - - match(';'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - private void mDOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = DOT; - - match('.'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - private void mE4X_DESC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = E4X_DESC; - - match(".."); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - private void mREST(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = REST; - - match("..."); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mIDENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = IDENT; - - { - switch ( cached_LA1 ) - { - case 'a': case 'b': case 'c': case 'd': - case 'e': case 'f': case 'g': case 'h': - case 'i': case 'j': case 'k': case 'l': - case 'm': case 'n': case 'o': case 'p': - case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': - case 'y': case 'z': - { - matchRange('a','z'); - break; - } - case 'A': case 'B': case 'C': case 'D': - case 'E': case 'F': case 'G': case 'H': - case 'I': case 'J': case 'K': case 'L': - case 'M': case 'N': case 'O': case 'P': - case 'Q': case 'R': case 'S': case 'T': - case 'U': case 'V': case 'W': case 'X': - case 'Y': case 'Z': - { - matchRange('A','Z'); - break; - } - case '_': - { - match('_'); - break; - } - case '$': - { - match('$'); - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - { // ( ... )* - for (;;) - { - if (((cached_LA1 >= 'a' && cached_LA1 <= 'z')) && (true) && (true) && (true)) - { - matchRange('a','z'); - } - else if (((cached_LA1 >= 'A' && cached_LA1 <= 'Z')) && (true) && (true) && (true)) { - matchRange('A','Z'); - } - else if ((cached_LA1=='_') && (true) && (true) && (true)) { - match('_'); - } - else if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) { - matchRange('0','9'); - } - else if ((cached_LA1=='$') && (true) && (true) && (true)) { - match('$'); - } - else - { - goto _loop271_breakloop; - } - - } -_loop271_breakloop: ; - } // ( ... )* - _ttype = testLiteralsTable(_ttype); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSTRING_LITERAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = STRING_LITERAL; - - switch ( cached_LA1 ) - { - case '"': - { - match('"'); - { // ( ... )* - for (;;) - { - if ((cached_LA1=='\\')) - { - mESC(false); - } - else if ((tokenSet_3_.member(cached_LA1))) { - { - match(tokenSet_3_); - } - } - else - { - goto _loop275_breakloop; - } - - } -_loop275_breakloop: ; - } // ( ... )* - match('"'); - break; - } - case '\'': - { - match('\''); - { // ( ... )* - for (;;) - { - if ((cached_LA1=='\\')) - { - mESC(false); - } - else if ((tokenSet_4_.member(cached_LA1))) { - { - match(tokenSet_4_); - } - } - else - { - goto _loop278_breakloop; - } - - } -_loop278_breakloop: ; - } // ( ... )* - match('\''); - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mESC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = ESC; - - match('\\'); - { - switch ( cached_LA1 ) - { - case 'n': - { - match('n'); - break; - } - case 'r': - { - match('r'); - break; - } - case 't': - { - match('t'); - break; - } - case 'b': - { - match('b'); - break; - } - case 'f': - { - match('f'); - break; - } - case '"': - { - match('"'); - break; - } - case '\'': - { - match('\''); - break; - } - case '\\': - { - match('\\'); - break; - } - case 'u': - { - { // ( ... )+ - int _cnt378=0; - for (;;) - { - if ((cached_LA1=='u')) - { - match('u'); - } - else - { - if (_cnt378 >= 1) { goto _loop378_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } - } - - _cnt378++; - } -_loop378_breakloop: ; - } // ( ... )+ - mHEX_DIGIT(false); - mHEX_DIGIT(false); - mHEX_DIGIT(false); - mHEX_DIGIT(false); - break; - } - case '0': case '1': case '2': case '3': - { - matchRange('0','3'); - { - if (((cached_LA1 >= '0' && cached_LA1 <= '7')) && (tokenSet_1_.member(cached_LA2)) && (true) && (true)) - { - matchRange('0','7'); - { - if (((cached_LA1 >= '0' && cached_LA1 <= '7')) && (tokenSet_1_.member(cached_LA2)) && (true) && (true)) - { - matchRange('0','7'); - } - else if ((tokenSet_1_.member(cached_LA1)) && (true) && (true) && (true)) { - } - else - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - - } - } - else if ((tokenSet_1_.member(cached_LA1)) && (true) && (true) && (true)) { - } - else - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - - } - break; - } - case '4': case '5': case '6': case '7': - { - matchRange('4','7'); - { - if (((cached_LA1 >= '0' && cached_LA1 <= '7')) && (tokenSet_1_.member(cached_LA2)) && (true) && (true)) - { - matchRange('0','7'); - } - else if ((tokenSet_1_.member(cached_LA1)) && (true) && (true) && (true)) { - } - else - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - - } - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mXML_LITERAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = XML_LITERAL; - - match('<'); - mIDENT(false); - { // ( ... )* - for (;;) - { - switch ( cached_LA1 ) - { - case '\t': case '\n': case '\u000c': case '\r': - case ' ': - { - mWS(false); - break; - } - case '$': case 'A': case 'B': case 'C': - case 'D': case 'E': case 'F': case 'G': - case 'H': case 'I': case 'J': case 'K': - case 'L': case 'M': case 'N': case 'O': - case 'P': case 'Q': case 'R': case 'S': - case 'T': case 'U': case 'V': case 'W': - case 'X': case 'Y': case 'Z': case '_': - case 'a': case 'b': case 'c': case 'd': - case 'e': case 'f': case 'g': case 'h': - case 'i': case 'j': case 'k': case 'l': - case 'm': case 'n': case 'o': case 'p': - case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': - case 'y': case 'z': - { - mXML_ATTRIBUTE(false); - break; - } - default: - { - goto _loop281_breakloop; - } - } - } -_loop281_breakloop: ; - } // ( ... )* - { - switch ( cached_LA1 ) - { - case '>': - { - match('>'); - { // ( ... )* - for (;;) - { - if ((cached_LA1=='\t'||cached_LA1=='\n'||cached_LA1=='\u000c'||cached_LA1=='\r'||cached_LA1==' ') && (tokenSet_5_.member(cached_LA2)) && (tokenSet_5_.member(LA(3))) && (tokenSet_5_.member(LA(4)))) - { - mWS(false); - } - else if ((tokenSet_6_.member(cached_LA1)) && (tokenSet_5_.member(cached_LA2)) && (tokenSet_5_.member(LA(3))) && (tokenSet_5_.member(LA(4)))) { - mXML_TEXTNODE(false); - } - else if ((cached_LA1=='<') && (cached_LA2=='!') && (LA(3)=='-')) { - mXML_COMMENT(false); - } - else if ((cached_LA1=='<') && (cached_LA2=='!') && (LA(3)=='[')) { - mXML_CDATA(false); - } - else if ((cached_LA1=='<') && (tokenSet_2_.member(cached_LA2))) { - mXML_LITERAL(false); - } - else - { - goto _loop284_breakloop; - } - - } -_loop284_breakloop: ; - } // ( ... )* - match("'); - break; - } - case '/': - { - match("/>"); - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mWS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = WS; - - { // ( ... )+ - int _cnt354=0; - for (;;) - { - if ((cached_LA1==' ') && (true) && (true) && (true)) - { - match(' '); - } - else if ((cached_LA1=='\t') && (true) && (true) && (true)) { - match('\t'); - } - else if ((cached_LA1=='\u000c') && (true) && (true) && (true)) { - match('\f'); - } - else if ((cached_LA1=='\n'||cached_LA1=='\r') && (true) && (true) && (true)) { - mNL(false); - } - else - { - if (_cnt354 >= 1) { goto _loop354_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } - } - - _cnt354++; - } -_loop354_breakloop: ; - } // ( ... )+ - if (0==inputState.guessing) - { - _ttype = Token.SKIP; - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mXML_ATTRIBUTE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = XML_ATTRIBUTE; - - mIDENT(false); - { // ( ... )* - for (;;) - { - if ((cached_LA1=='\t'||cached_LA1=='\n'||cached_LA1=='\u000c'||cached_LA1=='\r'||cached_LA1==' ')) - { - mWS(false); - } - else - { - goto _loop287_breakloop; - } - - } -_loop287_breakloop: ; - } // ( ... )* - mASSIGN(false); - { // ( ... )* - for (;;) - { - if ((cached_LA1=='\t'||cached_LA1=='\n'||cached_LA1=='\u000c'||cached_LA1=='\r'||cached_LA1==' ')) - { - mWS(false); - } - else - { - goto _loop289_breakloop; - } - - } -_loop289_breakloop: ; - } // ( ... )* - { - switch ( cached_LA1 ) - { - case '"': case '\'': - { - mSTRING_LITERAL(false); - break; - } - case '{': - { - mXML_BINDING(false); - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mXML_TEXTNODE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = XML_TEXTNODE; - - { - if ((cached_LA1=='\n'||cached_LA1=='\r')) - { - mNL(false); - } - else if (((cached_LA1=='/'))&&( LA(2)!='>' )) { - match('/'); - } - else if ((tokenSet_7_.member(cached_LA1))) { - { - match(tokenSet_7_); - } - } - else - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mXML_COMMENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = XML_COMMENT; - - match(""); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mXML_CDATA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = XML_CDATA; - - match("= '\u0003' && cached_LA2 <= '\u7ffe')) && ((LA(3) >= '\u0003' && LA(3) <= '\u7ffe')) && ((LA(4) >= '\u0003' && LA(4) <= '\u7ffe')))&&( LA(2)!=']')) - { - match(']'); - } - else if ((cached_LA1=='\n'||cached_LA1=='\r')) { - mNL(false); - } - else if ((tokenSet_9_.member(cached_LA1))) { - { - match(tokenSet_9_); - } - } - else - { - goto _loop307_breakloop; - } - - } -_loop307_breakloop: ; - } // ( ... )* - match("]]>"); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mXML_BINDING(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = XML_BINDING; - - match('{'); - mXML_AS3_EXPRESSION(false); - match('}'); - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mXML_AS3_EXPRESSION(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = XML_AS3_EXPRESSION; - - { - { // ( ... )* - for (;;) - { - if ((tokenSet_10_.member(cached_LA1))) - { - { - match(tokenSet_10_); - } - } - else - { - goto _loop296_breakloop; - } - - } -_loop296_breakloop: ; - } // ( ... )* - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mNL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = NL; - - { - if ((cached_LA1=='\r') && (cached_LA2=='\n') && (true) && (true)) - { - match('\r'); - match('\n'); - } - else if ((cached_LA1=='\r') && (true) && (true) && (true)) { - match('\r'); - } - else if ((cached_LA1=='\n')) { - match('\n'); - } - else - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - - } - if (0==inputState.guessing) - { - newline(); _ttype = Token.SKIP; - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mNUMBER(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = NUMBER; - Token t=null; - - if ((cached_LA1=='.') && (cached_LA2=='.') && (LA(3)=='.')) - { - match("..."); - if (0==inputState.guessing) - { - _ttype = REST; - } - } - else if ((cached_LA1=='.') && (cached_LA2=='.') && (true)) { - match(".."); - if (0==inputState.guessing) - { - _ttype = E4X_DESC; - } - } - else if ((cached_LA1=='.') && (true)) { - match('.'); - if (0==inputState.guessing) - { - _ttype = DOT; - } - { - if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) - { - { // ( ... )+ - int _cnt311=0; - for (;;) - { - if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) - { - matchRange('0','9'); - } - else - { - if (_cnt311 >= 1) { goto _loop311_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } - } - - _cnt311++; - } -_loop311_breakloop: ; - } // ( ... )+ - { - if ((cached_LA1=='E'||cached_LA1=='e')) - { - mEXPONENT(false); - } - else { - } - - } - if (0==inputState.guessing) - { - _ttype = NUMBER; - } - } - else { - } - - } - } - else if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) { - { - switch ( cached_LA1 ) - { - case '0': - { - match('0'); - { - if ((cached_LA1=='X'||cached_LA1=='x')) - { - { - switch ( cached_LA1 ) - { - case 'X': - { - match('X'); - break; - } - case 'x': - { - match('x'); - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - { // ( ... )+ - int _cnt317=0; - for (;;) - { - if ((tokenSet_11_.member(cached_LA1))) - { - mHEX_DIGIT(false); - } - else - { - if (_cnt317 >= 1) { goto _loop317_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } - } - - _cnt317++; - } -_loop317_breakloop: ; - } // ( ... )+ - } - else if (((cached_LA1 >= '0' && cached_LA1 <= '7')) && (true) && (true) && (true)) { - { // ( ... )+ - int _cnt333=0; - for (;;) - { - if (((cached_LA1 >= '0' && cached_LA1 <= '7'))) - { - matchRange('0','7'); - } - else - { - if (_cnt333 >= 1) { goto _loop333_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } - } - - _cnt333++; - } -_loop333_breakloop: ; - } // ( ... )+ - } - else { - bool synPredMatched325 = false; - if (( true )) - { - int _m325 = mark(); - synPredMatched325 = true; - inputState.guessing++; - try { - { - { // ( ... )* - for (;;) - { - if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) - { - matchRange('0','9'); - } - else - { - goto _loop320_breakloop; - } - - } -_loop320_breakloop: ; - } // ( ... )* - { - if ((cached_LA1=='.')) - { - match('.'); - { // ( ... )+ - int _cnt323=0; - for (;;) - { - if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) - { - matchRange('0','9'); - } - else - { - if (_cnt323 >= 1) { goto _loop323_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } - } - - _cnt323++; - } -_loop323_breakloop: ; - } // ( ... )+ - } - else { - } - - } - { - if ((cached_LA1=='E'||cached_LA1=='e')) - { - mEXPONENT(false); - } - else { - } - - } - } - } - catch (RecognitionException) - { - synPredMatched325 = false; - } - rewind(_m325); - inputState.guessing--; - } - if ( synPredMatched325 ) - { - { // ( ... )* - for (;;) - { - if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) - { - matchRange('0','9'); - } - else - { - goto _loop327_breakloop; - } - - } -_loop327_breakloop: ; - } // ( ... )* - { - if ((cached_LA1=='.')) - { - match('.'); - { // ( ... )+ - int _cnt330=0; - for (;;) - { - if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) - { - matchRange('0','9'); - } - else - { - if (_cnt330 >= 1) { goto _loop330_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } - } - - _cnt330++; - } -_loop330_breakloop: ; - } // ( ... )+ - } - else { - } - - } - { - if ((cached_LA1=='E'||cached_LA1=='e')) - { - mEXPONENT(false); - } - else { - } - - } - } - else { - } - } - } - break; - } - case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': - case '9': - { - { - matchRange('1','9'); - } - { // ( ... )* - for (;;) - { - if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) - { - matchRange('0','9'); - } - else - { - goto _loop336_breakloop; - } - - } -_loop336_breakloop: ; - } // ( ... )* - if (0==inputState.guessing) - { - _ttype = NUMBER; - } - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - } - else - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mEXPONENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = EXPONENT; - - { - switch ( cached_LA1 ) - { - case 'e': - { - match('e'); - break; - } - case 'E': - { - match('E'); - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - { - switch ( cached_LA1 ) - { - case '+': - { - match('+'); - break; - } - case '-': - { - match('-'); - break; - } - case '0': case '1': case '2': case '3': - case '4': case '5': case '6': case '7': - case '8': case '9': - { - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - { // ( ... )+ - int _cnt372=0; - for (;;) - { - if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) - { - matchRange('0','9'); - } - else - { - if (_cnt372 >= 1) { goto _loop372_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } - } - - _cnt372++; - } -_loop372_breakloop: ; - } // ( ... )+ - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mHEX_DIGIT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = HEX_DIGIT; - - { - switch ( cached_LA1 ) - { - case '0': case '1': case '2': case '3': - case '4': case '5': case '6': case '7': - case '8': case '9': - { - matchRange('0','9'); - break; - } - case 'A': case 'B': case 'C': case 'D': - case 'E': case 'F': - { - matchRange('A','F'); - break; - } - case 'a': case 'b': case 'c': case 'd': - case 'e': case 'f': - { - matchRange('a','f'); - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mREGEX_LITERAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = REGEX_LITERAL; - - match('/'); - mREGEX_BODY(false); - match('/'); - { // ( ... )* - for (;;) - { - switch ( cached_LA1 ) - { - case 'a': case 'b': case 'c': case 'd': - case 'e': case 'f': case 'g': case 'h': - case 'i': case 'j': case 'k': case 'l': - case 'm': case 'n': case 'o': case 'p': - case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': - case 'y': case 'z': - { - matchRange('a','z'); - break; - } - case 'A': case 'B': case 'C': case 'D': - case 'E': case 'F': case 'G': case 'H': - case 'I': case 'J': case 'K': case 'L': - case 'M': case 'N': case 'O': case 'P': - case 'Q': case 'R': case 'S': case 'T': - case 'U': case 'V': case 'W': case 'X': - case 'Y': case 'Z': - { - matchRange('A','Z'); - break; - } - case '_': - { - match('_'); - break; - } - case '0': case '1': case '2': case '3': - case '4': case '5': case '6': case '7': - case '8': case '9': - { - matchRange('0','9'); - break; - } - case '$': - { - match('$'); - break; - } - default: - { - goto _loop339_breakloop; - } - } - } -_loop339_breakloop: ; - } // ( ... )* - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - protected void mREGEX_BODY(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = REGEX_BODY; - - { - if ((tokenSet_12_.member(cached_LA1))) - { - { - { - match(tokenSet_12_); - } - } - } - else if ((cached_LA1=='\\')) { - match('\\'); - { - { - match(tokenSet_1_); - } - } - } - else - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - - } - { // ( ... )* - for (;;) - { - if ((tokenSet_13_.member(cached_LA1))) - { - { - { - match(tokenSet_13_); - } - } - } - else if ((cached_LA1=='\\')) { - match('\\'); - { - { - match(tokenSet_1_); - } - } - } - else - { - goto _loop351_breakloop; - } - - } -_loop351_breakloop: ; - } // ( ... )* - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mBOM(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = BOM; - - switch ( cached_LA1 ) - { - case '\u00ef': - { - match('\u00EF'); - break; - } - case '\u00bb': - { - match('\u00BB'); - break; - } - case '\u00bf': - { - match('\u00BF'); - if (0==inputState.guessing) - { - _ttype = Token.SKIP; - } - break; - } - default: - { - throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); - } - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mSL_COMMENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = SL_COMMENT; - - match("//"); - { // ( ... )* - for (;;) - { - if ((tokenSet_1_.member(cached_LA1))) - { - { - match(tokenSet_1_); - } - } - else - { - goto _loop361_breakloop; - } - - } -_loop361_breakloop: ; - } // ( ... )* - { - switch ( cached_LA1 ) - { - case '\n': - { - match('\n'); - break; - } - case '\r': - { - match('\r'); - { - if ((cached_LA1=='\n')) - { - match('\n'); - } - else { - } - - } - break; - } - default: - { - } - break; } - } - if (0==inputState.guessing) - { - _ttype = Token.SKIP; newline(); - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - public void mML_COMMENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException -{ - int _ttype; IToken _token=null; int _begin=text.Length; - _ttype = ML_COMMENT; - - match("/*"); - { // ( ... )* - for (;;) - { - if (((cached_LA1=='*') && ((cached_LA2 >= '\u0003' && cached_LA2 <= '\u7ffe')) && ((LA(3) >= '\u0003' && LA(3) <= '\u7ffe')))&&( LA(2)!='/' )) - { - match('*'); - } - else if ((cached_LA1=='\n'||cached_LA1=='\r')) { - mNL(false); - } - else if ((tokenSet_14_.member(cached_LA1))) { - { - match(tokenSet_14_); - } - } - else - { - goto _loop367_breakloop; - } - - } -_loop367_breakloop: ; - } // ( ... )* - match("*/"); - if (0==inputState.guessing) - { - _ttype = Token.SKIP; - } - if (_createToken && (null == _token) && (_ttype != Token.SKIP)) - { - _token = makeToken(_ttype); - _token.setText(text.ToString(_begin, text.Length-_begin)); - } - returnToken_ = _token; - } - - - private static long[] mk_tokenSet_0_() - { - long[] data = new long[1024]; - data[0]=-145135534875656L; - for (int i = 1; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_()); - private static long[] mk_tokenSet_1_() - { - long[] data = new long[1024]; - data[0]=-9224L; - for (int i = 1; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_()); - private static long[] mk_tokenSet_2_() - { - long[] data = new long[513]; - data[0]=68719476736L; - data[1]=576460745995190270L; - for (int i = 2; i<=512; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_()); - private static long[] mk_tokenSet_3_() - { - long[] data = new long[1024]; - data[0]=-17179878408L; - data[1]=-268435457L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_3_ = new BitSet(mk_tokenSet_3_()); - private static long[] mk_tokenSet_4_() - { - long[] data = new long[1024]; - data[0]=-549755823112L; - data[1]=-268435457L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_4_ = new BitSet(mk_tokenSet_4_()); - private static long[] mk_tokenSet_5_() - { - long[] data = new long[1024]; - data[0]=-8L; - data[1]=-576460752303423489L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_5_ = new BitSet(mk_tokenSet_5_()); - private static long[] mk_tokenSet_6_() - { - long[] data = new long[1024]; - data[0]=-1152921504606846984L; - data[1]=-576460752303423489L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_6_ = new BitSet(mk_tokenSet_6_()); - private static long[] mk_tokenSet_7_() - { - long[] data = new long[1024]; - data[0]=-1153062242095211528L; - data[1]=-576460752303423489L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_7_ = new BitSet(mk_tokenSet_7_()); - private static long[] mk_tokenSet_8_() - { - long[] data = new long[1024]; - data[0]=-35184372098056L; - for (int i = 1; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_8_ = new BitSet(mk_tokenSet_8_()); - private static long[] mk_tokenSet_9_() - { - long[] data = new long[1024]; - data[0]=-9224L; - data[1]=-536870913L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_9_ = new BitSet(mk_tokenSet_9_()); - private static long[] mk_tokenSet_10_() - { - long[] data = new long[1024]; - data[0]=-8L; - data[1]=-2882303761517117441L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_10_ = new BitSet(mk_tokenSet_10_()); - private static long[] mk_tokenSet_11_() - { - long[] data = new long[513]; - data[0]=287948901175001088L; - data[1]=541165879422L; - for (int i = 2; i<=512; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_11_ = new BitSet(mk_tokenSet_11_()); - private static long[] mk_tokenSet_12_() - { - long[] data = new long[1024]; - data[0]=-145135534875656L; - data[1]=-268435457L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_12_ = new BitSet(mk_tokenSet_12_()); - private static long[] mk_tokenSet_13_() - { - long[] data = new long[1024]; - data[0]=-140737488364552L; - data[1]=-268435457L; - for (int i = 2; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_13_ = new BitSet(mk_tokenSet_13_()); - private static long[] mk_tokenSet_14_() - { - long[] data = new long[1024]; - data[0]=-4398046520328L; - for (int i = 1; i<=510; i++) { data[i]=-1L; } - data[511]=9223372036854775807L; - for (int i = 512; i<=1023; i++) { data[i]=0L; } - return data; - } - public static readonly BitSet tokenSet_14_ = new BitSet(mk_tokenSet_14_()); - + for (;;) + { + IToken _token = null; + int _ttype = Token.INVALID_TYPE; + resetText(); + try // for char stream error handling + { + try // for lexical error handling + { + switch ( cached_LA1 ) + { + case '?': + { + mQUESTION(true); + theRetToken = returnToken_; + break; + } + case '(': + { + mLPAREN(true); + theRetToken = returnToken_; + break; + } + case ')': + { + mRPAREN(true); + theRetToken = returnToken_; + break; + } + case '[': + { + mLBRACK(true); + theRetToken = returnToken_; + break; + } + case ']': + { + mRBRACK(true); + theRetToken = returnToken_; + break; + } + case '{': + { + mLCURLY(true); + theRetToken = returnToken_; + break; + } + case '}': + { + mRCURLY(true); + theRetToken = returnToken_; + break; + } + case ',': + { + mCOMMA(true); + theRetToken = returnToken_; + break; + } + case '~': + { + mBNOT(true); + theRetToken = returnToken_; + break; + } + case '@': + { + mE4X_ATTRI(true); + theRetToken = returnToken_; + break; + } + case ';': + { + mSEMI(true); + theRetToken = returnToken_; + break; + } + case '$': case 'A': case 'B': case 'C': + case 'D': case 'E': case 'F': case 'G': + case 'H': case 'I': case 'J': case 'K': + case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': + case 'T': case 'U': case 'V': case 'W': + case 'X': case 'Y': case 'Z': case '_': + case 'a': case 'b': case 'c': case 'd': + case 'e': case 'f': case 'g': case 'h': + case 'i': case 'j': case 'k': case 'l': + case 'm': case 'n': case 'o': case 'p': + case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': + case 'y': case 'z': + { + mIDENT(true); + theRetToken = returnToken_; + break; + } + case '"': case '\'': + { + mSTRING_LITERAL(true); + theRetToken = returnToken_; + break; + } + case '\t': case '\n': case '\u000c': case '\r': + case ' ': + { + mWS(true); + theRetToken = returnToken_; + break; + } + case '.': case '0': case '1': case '2': + case '3': case '4': case '5': case '6': + case '7': case '8': case '9': + { + mNUMBER(true); + theRetToken = returnToken_; + break; + } + case '\u00bb': case '\u00bf': case '\u00ef': + { + mBOM(true); + theRetToken = returnToken_; + break; + } + default: + if ((cached_LA1=='>') && (cached_LA2=='>') && (LA(3)=='>') && (LA(4)=='=')) + { + mBSR_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='=') && (cached_LA2=='=') && (LA(3)=='=')) { + mSTRICT_EQUAL(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='!') && (cached_LA2=='=') && (LA(3)=='=')) { + mSTRICT_NOT_EQUAL(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='>') && (cached_LA2=='>') && (LA(3)=='=')) { + mSR_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='>') && (cached_LA2=='>') && (LA(3)=='>') && (true)) { + mBSR(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='<') && (cached_LA2=='<') && (LA(3)=='=')) { + mSL_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='&') && (cached_LA2=='&') && (LA(3)=='=')) { + mLAND_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='|') && (cached_LA2=='|') && (LA(3)=='=')) { + mLOR_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='/') && (tokenSet_0_.member(cached_LA2)) && (tokenSet_1_.member(LA(3)))) { + mREGEX_LITERAL(true); + theRetToken = returnToken_; + } + else if ((cached_LA1==':') && (cached_LA2==':')) { + mDBL_COLON(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='=') && (cached_LA2=='=') && (true)) { + mEQUAL(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='!') && (cached_LA2=='=') && (true)) { + mNOT_EQUAL(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='/') && (cached_LA2=='=') && (true)) { + mDIV_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='+') && (cached_LA2=='=')) { + mPLUS_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='+') && (cached_LA2=='+')) { + mINC(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='-') && (cached_LA2=='=')) { + mMINUS_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='-') && (cached_LA2=='-')) { + mDEC(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='*') && (cached_LA2=='=')) { + mSTAR_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='%') && (cached_LA2=='=')) { + mMOD_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='>') && (cached_LA2=='>') && (true)) { + mSR(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='>') && (cached_LA2=='=')) { + mGE(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='<') && (cached_LA2=='<') && (true)) { + mSL(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='<') && (cached_LA2=='=')) { + mLE(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='^') && (cached_LA2=='=')) { + mBXOR_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='|') && (cached_LA2=='=')) { + mBOR_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='|') && (cached_LA2=='|') && (true)) { + mLOR(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='&') && (cached_LA2=='=')) { + mBAND_ASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='&') && (cached_LA2=='&') && (true)) { + mLAND(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='<') && (tokenSet_2_.member(cached_LA2))) { + mXML_LITERAL(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='/') && (cached_LA2=='/')) { + mSL_COMMENT(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='/') && (cached_LA2=='*')) { + mML_COMMENT(true); + theRetToken = returnToken_; + } + else if ((cached_LA1==':') && (true)) { + mCOLON(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='=') && (true)) { + mASSIGN(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='!') && (true)) { + mLNOT(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='/') && (true)) { + mDIV(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='+') && (true)) { + mPLUS(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='-') && (true)) { + mMINUS(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='*') && (true)) { + mSTAR(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='%') && (true)) { + mMOD(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='>') && (true)) { + mGT(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='<') && (true)) { + mLWT(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='^') && (true)) { + mBXOR(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='|') && (true)) { + mBOR(true); + theRetToken = returnToken_; + } + else if ((cached_LA1=='&') && (true)) { + mBAND(true); + theRetToken = returnToken_; + } + else + { + if (cached_LA1==EOF_CHAR) { uponEOF(); returnToken_ = makeToken(Token.EOF_TYPE); } + else {throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());} + } + break; } + if ( null==returnToken_ ) goto tryAgain; // found SKIP token + _ttype = returnToken_.Type; + returnToken_.Type = _ttype; + return returnToken_; + } + catch (RecognitionException e) { + throw new TokenStreamRecognitionException(e); + } + } + catch (CharStreamException cse) { + if ( cse is CharStreamIOException ) { + throw new TokenStreamIOException(((CharStreamIOException)cse).io); + } + else { + throw new TokenStreamException(cse.Message); + } + } + } + } + + public void mQUESTION(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = QUESTION; + + match('?'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LPAREN; + + match('('); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mRPAREN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = RPAREN; + + match(')'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLBRACK(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LBRACK; + + match('['); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mRBRACK(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = RBRACK; + + match(']'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLCURLY(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LCURLY; + + match('{'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mRCURLY(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = RCURLY; + + match('}'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mCOLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = COLON; + + match(':'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mDBL_COLON(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = DBL_COLON; + + match("::"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mCOMMA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = COMMA; + + match(','); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = ASSIGN; + + match('='); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mEQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = EQUAL; + + match("=="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSTRICT_EQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = STRICT_EQUAL; + + match("==="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLNOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LNOT; + + match('!'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBNOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BNOT; + + match('~'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mNOT_EQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = NOT_EQUAL; + + match("!="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSTRICT_NOT_EQUAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = STRICT_NOT_EQUAL; + + match("!=="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mDIV(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = DIV; + + match('/'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mDIV_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = DIV_ASSIGN; + + match("/="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mPLUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = PLUS; + + match('+'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mPLUS_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = PLUS_ASSIGN; + + match("+="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mINC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = INC; + + match("++"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mMINUS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = MINUS; + + match('-'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mMINUS_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = MINUS_ASSIGN; + + match("-="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mDEC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = DEC; + + match("--"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSTAR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = STAR; + + match('*'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSTAR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = STAR_ASSIGN; + + match("*="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mMOD(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = MOD; + + match('%'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mMOD_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = MOD_ASSIGN; + + match("%="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = SR; + + match(">>"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = SR_ASSIGN; + + match(">>="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBSR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BSR; + + match(">>>"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBSR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BSR_ASSIGN; + + match(">>>="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mGE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = GE; + + match(">="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mGT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = GT; + + match('>'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = SL; + + match("<<"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSL_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = SL_ASSIGN; + + match("<<="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LE; + + match("<="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLWT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LWT; + + match('<'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBXOR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BXOR; + + match('^'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBXOR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BXOR_ASSIGN; + + match("^="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBOR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BOR; + + match('|'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBOR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BOR_ASSIGN; + + match("|="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLOR(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LOR; + + match("||"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBAND(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BAND; + + match('&'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBAND_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BAND_ASSIGN; + + match("&="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLAND(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LAND; + + match("&&"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLAND_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LAND_ASSIGN; + + match("&&="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mLOR_ASSIGN(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = LOR_ASSIGN; + + match("||="); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mE4X_ATTRI(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = E4X_ATTRI; + + match('@'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSEMI(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = SEMI; + + match(';'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + private void mDOT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = DOT; + + match('.'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + private void mE4X_DESC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = E4X_DESC; + + match(".."); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + private void mREST(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = REST; + + match("..."); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mIDENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = IDENT; + + { + switch ( cached_LA1 ) + { + case 'a': case 'b': case 'c': case 'd': + case 'e': case 'f': case 'g': case 'h': + case 'i': case 'j': case 'k': case 'l': + case 'm': case 'n': case 'o': case 'p': + case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': + case 'y': case 'z': + { + matchRange('a','z'); + break; + } + case 'A': case 'B': case 'C': case 'D': + case 'E': case 'F': case 'G': case 'H': + case 'I': case 'J': case 'K': case 'L': + case 'M': case 'N': case 'O': case 'P': + case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': + case 'Y': case 'Z': + { + matchRange('A','Z'); + break; + } + case '_': + { + match('_'); + break; + } + case '$': + { + match('$'); + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + { // ( ... )* + for (;;) + { + if (((cached_LA1 >= 'a' && cached_LA1 <= 'z')) && (true) && (true) && (true)) + { + matchRange('a','z'); + } + else if (((cached_LA1 >= 'A' && cached_LA1 <= 'Z')) && (true) && (true) && (true)) { + matchRange('A','Z'); + } + else if ((cached_LA1=='_') && (true) && (true) && (true)) { + match('_'); + } + else if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) { + matchRange('0','9'); + } + else if ((cached_LA1=='$') && (true) && (true) && (true)) { + match('$'); + } + else + { + goto _loop271_breakloop; + } + + } +_loop271_breakloop: ; + } // ( ... )* + _ttype = testLiteralsTable(_ttype); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSTRING_LITERAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = STRING_LITERAL; + + switch ( cached_LA1 ) + { + case '"': + { + match('"'); + { // ( ... )* + for (;;) + { + if ((cached_LA1=='\\')) + { + mESC(false); + } + else if ((tokenSet_3_.member(cached_LA1))) { + { + match(tokenSet_3_); + } + } + else + { + goto _loop275_breakloop; + } + + } +_loop275_breakloop: ; + } // ( ... )* + match('"'); + break; + } + case '\'': + { + match('\''); + { // ( ... )* + for (;;) + { + if ((cached_LA1=='\\')) + { + mESC(false); + } + else if ((tokenSet_4_.member(cached_LA1))) { + { + match(tokenSet_4_); + } + } + else + { + goto _loop278_breakloop; + } + + } +_loop278_breakloop: ; + } // ( ... )* + match('\''); + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mESC(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = ESC; + + match('\\'); + { + switch ( cached_LA1 ) + { + case 'n': + { + match('n'); + break; + } + case 'r': + { + match('r'); + break; + } + case 't': + { + match('t'); + break; + } + case 'b': + { + match('b'); + break; + } + case 'f': + { + match('f'); + break; + } + case '"': + { + match('"'); + break; + } + case '\'': + { + match('\''); + break; + } + case '\\': + { + match('\\'); + break; + } + case 'u': + { + { // ( ... )+ + int _cnt378=0; + for (;;) + { + if ((cached_LA1=='u')) + { + match('u'); + } + else + { + if (_cnt378 >= 1) { goto _loop378_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } + } + + _cnt378++; + } +_loop378_breakloop: ; + } // ( ... )+ + mHEX_DIGIT(false); + mHEX_DIGIT(false); + mHEX_DIGIT(false); + mHEX_DIGIT(false); + break; + } + case '0': case '1': case '2': case '3': + { + matchRange('0','3'); + { + if (((cached_LA1 >= '0' && cached_LA1 <= '7')) && (tokenSet_1_.member(cached_LA2)) && (true) && (true)) + { + matchRange('0','7'); + { + if (((cached_LA1 >= '0' && cached_LA1 <= '7')) && (tokenSet_1_.member(cached_LA2)) && (true) && (true)) + { + matchRange('0','7'); + } + else if ((tokenSet_1_.member(cached_LA1)) && (true) && (true) && (true)) { + } + else + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + + } + } + else if ((tokenSet_1_.member(cached_LA1)) && (true) && (true) && (true)) { + } + else + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + + } + break; + } + case '4': case '5': case '6': case '7': + { + matchRange('4','7'); + { + if (((cached_LA1 >= '0' && cached_LA1 <= '7')) && (tokenSet_1_.member(cached_LA2)) && (true) && (true)) + { + matchRange('0','7'); + } + else if ((tokenSet_1_.member(cached_LA1)) && (true) && (true) && (true)) { + } + else + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + + } + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mXML_LITERAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = XML_LITERAL; + + match('<'); + mIDENT(false); + { // ( ... )* + for (;;) + { + switch ( cached_LA1 ) + { + case '\t': case '\n': case '\u000c': case '\r': + case ' ': + { + mWS(false); + break; + } + case '$': case 'A': case 'B': case 'C': + case 'D': case 'E': case 'F': case 'G': + case 'H': case 'I': case 'J': case 'K': + case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': + case 'T': case 'U': case 'V': case 'W': + case 'X': case 'Y': case 'Z': case '_': + case 'a': case 'b': case 'c': case 'd': + case 'e': case 'f': case 'g': case 'h': + case 'i': case 'j': case 'k': case 'l': + case 'm': case 'n': case 'o': case 'p': + case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': + case 'y': case 'z': + { + mXML_ATTRIBUTE(false); + break; + } + default: + { + goto _loop281_breakloop; + } + } + } +_loop281_breakloop: ; + } // ( ... )* + { + switch ( cached_LA1 ) + { + case '>': + { + match('>'); + { // ( ... )* + for (;;) + { + if ((cached_LA1=='\t'||cached_LA1=='\n'||cached_LA1=='\u000c'||cached_LA1=='\r'||cached_LA1==' ') && (tokenSet_5_.member(cached_LA2)) && (tokenSet_5_.member(LA(3))) && (tokenSet_5_.member(LA(4)))) + { + mWS(false); + } + else if ((tokenSet_6_.member(cached_LA1)) && (tokenSet_5_.member(cached_LA2)) && (tokenSet_5_.member(LA(3))) && (tokenSet_5_.member(LA(4)))) { + mXML_TEXTNODE(false); + } + else if ((cached_LA1=='<') && (cached_LA2=='!') && (LA(3)=='-')) { + mXML_COMMENT(false); + } + else if ((cached_LA1=='<') && (cached_LA2=='!') && (LA(3)=='[')) { + mXML_CDATA(false); + } + else if ((cached_LA1=='<') && (tokenSet_2_.member(cached_LA2))) { + mXML_LITERAL(false); + } + else + { + goto _loop284_breakloop; + } + + } +_loop284_breakloop: ; + } // ( ... )* + match("'); + break; + } + case '/': + { + match("/>"); + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mWS(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = WS; + + { // ( ... )+ + int _cnt354=0; + for (;;) + { + if ((cached_LA1==' ') && (true) && (true) && (true)) + { + match(' '); + } + else if ((cached_LA1=='\t') && (true) && (true) && (true)) { + match('\t'); + } + else if ((cached_LA1=='\u000c') && (true) && (true) && (true)) { + match('\f'); + } + else if ((cached_LA1=='\n'||cached_LA1=='\r') && (true) && (true) && (true)) { + mNL(false); + } + else + { + if (_cnt354 >= 1) { goto _loop354_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } + } + + _cnt354++; + } +_loop354_breakloop: ; + } // ( ... )+ + if (0==inputState.guessing) + { + _ttype = Token.SKIP; + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mXML_ATTRIBUTE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = XML_ATTRIBUTE; + + mIDENT(false); + { // ( ... )* + for (;;) + { + if ((cached_LA1=='\t'||cached_LA1=='\n'||cached_LA1=='\u000c'||cached_LA1=='\r'||cached_LA1==' ')) + { + mWS(false); + } + else + { + goto _loop287_breakloop; + } + + } +_loop287_breakloop: ; + } // ( ... )* + mASSIGN(false); + { // ( ... )* + for (;;) + { + if ((cached_LA1=='\t'||cached_LA1=='\n'||cached_LA1=='\u000c'||cached_LA1=='\r'||cached_LA1==' ')) + { + mWS(false); + } + else + { + goto _loop289_breakloop; + } + + } +_loop289_breakloop: ; + } // ( ... )* + { + switch ( cached_LA1 ) + { + case '"': case '\'': + { + mSTRING_LITERAL(false); + break; + } + case '{': + { + mXML_BINDING(false); + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mXML_TEXTNODE(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = XML_TEXTNODE; + + { + if ((cached_LA1=='\n'||cached_LA1=='\r')) + { + mNL(false); + } + else if (((cached_LA1=='/'))&&( LA(2)!='>' )) { + match('/'); + } + else if ((tokenSet_7_.member(cached_LA1))) { + { + match(tokenSet_7_); + } + } + else + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mXML_COMMENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = XML_COMMENT; + + match(""); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mXML_CDATA(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = XML_CDATA; + + match("= '\u0003' && cached_LA2 <= '\u7ffe')) && ((LA(3) >= '\u0003' && LA(3) <= '\u7ffe')) && ((LA(4) >= '\u0003' && LA(4) <= '\u7ffe')))&&( LA(2)!=']')) + { + match(']'); + } + else if ((cached_LA1=='\n'||cached_LA1=='\r')) { + mNL(false); + } + else if ((tokenSet_9_.member(cached_LA1))) { + { + match(tokenSet_9_); + } + } + else + { + goto _loop307_breakloop; + } + + } +_loop307_breakloop: ; + } // ( ... )* + match("]]>"); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mXML_BINDING(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = XML_BINDING; + + match('{'); + mXML_AS3_EXPRESSION(false); + match('}'); + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mXML_AS3_EXPRESSION(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = XML_AS3_EXPRESSION; + + { + { // ( ... )* + for (;;) + { + if ((tokenSet_10_.member(cached_LA1))) + { + { + match(tokenSet_10_); + } + } + else + { + goto _loop296_breakloop; + } + + } +_loop296_breakloop: ; + } // ( ... )* + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mNL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = NL; + + { + if ((cached_LA1=='\r') && (cached_LA2=='\n') && (true) && (true)) + { + match('\r'); + match('\n'); + } + else if ((cached_LA1=='\r') && (true) && (true) && (true)) { + match('\r'); + } + else if ((cached_LA1=='\n')) { + match('\n'); + } + else + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + + } + if (0==inputState.guessing) + { + newline(); _ttype = Token.SKIP; + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mNUMBER(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = NUMBER; + Token t=null; + + if ((cached_LA1=='.') && (cached_LA2=='.') && (LA(3)=='.')) + { + match("..."); + if (0==inputState.guessing) + { + _ttype = REST; + } + } + else if ((cached_LA1=='.') && (cached_LA2=='.') && (true)) { + match(".."); + if (0==inputState.guessing) + { + _ttype = E4X_DESC; + } + } + else if ((cached_LA1=='.') && (true)) { + match('.'); + if (0==inputState.guessing) + { + _ttype = DOT; + } + { + if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) + { + { // ( ... )+ + int _cnt311=0; + for (;;) + { + if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) + { + matchRange('0','9'); + } + else + { + if (_cnt311 >= 1) { goto _loop311_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } + } + + _cnt311++; + } +_loop311_breakloop: ; + } // ( ... )+ + { + if ((cached_LA1=='E'||cached_LA1=='e')) + { + mEXPONENT(false); + } + else { + } + + } + if (0==inputState.guessing) + { + _ttype = NUMBER; + } + } + else { + } + + } + } + else if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) { + { + switch ( cached_LA1 ) + { + case '0': + { + match('0'); + { + if ((cached_LA1=='X'||cached_LA1=='x')) + { + { + switch ( cached_LA1 ) + { + case 'X': + { + match('X'); + break; + } + case 'x': + { + match('x'); + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + { // ( ... )+ + int _cnt317=0; + for (;;) + { + if ((tokenSet_11_.member(cached_LA1))) + { + mHEX_DIGIT(false); + } + else + { + if (_cnt317 >= 1) { goto _loop317_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } + } + + _cnt317++; + } +_loop317_breakloop: ; + } // ( ... )+ + } + else if (((cached_LA1 >= '0' && cached_LA1 <= '7')) && (true) && (true) && (true)) { + { // ( ... )+ + int _cnt333=0; + for (;;) + { + if (((cached_LA1 >= '0' && cached_LA1 <= '7'))) + { + matchRange('0','7'); + } + else + { + if (_cnt333 >= 1) { goto _loop333_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } + } + + _cnt333++; + } +_loop333_breakloop: ; + } // ( ... )+ + } + else { + bool synPredMatched325 = false; + if (( true )) + { + int _m325 = mark(); + synPredMatched325 = true; + inputState.guessing++; + try { + { + { // ( ... )* + for (;;) + { + if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) + { + matchRange('0','9'); + } + else + { + goto _loop320_breakloop; + } + + } +_loop320_breakloop: ; + } // ( ... )* + { + if ((cached_LA1=='.')) + { + match('.'); + { // ( ... )+ + int _cnt323=0; + for (;;) + { + if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) + { + matchRange('0','9'); + } + else + { + if (_cnt323 >= 1) { goto _loop323_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } + } + + _cnt323++; + } +_loop323_breakloop: ; + } // ( ... )+ + } + else { + } + + } + { + if ((cached_LA1=='E'||cached_LA1=='e')) + { + mEXPONENT(false); + } + else { + } + + } + } + } + catch (RecognitionException) + { + synPredMatched325 = false; + } + rewind(_m325); + inputState.guessing--; + } + if ( synPredMatched325 ) + { + { // ( ... )* + for (;;) + { + if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) + { + matchRange('0','9'); + } + else + { + goto _loop327_breakloop; + } + + } +_loop327_breakloop: ; + } // ( ... )* + { + if ((cached_LA1=='.')) + { + match('.'); + { // ( ... )+ + int _cnt330=0; + for (;;) + { + if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) + { + matchRange('0','9'); + } + else + { + if (_cnt330 >= 1) { goto _loop330_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } + } + + _cnt330++; + } +_loop330_breakloop: ; + } // ( ... )+ + } + else { + } + + } + { + if ((cached_LA1=='E'||cached_LA1=='e')) + { + mEXPONENT(false); + } + else { + } + + } + } + else { + } + } + } + break; + } + case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': + case '9': + { + { + matchRange('1','9'); + } + { // ( ... )* + for (;;) + { + if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) + { + matchRange('0','9'); + } + else + { + goto _loop336_breakloop; + } + + } +_loop336_breakloop: ; + } // ( ... )* + if (0==inputState.guessing) + { + _ttype = NUMBER; + } + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + } + else + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mEXPONENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = EXPONENT; + + { + switch ( cached_LA1 ) + { + case 'e': + { + match('e'); + break; + } + case 'E': + { + match('E'); + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + { + switch ( cached_LA1 ) + { + case '+': + { + match('+'); + break; + } + case '-': + { + match('-'); + break; + } + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + case '8': case '9': + { + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + { // ( ... )+ + int _cnt372=0; + for (;;) + { + if (((cached_LA1 >= '0' && cached_LA1 <= '9'))) + { + matchRange('0','9'); + } + else + { + if (_cnt372 >= 1) { goto _loop372_breakloop; } else { throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn());; } + } + + _cnt372++; + } +_loop372_breakloop: ; + } // ( ... )+ + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mHEX_DIGIT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = HEX_DIGIT; + + { + switch ( cached_LA1 ) + { + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + case '8': case '9': + { + matchRange('0','9'); + break; + } + case 'A': case 'B': case 'C': case 'D': + case 'E': case 'F': + { + matchRange('A','F'); + break; + } + case 'a': case 'b': case 'c': case 'd': + case 'e': case 'f': + { + matchRange('a','f'); + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mREGEX_LITERAL(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = REGEX_LITERAL; + + match('/'); + mREGEX_BODY(false); + match('/'); + { // ( ... )* + for (;;) + { + switch ( cached_LA1 ) + { + case 'a': case 'b': case 'c': case 'd': + case 'e': case 'f': case 'g': case 'h': + case 'i': case 'j': case 'k': case 'l': + case 'm': case 'n': case 'o': case 'p': + case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': + case 'y': case 'z': + { + matchRange('a','z'); + break; + } + case 'A': case 'B': case 'C': case 'D': + case 'E': case 'F': case 'G': case 'H': + case 'I': case 'J': case 'K': case 'L': + case 'M': case 'N': case 'O': case 'P': + case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': + case 'Y': case 'Z': + { + matchRange('A','Z'); + break; + } + case '_': + { + match('_'); + break; + } + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + case '8': case '9': + { + matchRange('0','9'); + break; + } + case '$': + { + match('$'); + break; + } + default: + { + goto _loop339_breakloop; + } + } + } +_loop339_breakloop: ; + } // ( ... )* + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + protected void mREGEX_BODY(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = REGEX_BODY; + + { + if ((tokenSet_12_.member(cached_LA1))) + { + { + { + match(tokenSet_12_); + } + } + } + else if ((cached_LA1=='\\')) { + match('\\'); + { + { + match(tokenSet_1_); + } + } + } + else + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + + } + { // ( ... )* + for (;;) + { + if ((tokenSet_13_.member(cached_LA1))) + { + { + { + match(tokenSet_13_); + } + } + } + else if ((cached_LA1=='\\')) { + match('\\'); + { + { + match(tokenSet_1_); + } + } + } + else + { + goto _loop351_breakloop; + } + + } +_loop351_breakloop: ; + } // ( ... )* + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mBOM(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = BOM; + + switch ( cached_LA1 ) + { + case '\u00ef': + { + match('\u00EF'); + break; + } + case '\u00bb': + { + match('\u00BB'); + break; + } + case '\u00bf': + { + match('\u00BF'); + if (0==inputState.guessing) + { + _ttype = Token.SKIP; + } + break; + } + default: + { + throw new NoViableAltForCharException(cached_LA1, getFilename(), getLine(), getColumn()); + } + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mSL_COMMENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = SL_COMMENT; + + match("//"); + { // ( ... )* + for (;;) + { + if ((tokenSet_1_.member(cached_LA1))) + { + { + match(tokenSet_1_); + } + } + else + { + goto _loop361_breakloop; + } + + } +_loop361_breakloop: ; + } // ( ... )* + { + switch ( cached_LA1 ) + { + case '\n': + { + match('\n'); + break; + } + case '\r': + { + match('\r'); + { + if ((cached_LA1=='\n')) + { + match('\n'); + } + else { + } + + } + break; + } + default: + { + } + break; } + } + if (0==inputState.guessing) + { + _ttype = Token.SKIP; newline(); + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + public void mML_COMMENT(bool _createToken) //throws RecognitionException, CharStreamException, TokenStreamException +{ + int _ttype; IToken _token=null; int _begin=text.Length; + _ttype = ML_COMMENT; + + match("/*"); + { // ( ... )* + for (;;) + { + if (((cached_LA1=='*') && ((cached_LA2 >= '\u0003' && cached_LA2 <= '\u7ffe')) && ((LA(3) >= '\u0003' && LA(3) <= '\u7ffe')))&&( LA(2)!='/' )) + { + match('*'); + } + else if ((cached_LA1=='\n'||cached_LA1=='\r')) { + mNL(false); + } + else if ((tokenSet_14_.member(cached_LA1))) { + { + match(tokenSet_14_); + } + } + else + { + goto _loop367_breakloop; + } + + } +_loop367_breakloop: ; + } // ( ... )* + match("*/"); + if (0==inputState.guessing) + { + _ttype = Token.SKIP; + } + if (_createToken && (null == _token) && (_ttype != Token.SKIP)) + { + _token = makeToken(_ttype); + _token.setText(text.ToString(_begin, text.Length-_begin)); + } + returnToken_ = _token; + } + + + private static long[] mk_tokenSet_0_() + { + long[] data = new long[1024]; + data[0]=-145135534875656L; + for (int i = 1; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_()); + private static long[] mk_tokenSet_1_() + { + long[] data = new long[1024]; + data[0]=-9224L; + for (int i = 1; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_()); + private static long[] mk_tokenSet_2_() + { + long[] data = new long[513]; + data[0]=68719476736L; + data[1]=576460745995190270L; + for (int i = 2; i<=512; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_()); + private static long[] mk_tokenSet_3_() + { + long[] data = new long[1024]; + data[0]=-17179878408L; + data[1]=-268435457L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_3_ = new BitSet(mk_tokenSet_3_()); + private static long[] mk_tokenSet_4_() + { + long[] data = new long[1024]; + data[0]=-549755823112L; + data[1]=-268435457L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_4_ = new BitSet(mk_tokenSet_4_()); + private static long[] mk_tokenSet_5_() + { + long[] data = new long[1024]; + data[0]=-8L; + data[1]=-576460752303423489L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_5_ = new BitSet(mk_tokenSet_5_()); + private static long[] mk_tokenSet_6_() + { + long[] data = new long[1024]; + data[0]=-1152921504606846984L; + data[1]=-576460752303423489L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_6_ = new BitSet(mk_tokenSet_6_()); + private static long[] mk_tokenSet_7_() + { + long[] data = new long[1024]; + data[0]=-1153062242095211528L; + data[1]=-576460752303423489L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_7_ = new BitSet(mk_tokenSet_7_()); + private static long[] mk_tokenSet_8_() + { + long[] data = new long[1024]; + data[0]=-35184372098056L; + for (int i = 1; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_8_ = new BitSet(mk_tokenSet_8_()); + private static long[] mk_tokenSet_9_() + { + long[] data = new long[1024]; + data[0]=-9224L; + data[1]=-536870913L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_9_ = new BitSet(mk_tokenSet_9_()); + private static long[] mk_tokenSet_10_() + { + long[] data = new long[1024]; + data[0]=-8L; + data[1]=-2882303761517117441L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_10_ = new BitSet(mk_tokenSet_10_()); + private static long[] mk_tokenSet_11_() + { + long[] data = new long[513]; + data[0]=287948901175001088L; + data[1]=541165879422L; + for (int i = 2; i<=512; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_11_ = new BitSet(mk_tokenSet_11_()); + private static long[] mk_tokenSet_12_() + { + long[] data = new long[1024]; + data[0]=-145135534875656L; + data[1]=-268435457L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_12_ = new BitSet(mk_tokenSet_12_()); + private static long[] mk_tokenSet_13_() + { + long[] data = new long[1024]; + data[0]=-140737488364552L; + data[1]=-268435457L; + for (int i = 2; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_13_ = new BitSet(mk_tokenSet_13_()); + private static long[] mk_tokenSet_14_() + { + long[] data = new long[1024]; + data[0]=-4398046520328L; + for (int i = 1; i<=510; i++) { data[i]=-1L; } + data[511]=9223372036854775807L; + for (int i = 512; i<=1023; i++) { data[i]=0L; } + return data; + } + public static readonly BitSet tokenSet_14_ = new BitSet(mk_tokenSet_14_()); + } } diff --git a/External/Plugins/AS3Context/Grammar/AS3Parser.cs b/External/Plugins/AS3Context/Grammar/AS3Parser.cs index 6037b7e559..c8616342c9 100644 --- a/External/Plugins/AS3Context/Grammar/AS3Parser.cs +++ b/External/Plugins/AS3Context/Grammar/AS3Parser.cs @@ -34,5806 +34,5806 @@ namespace AS3Context.Grammar { - // Generate the header common to all output files. - using System; - - using TokenBuffer = antlr.TokenBuffer; - using TokenStreamException = antlr.TokenStreamException; - using TokenStreamIOException = antlr.TokenStreamIOException; - using ANTLRException = antlr.ANTLRException; - using LLkParser = antlr.LLkParser; - using Token = antlr.Token; - using IToken = antlr.IToken; - using TokenStream = antlr.TokenStream; - using RecognitionException = antlr.RecognitionException; - using NoViableAltException = antlr.NoViableAltException; - using MismatchedTokenException = antlr.MismatchedTokenException; - using SemanticException = antlr.SemanticException; - using ParserSharedInputState = antlr.ParserSharedInputState; - using BitSet = antlr.collections.impl.BitSet; - using AST = antlr.collections.AST; - using ASTPair = antlr.ASTPair; - using ASTFactory = antlr.ASTFactory; - using ASTArray = antlr.collections.impl.ASTArray; - + // Generate the header common to all output files. + using System; + + using TokenBuffer = antlr.TokenBuffer; + using TokenStreamException = antlr.TokenStreamException; + using TokenStreamIOException = antlr.TokenStreamIOException; + using ANTLRException = antlr.ANTLRException; + using LLkParser = antlr.LLkParser; + using Token = antlr.Token; + using IToken = antlr.IToken; + using TokenStream = antlr.TokenStream; + using RecognitionException = antlr.RecognitionException; + using NoViableAltException = antlr.NoViableAltException; + using MismatchedTokenException = antlr.MismatchedTokenException; + using SemanticException = antlr.SemanticException; + using ParserSharedInputState = antlr.ParserSharedInputState; + using BitSet = antlr.collections.impl.BitSet; + using AST = antlr.collections.AST; + using ASTPair = antlr.ASTPair; + using ASTFactory = antlr.ASTFactory; + using ASTArray = antlr.collections.impl.ASTArray; + /** - * @author Martin Schnabel + * @author Martin Schnabel */ - public class AS3Parser : antlr.LLkParser - { - public const int EOF = 1; - public const int NULL_TREE_LOOKAHEAD = 3; - public const int COMPILATION_UNIT = 4; - public const int IMPORT = 5; - public const int CLASS_DEF = 6; - public const int INTERFACE_DEF = 7; - public const int EXTENDS_CLAUSE = 8; - public const int IMPLEMENTS_CLAUSE = 9; - public const int TYPE_BLOCK = 10; - public const int MODIFIERS = 11; - public const int VARIABLE_DEF = 12; - public const int METHOD_DEF = 13; - public const int NAMESPACE_DEF = 14; - public const int PARAMS = 15; - public const int PARAM = 16; - public const int TYPE_SPEC = 17; - public const int BLOCK = 18; - public const int EXPR = 19; - public const int ELIST = 20; - public const int EXPR_STMNT = 21; - public const int NEW_EXPR = 22; - public const int ENCPS_EXPR = 23; - public const int VAR_INIT = 24; - public const int METHOD_CALL = 25; - public const int ARRAY_ACC = 26; - public const int UNARY_PLUS = 27; - public const int UNARY_MINUS = 28; - public const int POST_INC = 29; - public const int POST_DEC = 30; - public const int ARRAY_LITERAL = 31; - public const int ELEMENT = 32; - public const int OBJECT_LITERAL = 33; - public const int OBJECT_FIELD = 34; - public const int FUNC_DEF = 35; - public const int FOR_INIT = 36; - public const int FOR_CONDITION = 37; - public const int FOR_ITERATOR = 38; - public const int LITERAL_package = 39; - public const int LCURLY = 40; - public const int SEMI = 41; - public const int RCURLY = 42; - public const int LITERAL_import = 43; - public const int LBRACK = 44; - public const int COMMA = 45; - public const int RBRACK = 46; - public const int LPAREN = 47; - public const int RPAREN = 48; - public const int LITERAL_class = 49; - public const int LITERAL_interface = 50; - public const int LITERAL_extends = 51; - public const int LITERAL_implements = 52; - public const int LITERAL_function = 53; - public const int LITERAL_get = 54; - public const int LITERAL_set = 55; - // "/n" = 56 - // "/r" = 57 - public const int IDENT = 58; - public const int LITERAL_namespace = 59; - public const int LITERAL_var = 60; - public const int LITERAL_const = 61; - public const int ASSIGN = 62; - public const int REST = 63; - public const int LITERAL_while = 64; - public const int LITERAL_do = 65; - public const int LITERAL_with = 66; - public const int LITERAL_if = 67; - public const int LITERAL_else = 68; - public const int LITERAL_throw = 69; - public const int LITERAL_return = 70; - public const int LITERAL_continue = 71; - public const int LITERAL_break = 72; - public const int LITERAL_switch = 73; - public const int LITERAL_case = 74; - public const int COLON = 75; - public const int LITERAL_default = 76; - public const int LITERAL_for = 77; - public const int LITERAL_each = 78; - public const int LITERAL_in = 79; - public const int DOT = 80; - public const int STAR = 81; - public const int LITERAL_public = 82; - public const int LITERAL_private = 83; - public const int LITERAL_protected = 84; - public const int LITERAL_internal = 85; - public const int LITERAL_static = 86; - public const int LITERAL_final = 87; - public const int LITERAL_enumerable = 88; - public const int LITERAL_explicit = 89; - public const int LITERAL_override = 90; - public const int LITERAL_dynamic = 91; - public const int NUMBER = 92; - public const int STAR_ASSIGN = 93; - public const int DIV_ASSIGN = 94; - public const int MOD_ASSIGN = 95; - public const int PLUS_ASSIGN = 96; - public const int MINUS_ASSIGN = 97; - public const int SL_ASSIGN = 98; - public const int SR_ASSIGN = 99; - public const int BSR_ASSIGN = 100; - public const int BAND_ASSIGN = 101; - public const int BXOR_ASSIGN = 102; - public const int BOR_ASSIGN = 103; - public const int LAND_ASSIGN = 104; - public const int LOR_ASSIGN = 105; - public const int QUESTION = 106; - public const int LOR = 107; - public const int LAND = 108; - public const int BOR = 109; - public const int BXOR = 110; - public const int BAND = 111; - public const int STRICT_EQUAL = 112; - public const int STRICT_NOT_EQUAL = 113; - public const int NOT_EQUAL = 114; - public const int EQUAL = 115; - public const int LWT = 116; - public const int GT = 117; - public const int LE = 118; - public const int GE = 119; - public const int LITERAL_is = 120; - public const int LITERAL_as = 121; - public const int SL = 122; - public const int SR = 123; - public const int BSR = 124; - public const int PLUS = 125; - public const int MINUS = 126; - public const int DIV = 127; - public const int MOD = 128; - public const int INC = 129; - public const int DEC = 130; - public const int LITERAL_delete = 131; - public const int LITERAL_typeof = 132; - public const int LNOT = 133; - public const int BNOT = 134; - public const int E4X_DESC = 135; - public const int E4X_ATTRI = 136; - public const int LITERAL_null = 137; - public const int LITERAL_true = 138; - public const int LITERAL_false = 139; - public const int LITERAL_undefined = 140; - public const int STRING_LITERAL = 141; - public const int REGEX_LITERAL = 142; - public const int XML_LITERAL = 143; - public const int LITERAL_new = 144; - public const int DBL_COLON = 145; - public const int XML_ATTRIBUTE = 146; - public const int XML_BINDING = 147; - public const int XML_AS3_EXPRESSION = 148; - public const int XML_TEXTNODE = 149; - public const int XML_COMMENT = 150; - public const int XML_CDATA = 151; - public const int REGEX_BODY = 152; - public const int WS = 153; - public const int NL = 154; - public const int BOM = 155; - public const int SL_COMMENT = 156; - public const int ML_COMMENT = 157; - public const int EXPONENT = 158; - public const int HEX_DIGIT = 159; - public const int ESC = 160; - - - private void setRegionInfo(AST ast,AST startAST,AST endAST){ - // do something with the model - } - - protected void initialize() - { - tokenNames = tokenNames_; - initializeFactory(); - } - - - protected AS3Parser(TokenBuffer tokenBuf, int k) : base(tokenBuf, k) - { - initialize(); - } - - public AS3Parser(TokenBuffer tokenBuf) : this(tokenBuf,2) - { - } - - protected AS3Parser(TokenStream lexer, int k) : base(lexer,k) - { - initialize(); - } - - public AS3Parser(TokenStream lexer) : this(lexer,2) - { - } - - public AS3Parser(ParserSharedInputState state) : base(state,2) - { - initialize(); - } - + public class AS3Parser : antlr.LLkParser + { + public const int EOF = 1; + public const int NULL_TREE_LOOKAHEAD = 3; + public const int COMPILATION_UNIT = 4; + public const int IMPORT = 5; + public const int CLASS_DEF = 6; + public const int INTERFACE_DEF = 7; + public const int EXTENDS_CLAUSE = 8; + public const int IMPLEMENTS_CLAUSE = 9; + public const int TYPE_BLOCK = 10; + public const int MODIFIERS = 11; + public const int VARIABLE_DEF = 12; + public const int METHOD_DEF = 13; + public const int NAMESPACE_DEF = 14; + public const int PARAMS = 15; + public const int PARAM = 16; + public const int TYPE_SPEC = 17; + public const int BLOCK = 18; + public const int EXPR = 19; + public const int ELIST = 20; + public const int EXPR_STMNT = 21; + public const int NEW_EXPR = 22; + public const int ENCPS_EXPR = 23; + public const int VAR_INIT = 24; + public const int METHOD_CALL = 25; + public const int ARRAY_ACC = 26; + public const int UNARY_PLUS = 27; + public const int UNARY_MINUS = 28; + public const int POST_INC = 29; + public const int POST_DEC = 30; + public const int ARRAY_LITERAL = 31; + public const int ELEMENT = 32; + public const int OBJECT_LITERAL = 33; + public const int OBJECT_FIELD = 34; + public const int FUNC_DEF = 35; + public const int FOR_INIT = 36; + public const int FOR_CONDITION = 37; + public const int FOR_ITERATOR = 38; + public const int LITERAL_package = 39; + public const int LCURLY = 40; + public const int SEMI = 41; + public const int RCURLY = 42; + public const int LITERAL_import = 43; + public const int LBRACK = 44; + public const int COMMA = 45; + public const int RBRACK = 46; + public const int LPAREN = 47; + public const int RPAREN = 48; + public const int LITERAL_class = 49; + public const int LITERAL_interface = 50; + public const int LITERAL_extends = 51; + public const int LITERAL_implements = 52; + public const int LITERAL_function = 53; + public const int LITERAL_get = 54; + public const int LITERAL_set = 55; + // "/n" = 56 + // "/r" = 57 + public const int IDENT = 58; + public const int LITERAL_namespace = 59; + public const int LITERAL_var = 60; + public const int LITERAL_const = 61; + public const int ASSIGN = 62; + public const int REST = 63; + public const int LITERAL_while = 64; + public const int LITERAL_do = 65; + public const int LITERAL_with = 66; + public const int LITERAL_if = 67; + public const int LITERAL_else = 68; + public const int LITERAL_throw = 69; + public const int LITERAL_return = 70; + public const int LITERAL_continue = 71; + public const int LITERAL_break = 72; + public const int LITERAL_switch = 73; + public const int LITERAL_case = 74; + public const int COLON = 75; + public const int LITERAL_default = 76; + public const int LITERAL_for = 77; + public const int LITERAL_each = 78; + public const int LITERAL_in = 79; + public const int DOT = 80; + public const int STAR = 81; + public const int LITERAL_public = 82; + public const int LITERAL_private = 83; + public const int LITERAL_protected = 84; + public const int LITERAL_internal = 85; + public const int LITERAL_static = 86; + public const int LITERAL_final = 87; + public const int LITERAL_enumerable = 88; + public const int LITERAL_explicit = 89; + public const int LITERAL_override = 90; + public const int LITERAL_dynamic = 91; + public const int NUMBER = 92; + public const int STAR_ASSIGN = 93; + public const int DIV_ASSIGN = 94; + public const int MOD_ASSIGN = 95; + public const int PLUS_ASSIGN = 96; + public const int MINUS_ASSIGN = 97; + public const int SL_ASSIGN = 98; + public const int SR_ASSIGN = 99; + public const int BSR_ASSIGN = 100; + public const int BAND_ASSIGN = 101; + public const int BXOR_ASSIGN = 102; + public const int BOR_ASSIGN = 103; + public const int LAND_ASSIGN = 104; + public const int LOR_ASSIGN = 105; + public const int QUESTION = 106; + public const int LOR = 107; + public const int LAND = 108; + public const int BOR = 109; + public const int BXOR = 110; + public const int BAND = 111; + public const int STRICT_EQUAL = 112; + public const int STRICT_NOT_EQUAL = 113; + public const int NOT_EQUAL = 114; + public const int EQUAL = 115; + public const int LWT = 116; + public const int GT = 117; + public const int LE = 118; + public const int GE = 119; + public const int LITERAL_is = 120; + public const int LITERAL_as = 121; + public const int SL = 122; + public const int SR = 123; + public const int BSR = 124; + public const int PLUS = 125; + public const int MINUS = 126; + public const int DIV = 127; + public const int MOD = 128; + public const int INC = 129; + public const int DEC = 130; + public const int LITERAL_delete = 131; + public const int LITERAL_typeof = 132; + public const int LNOT = 133; + public const int BNOT = 134; + public const int E4X_DESC = 135; + public const int E4X_ATTRI = 136; + public const int LITERAL_null = 137; + public const int LITERAL_true = 138; + public const int LITERAL_false = 139; + public const int LITERAL_undefined = 140; + public const int STRING_LITERAL = 141; + public const int REGEX_LITERAL = 142; + public const int XML_LITERAL = 143; + public const int LITERAL_new = 144; + public const int DBL_COLON = 145; + public const int XML_ATTRIBUTE = 146; + public const int XML_BINDING = 147; + public const int XML_AS3_EXPRESSION = 148; + public const int XML_TEXTNODE = 149; + public const int XML_COMMENT = 150; + public const int XML_CDATA = 151; + public const int REGEX_BODY = 152; + public const int WS = 153; + public const int NL = 154; + public const int BOM = 155; + public const int SL_COMMENT = 156; + public const int ML_COMMENT = 157; + public const int EXPONENT = 158; + public const int HEX_DIGIT = 159; + public const int ESC = 160; + + + private void setRegionInfo(AST ast,AST startAST,AST endAST){ + // do something with the model + } + + protected void initialize() + { + tokenNames = tokenNames_; + initializeFactory(); + } + + + protected AS3Parser(TokenBuffer tokenBuf, int k) : base(tokenBuf, k) + { + initialize(); + } + + public AS3Parser(TokenBuffer tokenBuf) : this(tokenBuf,2) + { + } + + protected AS3Parser(TokenStream lexer, int k) : base(lexer,k) + { + initialize(); + } + + public AS3Parser(TokenStream lexer) : this(lexer,2) + { + } + + public AS3Parser(ParserSharedInputState state) : base(state,2) + { + initialize(); + } + /** * this is the start rule for this parser */ - public void compilationUnit() //throws RecognitionException, TokenStreamException + public void compilationUnit() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST compilationUnit_AST = null; - AST mods_AST = null; - - AST tmp1_AST = null; - tmp1_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp1_AST); - match(LITERAL_package); - { - switch ( LA(1) ) - { - case IDENT: - { - identifier(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LCURLY: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - match(LCURLY); - { // ( ... )* - for (;;) - { - switch ( LA(1) ) - { - case LITERAL_import: - { - importDefinition(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LBRACK: - { - metadataDefinition(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LITERAL_class: - case LITERAL_interface: - case LITERAL_function: - case LITERAL_namespace: - case LITERAL_var: - case LITERAL_const: - case LITERAL_public: - case LITERAL_private: - case LITERAL_protected: - case LITERAL_internal: - case LITERAL_static: - case LITERAL_final: - case LITERAL_enumerable: - case LITERAL_explicit: - case LITERAL_override: - case LITERAL_dynamic: - { - modifiers(); - if (0 == inputState.guessing) - { - mods_AST = (AST)returnAST; - } - { - switch ( LA(1) ) - { - case LITERAL_class: - { - classDefinition(mods_AST); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LITERAL_interface: - { - interfaceDefinition(mods_AST); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LITERAL_var: - case LITERAL_const: - { - variableDefinition(mods_AST); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LITERAL_function: - { - methodDefinition(mods_AST); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LITERAL_namespace: - { - namespaceDefinition(mods_AST); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - break; - } - case SEMI: - { - match(SEMI); - break; - } - default: - { - goto _loop5_breakloop; - } - } - } -_loop5_breakloop: ; - } // ( ... )* - match(RCURLY); - match(Token.EOF_TYPE); - if (0==inputState.guessing) - { - compilationUnit_AST = (AST)currentAST.root; - compilationUnit_AST = (AST) astFactory.make(astFactory.create(COMPILATION_UNIT,"COMPILATION_UNIT"), compilationUnit_AST); - currentAST.root = compilationUnit_AST; - if ( (null != compilationUnit_AST) && (null != compilationUnit_AST.getFirstChild()) ) - currentAST.child = compilationUnit_AST.getFirstChild(); - else - currentAST.child = compilationUnit_AST; - currentAST.advanceChildToEnd(); - } - compilationUnit_AST = currentAST.root; - returnAST = compilationUnit_AST; - } - - public void identifier() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST compilationUnit_AST = null; + AST mods_AST = null; + + AST tmp1_AST = null; + tmp1_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp1_AST); + match(LITERAL_package); + { + switch ( LA(1) ) + { + case IDENT: + { + identifier(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LCURLY: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + match(LCURLY); + { // ( ... )* + for (;;) + { + switch ( LA(1) ) + { + case LITERAL_import: + { + importDefinition(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LBRACK: + { + metadataDefinition(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LITERAL_class: + case LITERAL_interface: + case LITERAL_function: + case LITERAL_namespace: + case LITERAL_var: + case LITERAL_const: + case LITERAL_public: + case LITERAL_private: + case LITERAL_protected: + case LITERAL_internal: + case LITERAL_static: + case LITERAL_final: + case LITERAL_enumerable: + case LITERAL_explicit: + case LITERAL_override: + case LITERAL_dynamic: + { + modifiers(); + if (0 == inputState.guessing) + { + mods_AST = (AST)returnAST; + } + { + switch ( LA(1) ) + { + case LITERAL_class: + { + classDefinition(mods_AST); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LITERAL_interface: + { + interfaceDefinition(mods_AST); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LITERAL_var: + case LITERAL_const: + { + variableDefinition(mods_AST); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LITERAL_function: + { + methodDefinition(mods_AST); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LITERAL_namespace: + { + namespaceDefinition(mods_AST); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + break; + } + case SEMI: + { + match(SEMI); + break; + } + default: + { + goto _loop5_breakloop; + } + } + } +_loop5_breakloop: ; + } // ( ... )* + match(RCURLY); + match(Token.EOF_TYPE); + if (0==inputState.guessing) + { + compilationUnit_AST = (AST)currentAST.root; + compilationUnit_AST = (AST) astFactory.make(astFactory.create(COMPILATION_UNIT,"COMPILATION_UNIT"), compilationUnit_AST); + currentAST.root = compilationUnit_AST; + if ( (null != compilationUnit_AST) && (null != compilationUnit_AST.getFirstChild()) ) + currentAST.child = compilationUnit_AST.getFirstChild(); + else + currentAST.child = compilationUnit_AST; + currentAST.advanceChildToEnd(); + } + compilationUnit_AST = currentAST.root; + returnAST = compilationUnit_AST; + } + + public void identifier() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST identifier_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(IDENT); - { // ( ... )* - for (;;) - { - if ((LA(1)==DOT)) - { - match(DOT); - e = LT(1); - e_AST = astFactory.create(e); - astFactory.makeASTRoot(ref currentAST, e_AST); - match(IDENT); - if (0==inputState.guessing) - { - identifier_AST = (AST)currentAST.root; - setRegionInfo(identifier_AST,s_AST,e_AST); - } - } - else - { - goto _loop112_breakloop; - } - - } -_loop112_breakloop: ; - } // ( ... )* - if (0==inputState.guessing) - { - identifier_AST = (AST)currentAST.root; - setRegionInfo(identifier_AST,s_AST,e_AST); - } - identifier_AST = currentAST.root; - returnAST = identifier_AST; - } - - public void importDefinition() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST identifier_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(IDENT); + { // ( ... )* + for (;;) + { + if ((LA(1)==DOT)) + { + match(DOT); + e = LT(1); + e_AST = astFactory.create(e); + astFactory.makeASTRoot(ref currentAST, e_AST); + match(IDENT); + if (0==inputState.guessing) + { + identifier_AST = (AST)currentAST.root; + setRegionInfo(identifier_AST,s_AST,e_AST); + } + } + else + { + goto _loop112_breakloop; + } + + } +_loop112_breakloop: ; + } // ( ... )* + if (0==inputState.guessing) + { + identifier_AST = (AST)currentAST.root; + setRegionInfo(identifier_AST,s_AST,e_AST); + } + identifier_AST = currentAST.root; + returnAST = identifier_AST; + } + + public void importDefinition() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST importDefinition_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LITERAL_import); - identifierStar(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - importDefinition_AST = (AST)currentAST.root; - importDefinition_AST = (AST) astFactory.make(astFactory.create(IMPORT,"IMPORT"), importDefinition_AST); - setRegionInfo(importDefinition_AST,s_AST,e_AST); - currentAST.root = importDefinition_AST; - if ( (null != importDefinition_AST) && (null != importDefinition_AST.getFirstChild()) ) - currentAST.child = importDefinition_AST.getFirstChild(); - else - currentAST.child = importDefinition_AST; - currentAST.advanceChildToEnd(); - } - importDefinition_AST = currentAST.root; - returnAST = importDefinition_AST; - } - - public void metadataDefinition() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST importDefinition_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LITERAL_import); + identifierStar(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + importDefinition_AST = (AST)currentAST.root; + importDefinition_AST = (AST) astFactory.make(astFactory.create(IMPORT,"IMPORT"), importDefinition_AST); + setRegionInfo(importDefinition_AST,s_AST,e_AST); + currentAST.root = importDefinition_AST; + if ( (null != importDefinition_AST) && (null != importDefinition_AST.getFirstChild()) ) + currentAST.child = importDefinition_AST.getFirstChild(); + else + currentAST.child = importDefinition_AST; + currentAST.advanceChildToEnd(); + } + importDefinition_AST = currentAST.root; + returnAST = importDefinition_AST; + } + + public void metadataDefinition() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST metadataDefinition_AST = null; - - AST tmp7_AST = null; - tmp7_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp7_AST); - match(LBRACK); - { - metadataItem(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - match(COMMA); - metadataItem(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop10_breakloop; - } - - } -_loop10_breakloop: ; - } // ( ... )* - } - AST tmp9_AST = null; - tmp9_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp9_AST); - match(RBRACK); - metadataDefinition_AST = currentAST.root; - returnAST = metadataDefinition_AST; - } - - public void modifiers() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST metadataDefinition_AST = null; + + AST tmp7_AST = null; + tmp7_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp7_AST); + match(LBRACK); + { + metadataItem(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + match(COMMA); + metadataItem(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop10_breakloop; + } + + } +_loop10_breakloop: ; + } // ( ... )* + } + AST tmp9_AST = null; + tmp9_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp9_AST); + match(RBRACK); + metadataDefinition_AST = currentAST.root; + returnAST = metadataDefinition_AST; + } + + public void modifiers() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST modifiers_AST = null; - AST s_AST = null; - AST e_AST = null; - - { - switch ( LA(1) ) - { - case LITERAL_public: - case LITERAL_private: - case LITERAL_protected: - case LITERAL_internal: - case LITERAL_static: - case LITERAL_final: - case LITERAL_enumerable: - case LITERAL_explicit: - case LITERAL_override: - case LITERAL_dynamic: - { - modifier(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if (((LA(1) >= LITERAL_public && LA(1) <= LITERAL_dynamic))) - { - modifier(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop120_breakloop; - } - - } -_loop120_breakloop: ; - } // ( ... )* - break; - } - case LITERAL_class: - case LITERAL_interface: - case LITERAL_function: - case LITERAL_namespace: - case LITERAL_var: - case LITERAL_const: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - modifiers_AST = (AST)currentAST.root; - modifiers_AST = (AST) astFactory.make(astFactory.create(MODIFIERS,"MODIFIERS"), modifiers_AST); - setRegionInfo(modifiers_AST,s_AST,e_AST); - currentAST.root = modifiers_AST; - if ( (null != modifiers_AST) && (null != modifiers_AST.getFirstChild()) ) - currentAST.child = modifiers_AST.getFirstChild(); - else - currentAST.child = modifiers_AST; - currentAST.advanceChildToEnd(); - } - modifiers_AST = currentAST.root; - returnAST = modifiers_AST; - } - - public void classDefinition( - AST mods - ) //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST modifiers_AST = null; + AST s_AST = null; + AST e_AST = null; + + { + switch ( LA(1) ) + { + case LITERAL_public: + case LITERAL_private: + case LITERAL_protected: + case LITERAL_internal: + case LITERAL_static: + case LITERAL_final: + case LITERAL_enumerable: + case LITERAL_explicit: + case LITERAL_override: + case LITERAL_dynamic: + { + modifier(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if (((LA(1) >= LITERAL_public && LA(1) <= LITERAL_dynamic))) + { + modifier(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop120_breakloop; + } + + } +_loop120_breakloop: ; + } // ( ... )* + break; + } + case LITERAL_class: + case LITERAL_interface: + case LITERAL_function: + case LITERAL_namespace: + case LITERAL_var: + case LITERAL_const: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + modifiers_AST = (AST)currentAST.root; + modifiers_AST = (AST) astFactory.make(astFactory.create(MODIFIERS,"MODIFIERS"), modifiers_AST); + setRegionInfo(modifiers_AST,s_AST,e_AST); + currentAST.root = modifiers_AST; + if ( (null != modifiers_AST) && (null != modifiers_AST.getFirstChild()) ) + currentAST.child = modifiers_AST.getFirstChild(); + else + currentAST.child = modifiers_AST; + currentAST.advanceChildToEnd(); + } + modifiers_AST = currentAST.root; + returnAST = modifiers_AST; + } + + public void classDefinition( + AST mods + ) //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST classDefinition_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LITERAL_class); - identifier(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - extendsClause(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - implementsClause(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - typeBlock(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - classDefinition_AST = (AST)currentAST.root; - classDefinition_AST = (AST) astFactory.make(astFactory.create(CLASS_DEF,"CLASS_DEF"), classDefinition_AST, mods); - setRegionInfo(classDefinition_AST,s_AST,e_AST); - currentAST.root = classDefinition_AST; - if ( (null != classDefinition_AST) && (null != classDefinition_AST.getFirstChild()) ) - currentAST.child = classDefinition_AST.getFirstChild(); - else - currentAST.child = classDefinition_AST; - currentAST.advanceChildToEnd(); - } - classDefinition_AST = currentAST.root; - returnAST = classDefinition_AST; - } - - public void interfaceDefinition( - AST mods - ) //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST classDefinition_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LITERAL_class); + identifier(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + extendsClause(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + implementsClause(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + typeBlock(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + classDefinition_AST = (AST)currentAST.root; + classDefinition_AST = (AST) astFactory.make(astFactory.create(CLASS_DEF,"CLASS_DEF"), classDefinition_AST, mods); + setRegionInfo(classDefinition_AST,s_AST,e_AST); + currentAST.root = classDefinition_AST; + if ( (null != classDefinition_AST) && (null != classDefinition_AST.getFirstChild()) ) + currentAST.child = classDefinition_AST.getFirstChild(); + else + currentAST.child = classDefinition_AST; + currentAST.advanceChildToEnd(); + } + classDefinition_AST = currentAST.root; + returnAST = classDefinition_AST; + } + + public void interfaceDefinition( + AST mods + ) //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST interfaceDefinition_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LITERAL_interface); - identifier(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - extendsClause(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - typeBlock(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - interfaceDefinition_AST = (AST)currentAST.root; - interfaceDefinition_AST = (AST) astFactory.make(astFactory.create(INTERFACE_DEF,"INTERFACE_DEF"), interfaceDefinition_AST, mods); - setRegionInfo(interfaceDefinition_AST,s_AST,e_AST); - currentAST.root = interfaceDefinition_AST; - if ( (null != interfaceDefinition_AST) && (null != interfaceDefinition_AST.getFirstChild()) ) - currentAST.child = interfaceDefinition_AST.getFirstChild(); - else - currentAST.child = interfaceDefinition_AST; - currentAST.advanceChildToEnd(); - } - interfaceDefinition_AST = currentAST.root; - returnAST = interfaceDefinition_AST; - } - - public void variableDefinition( - AST mods - ) //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST interfaceDefinition_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LITERAL_interface); + identifier(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + extendsClause(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + typeBlock(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + interfaceDefinition_AST = (AST)currentAST.root; + interfaceDefinition_AST = (AST) astFactory.make(astFactory.create(INTERFACE_DEF,"INTERFACE_DEF"), interfaceDefinition_AST, mods); + setRegionInfo(interfaceDefinition_AST,s_AST,e_AST); + currentAST.root = interfaceDefinition_AST; + if ( (null != interfaceDefinition_AST) && (null != interfaceDefinition_AST.getFirstChild()) ) + currentAST.child = interfaceDefinition_AST.getFirstChild(); + else + currentAST.child = interfaceDefinition_AST; + currentAST.advanceChildToEnd(); + } + interfaceDefinition_AST = currentAST.root; + returnAST = interfaceDefinition_AST; + } + + public void variableDefinition( + AST mods + ) //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST variableDefinition_AST = null; - - { - switch ( LA(1) ) - { - case LITERAL_var: - { - match(LITERAL_var); - break; - } - case LITERAL_const: - { - match(LITERAL_const); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - variableDeclarator(getASTFactory().dupTree(mods)); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - match(COMMA); - variableDeclarator(getASTFactory().dupTree(mods)); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop38_breakloop; - } - - } -_loop38_breakloop: ; - } // ( ... )* - variableDefinition_AST = currentAST.root; - returnAST = variableDefinition_AST; - } - - public void methodDefinition( - AST mods - ) //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST variableDefinition_AST = null; + + { + switch ( LA(1) ) + { + case LITERAL_var: + { + match(LITERAL_var); + break; + } + case LITERAL_const: + { + match(LITERAL_const); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + variableDeclarator(getASTFactory().dupTree(mods)); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + match(COMMA); + variableDeclarator(getASTFactory().dupTree(mods)); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop38_breakloop; + } + + } +_loop38_breakloop: ; + } // ( ... )* + variableDefinition_AST = currentAST.root; + returnAST = variableDefinition_AST; + } + + public void methodDefinition( + AST mods + ) //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST methodDefinition_AST = null; - IToken s = null; - AST s_AST = null; - AST e1_AST = null; - AST e2_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LITERAL_function); - { - switch ( LA(1) ) - { - case LITERAL_get: - case LITERAL_set: - { - { - switch ( LA(1) ) - { - case LITERAL_get: - { - AST tmp13_AST = null; - tmp13_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp13_AST); - match(LITERAL_get); - break; - } - case LITERAL_set: - { - AST tmp14_AST = null; - tmp14_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp14_AST); - match(LITERAL_set); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - { - AST tmp15_AST = null; - tmp15_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp15_AST); - match(tokenSet_0_); - } - break; - } - case IDENT: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - AST tmp16_AST = null; - tmp16_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp16_AST); - match(IDENT); - parameterDeclarationList(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - typeExpression(); - if (0 == inputState.guessing) - { - e1_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { - switch ( LA(1) ) - { - case LCURLY: - { - block(); - if (0 == inputState.guessing) - { - e2_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case SEMI: - case RCURLY: - case LITERAL_import: - case LBRACK: - case LITERAL_class: - case LITERAL_interface: - case LITERAL_function: - case LITERAL_namespace: - case LITERAL_var: - case LITERAL_const: - case LITERAL_public: - case LITERAL_private: - case LITERAL_protected: - case LITERAL_internal: - case LITERAL_static: - case LITERAL_final: - case LITERAL_enumerable: - case LITERAL_explicit: - case LITERAL_override: - case LITERAL_dynamic: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - methodDefinition_AST = (AST)currentAST.root; - methodDefinition_AST = (AST) astFactory.make(astFactory.create(METHOD_DEF,"METHOD_DEF"), methodDefinition_AST, mods); - setRegionInfo(methodDefinition_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - currentAST.root = methodDefinition_AST; - if ( (null != methodDefinition_AST) && (null != methodDefinition_AST.getFirstChild()) ) - currentAST.child = methodDefinition_AST.getFirstChild(); - else - currentAST.child = methodDefinition_AST; - currentAST.advanceChildToEnd(); - } - methodDefinition_AST = currentAST.root; - returnAST = methodDefinition_AST; - } - - public void namespaceDefinition( - AST mods - ) //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST methodDefinition_AST = null; + IToken s = null; + AST s_AST = null; + AST e1_AST = null; + AST e2_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LITERAL_function); + { + switch ( LA(1) ) + { + case LITERAL_get: + case LITERAL_set: + { + { + switch ( LA(1) ) + { + case LITERAL_get: + { + AST tmp13_AST = null; + tmp13_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp13_AST); + match(LITERAL_get); + break; + } + case LITERAL_set: + { + AST tmp14_AST = null; + tmp14_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp14_AST); + match(LITERAL_set); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + { + AST tmp15_AST = null; + tmp15_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp15_AST); + match(tokenSet_0_); + } + break; + } + case IDENT: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + AST tmp16_AST = null; + tmp16_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp16_AST); + match(IDENT); + parameterDeclarationList(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + typeExpression(); + if (0 == inputState.guessing) + { + e1_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { + switch ( LA(1) ) + { + case LCURLY: + { + block(); + if (0 == inputState.guessing) + { + e2_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case SEMI: + case RCURLY: + case LITERAL_import: + case LBRACK: + case LITERAL_class: + case LITERAL_interface: + case LITERAL_function: + case LITERAL_namespace: + case LITERAL_var: + case LITERAL_const: + case LITERAL_public: + case LITERAL_private: + case LITERAL_protected: + case LITERAL_internal: + case LITERAL_static: + case LITERAL_final: + case LITERAL_enumerable: + case LITERAL_explicit: + case LITERAL_override: + case LITERAL_dynamic: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + methodDefinition_AST = (AST)currentAST.root; + methodDefinition_AST = (AST) astFactory.make(astFactory.create(METHOD_DEF,"METHOD_DEF"), methodDefinition_AST, mods); + setRegionInfo(methodDefinition_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + currentAST.root = methodDefinition_AST; + if ( (null != methodDefinition_AST) && (null != methodDefinition_AST.getFirstChild()) ) + currentAST.child = methodDefinition_AST.getFirstChild(); + else + currentAST.child = methodDefinition_AST; + currentAST.advanceChildToEnd(); + } + methodDefinition_AST = currentAST.root; + returnAST = methodDefinition_AST; + } + + public void namespaceDefinition( + AST mods + ) //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST namespaceDefinition_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LITERAL_namespace); - e = LT(1); - e_AST = astFactory.create(e); - astFactory.addASTChild(ref currentAST, e_AST); - match(IDENT); - if (0==inputState.guessing) - { - namespaceDefinition_AST = (AST)currentAST.root; - namespaceDefinition_AST = (AST) astFactory.make(astFactory.create(NAMESPACE_DEF,"NAMESPACE_DEF"), namespaceDefinition_AST, mods); - setRegionInfo(namespaceDefinition_AST,s_AST,e_AST); - currentAST.root = namespaceDefinition_AST; - if ( (null != namespaceDefinition_AST) && (null != namespaceDefinition_AST.getFirstChild()) ) - currentAST.child = namespaceDefinition_AST.getFirstChild(); - else - currentAST.child = namespaceDefinition_AST; - currentAST.advanceChildToEnd(); - } - namespaceDefinition_AST = currentAST.root; - returnAST = namespaceDefinition_AST; - } - - public void identifierStar() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST namespaceDefinition_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LITERAL_namespace); + e = LT(1); + e_AST = astFactory.create(e); + astFactory.addASTChild(ref currentAST, e_AST); + match(IDENT); + if (0==inputState.guessing) + { + namespaceDefinition_AST = (AST)currentAST.root; + namespaceDefinition_AST = (AST) astFactory.make(astFactory.create(NAMESPACE_DEF,"NAMESPACE_DEF"), namespaceDefinition_AST, mods); + setRegionInfo(namespaceDefinition_AST,s_AST,e_AST); + currentAST.root = namespaceDefinition_AST; + if ( (null != namespaceDefinition_AST) && (null != namespaceDefinition_AST.getFirstChild()) ) + currentAST.child = namespaceDefinition_AST.getFirstChild(); + else + currentAST.child = namespaceDefinition_AST; + currentAST.advanceChildToEnd(); + } + namespaceDefinition_AST = currentAST.root; + returnAST = namespaceDefinition_AST; + } + + public void identifierStar() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST identifierStar_AST = null; - IToken s = null; - AST s_AST = null; - IToken e1 = null; - AST e1_AST = null; - IToken e2 = null; - AST e2_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(IDENT); - { // ( ... )* - for (;;) - { - if ((LA(1)==DOT) && (LA(2)==IDENT)) - { - match(DOT); - e1 = LT(1); - e1_AST = astFactory.create(e1); - astFactory.makeASTRoot(ref currentAST, e1_AST); - match(IDENT); - if (0==inputState.guessing) - { - identifierStar_AST = (AST)currentAST.root; - setRegionInfo(identifierStar_AST,s_AST,e1_AST); - } - } - else - { - goto _loop115_breakloop; - } - - } -_loop115_breakloop: ; - } // ( ... )* - { - switch ( LA(1) ) - { - case DOT: - { - match(DOT); - e2 = LT(1); - e2_AST = astFactory.create(e2); - astFactory.makeASTRoot(ref currentAST, e2_AST); - match(STAR); - if (0==inputState.guessing) - { - identifierStar_AST = (AST)currentAST.root; - setRegionInfo(identifierStar_AST,s_AST,e2_AST); - } - break; - } - case SEMI: - case RCURLY: - case LITERAL_import: - case LBRACK: - case LITERAL_class: - case LITERAL_interface: - case LITERAL_function: - case LITERAL_namespace: - case LITERAL_var: - case LITERAL_const: - case LITERAL_public: - case LITERAL_private: - case LITERAL_protected: - case LITERAL_internal: - case LITERAL_static: - case LITERAL_final: - case LITERAL_enumerable: - case LITERAL_explicit: - case LITERAL_override: - case LITERAL_dynamic: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - identifierStar_AST = (AST)currentAST.root; - setRegionInfo(identifierStar_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - } - identifierStar_AST = currentAST.root; - returnAST = identifierStar_AST; - } - - public void metadataItem() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST identifierStar_AST = null; + IToken s = null; + AST s_AST = null; + IToken e1 = null; + AST e1_AST = null; + IToken e2 = null; + AST e2_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(IDENT); + { // ( ... )* + for (;;) + { + if ((LA(1)==DOT) && (LA(2)==IDENT)) + { + match(DOT); + e1 = LT(1); + e1_AST = astFactory.create(e1); + astFactory.makeASTRoot(ref currentAST, e1_AST); + match(IDENT); + if (0==inputState.guessing) + { + identifierStar_AST = (AST)currentAST.root; + setRegionInfo(identifierStar_AST,s_AST,e1_AST); + } + } + else + { + goto _loop115_breakloop; + } + + } +_loop115_breakloop: ; + } // ( ... )* + { + switch ( LA(1) ) + { + case DOT: + { + match(DOT); + e2 = LT(1); + e2_AST = astFactory.create(e2); + astFactory.makeASTRoot(ref currentAST, e2_AST); + match(STAR); + if (0==inputState.guessing) + { + identifierStar_AST = (AST)currentAST.root; + setRegionInfo(identifierStar_AST,s_AST,e2_AST); + } + break; + } + case SEMI: + case RCURLY: + case LITERAL_import: + case LBRACK: + case LITERAL_class: + case LITERAL_interface: + case LITERAL_function: + case LITERAL_namespace: + case LITERAL_var: + case LITERAL_const: + case LITERAL_public: + case LITERAL_private: + case LITERAL_protected: + case LITERAL_internal: + case LITERAL_static: + case LITERAL_final: + case LITERAL_enumerable: + case LITERAL_explicit: + case LITERAL_override: + case LITERAL_dynamic: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + identifierStar_AST = (AST)currentAST.root; + setRegionInfo(identifierStar_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + } + identifierStar_AST = currentAST.root; + returnAST = identifierStar_AST; + } + + public void metadataItem() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST metadataItem_AST = null; - - identifier(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { - switch ( LA(1) ) - { - case LPAREN: - { - AST tmp19_AST = null; - tmp19_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp19_AST); - match(LPAREN); - { - switch ( LA(1) ) - { - case LCURLY: - case LBRACK: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - expression(); - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - match(COMMA); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop15_breakloop; - } - - } -_loop15_breakloop: ; - } // ( ... )* - break; - } - case RPAREN: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - AST tmp21_AST = null; - tmp21_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp21_AST); - match(RPAREN); - break; - } - case COMMA: - case RBRACK: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - metadataItem_AST = currentAST.root; - returnAST = metadataItem_AST; - } - - public void expression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST metadataItem_AST = null; + + identifier(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { + switch ( LA(1) ) + { + case LPAREN: + { + AST tmp19_AST = null; + tmp19_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp19_AST); + match(LPAREN); + { + switch ( LA(1) ) + { + case LCURLY: + case LBRACK: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + expression(); + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + match(COMMA); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop15_breakloop; + } + + } +_loop15_breakloop: ; + } // ( ... )* + break; + } + case RPAREN: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + AST tmp21_AST = null; + tmp21_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp21_AST); + match(RPAREN); + break; + } + case COMMA: + case RBRACK: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + metadataItem_AST = currentAST.root; + returnAST = metadataItem_AST; + } + + public void expression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST expression_AST = null; - AST s_AST = null; - - assignmentExpression(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - expression_AST = (AST)currentAST.root; - expression_AST = (AST) astFactory.make(astFactory.create(EXPR,"EXPR"), expression_AST); - setRegionInfo(expression_AST,s_AST,null); - currentAST.root = expression_AST; - if ( (null != expression_AST) && (null != expression_AST.getFirstChild()) ) - currentAST.child = expression_AST.getFirstChild(); - else - currentAST.child = expression_AST; - currentAST.advanceChildToEnd(); - } - expression_AST = currentAST.root; - returnAST = expression_AST; - } - - public void extendsClause() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST expression_AST = null; + AST s_AST = null; + + assignmentExpression(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + expression_AST = (AST)currentAST.root; + expression_AST = (AST) astFactory.make(astFactory.create(EXPR,"EXPR"), expression_AST); + setRegionInfo(expression_AST,s_AST,null); + currentAST.root = expression_AST; + if ( (null != expression_AST) && (null != expression_AST.getFirstChild()) ) + currentAST.child = expression_AST.getFirstChild(); + else + currentAST.child = expression_AST; + currentAST.advanceChildToEnd(); + } + expression_AST = currentAST.root; + returnAST = expression_AST; + } + + public void extendsClause() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST extendsClause_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - { - switch ( LA(1) ) - { - case LITERAL_extends: - { - s = LT(1); - s_AST = astFactory.create(s); - match(LITERAL_extends); - identifier(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LCURLY: - case LITERAL_implements: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - extendsClause_AST = (AST)currentAST.root; - extendsClause_AST = (AST) astFactory.make(astFactory.create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE"), extendsClause_AST); - setRegionInfo(extendsClause_AST,s_AST,e_AST); - currentAST.root = extendsClause_AST; - if ( (null != extendsClause_AST) && (null != extendsClause_AST.getFirstChild()) ) - currentAST.child = extendsClause_AST.getFirstChild(); - else - currentAST.child = extendsClause_AST; - currentAST.advanceChildToEnd(); - } - extendsClause_AST = currentAST.root; - returnAST = extendsClause_AST; - } - - public void implementsClause() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST extendsClause_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + { + switch ( LA(1) ) + { + case LITERAL_extends: + { + s = LT(1); + s_AST = astFactory.create(s); + match(LITERAL_extends); + identifier(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LCURLY: + case LITERAL_implements: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + extendsClause_AST = (AST)currentAST.root; + extendsClause_AST = (AST) astFactory.make(astFactory.create(EXTENDS_CLAUSE,"EXTENDS_CLAUSE"), extendsClause_AST); + setRegionInfo(extendsClause_AST,s_AST,e_AST); + currentAST.root = extendsClause_AST; + if ( (null != extendsClause_AST) && (null != extendsClause_AST.getFirstChild()) ) + currentAST.child = extendsClause_AST.getFirstChild(); + else + currentAST.child = extendsClause_AST; + currentAST.advanceChildToEnd(); + } + extendsClause_AST = currentAST.root; + returnAST = extendsClause_AST; + } + + public void implementsClause() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST implementsClause_AST = null; - IToken s = null; - AST s_AST = null; - AST e1_AST = null; - AST e2_AST = null; - - { // ( ... )* - for (;;) - { - if ((LA(1)==LITERAL_implements)) - { - s = LT(1); - s_AST = astFactory.create(s); - match(LITERAL_implements); - identifier(); - if (0 == inputState.guessing) - { - e1_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - match(COMMA); - identifier(); - if (0 == inputState.guessing) - { - e2_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop23_breakloop; - } - - } -_loop23_breakloop: ; - } // ( ... )* - } - else - { - goto _loop24_breakloop; - } - - } -_loop24_breakloop: ; - } // ( ... )* - if (0==inputState.guessing) - { - implementsClause_AST = (AST)currentAST.root; - implementsClause_AST = (AST) astFactory.make(astFactory.create(IMPLEMENTS_CLAUSE,"IMPLEMENTS_CLAUSE"), implementsClause_AST); - setRegionInfo(implementsClause_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - currentAST.root = implementsClause_AST; - if ( (null != implementsClause_AST) && (null != implementsClause_AST.getFirstChild()) ) - currentAST.child = implementsClause_AST.getFirstChild(); - else - currentAST.child = implementsClause_AST; - currentAST.advanceChildToEnd(); - } - implementsClause_AST = currentAST.root; - returnAST = implementsClause_AST; - } - - public void typeBlock() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST implementsClause_AST = null; + IToken s = null; + AST s_AST = null; + AST e1_AST = null; + AST e2_AST = null; + + { // ( ... )* + for (;;) + { + if ((LA(1)==LITERAL_implements)) + { + s = LT(1); + s_AST = astFactory.create(s); + match(LITERAL_implements); + identifier(); + if (0 == inputState.guessing) + { + e1_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + match(COMMA); + identifier(); + if (0 == inputState.guessing) + { + e2_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop23_breakloop; + } + + } +_loop23_breakloop: ; + } // ( ... )* + } + else + { + goto _loop24_breakloop; + } + + } +_loop24_breakloop: ; + } // ( ... )* + if (0==inputState.guessing) + { + implementsClause_AST = (AST)currentAST.root; + implementsClause_AST = (AST) astFactory.make(astFactory.create(IMPLEMENTS_CLAUSE,"IMPLEMENTS_CLAUSE"), implementsClause_AST); + setRegionInfo(implementsClause_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + currentAST.root = implementsClause_AST; + if ( (null != implementsClause_AST) && (null != implementsClause_AST.getFirstChild()) ) + currentAST.child = implementsClause_AST.getFirstChild(); + else + currentAST.child = implementsClause_AST; + currentAST.advanceChildToEnd(); + } + implementsClause_AST = currentAST.root; + returnAST = implementsClause_AST; + } + + public void typeBlock() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST typeBlock_AST = null; - IToken s = null; - AST s_AST = null; - AST m_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LCURLY); - { // ( ... )* - for (;;) - { - switch ( LA(1) ) - { - case LBRACK: - { - metadataDefinition(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LITERAL_function: - case LITERAL_var: - case LITERAL_const: - case LITERAL_public: - case LITERAL_private: - case LITERAL_protected: - case LITERAL_internal: - case LITERAL_static: - case LITERAL_final: - case LITERAL_enumerable: - case LITERAL_explicit: - case LITERAL_override: - case LITERAL_dynamic: - { - modifiers(); - if (0 == inputState.guessing) - { - m_AST = (AST)returnAST; - } - { - switch ( LA(1) ) - { - case LITERAL_var: - case LITERAL_const: - { - variableDefinition(m_AST); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LITERAL_function: - { - methodDefinition(m_AST); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - break; - } - case SEMI: - { - match(SEMI); - break; - } - default: - { - goto _loop28_breakloop; - } - } - } -_loop28_breakloop: ; - } // ( ... )* - e = LT(1); - e_AST = astFactory.create(e); - match(RCURLY); - if (0==inputState.guessing) - { - typeBlock_AST = (AST)currentAST.root; - typeBlock_AST = (AST) astFactory.make(astFactory.create(TYPE_BLOCK,"TYPE_BLOCK"), typeBlock_AST); - setRegionInfo(typeBlock_AST,s_AST,e_AST); - currentAST.root = typeBlock_AST; - if ( (null != typeBlock_AST) && (null != typeBlock_AST.getFirstChild()) ) - currentAST.child = typeBlock_AST.getFirstChild(); - else - currentAST.child = typeBlock_AST; - currentAST.advanceChildToEnd(); - } - typeBlock_AST = currentAST.root; - returnAST = typeBlock_AST; - } - - public void parameterDeclarationList() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST typeBlock_AST = null; + IToken s = null; + AST s_AST = null; + AST m_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LCURLY); + { // ( ... )* + for (;;) + { + switch ( LA(1) ) + { + case LBRACK: + { + metadataDefinition(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LITERAL_function: + case LITERAL_var: + case LITERAL_const: + case LITERAL_public: + case LITERAL_private: + case LITERAL_protected: + case LITERAL_internal: + case LITERAL_static: + case LITERAL_final: + case LITERAL_enumerable: + case LITERAL_explicit: + case LITERAL_override: + case LITERAL_dynamic: + { + modifiers(); + if (0 == inputState.guessing) + { + m_AST = (AST)returnAST; + } + { + switch ( LA(1) ) + { + case LITERAL_var: + case LITERAL_const: + { + variableDefinition(m_AST); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LITERAL_function: + { + methodDefinition(m_AST); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + break; + } + case SEMI: + { + match(SEMI); + break; + } + default: + { + goto _loop28_breakloop; + } + } + } +_loop28_breakloop: ; + } // ( ... )* + e = LT(1); + e_AST = astFactory.create(e); + match(RCURLY); + if (0==inputState.guessing) + { + typeBlock_AST = (AST)currentAST.root; + typeBlock_AST = (AST) astFactory.make(astFactory.create(TYPE_BLOCK,"TYPE_BLOCK"), typeBlock_AST); + setRegionInfo(typeBlock_AST,s_AST,e_AST); + currentAST.root = typeBlock_AST; + if ( (null != typeBlock_AST) && (null != typeBlock_AST.getFirstChild()) ) + currentAST.child = typeBlock_AST.getFirstChild(); + else + currentAST.child = typeBlock_AST; + currentAST.advanceChildToEnd(); + } + typeBlock_AST = currentAST.root; + returnAST = typeBlock_AST; + } + + public void parameterDeclarationList() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST parameterDeclarationList_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LPAREN); - { - switch ( LA(1) ) - { - case IDENT: - case LITERAL_const: - case REST: - { - { - switch ( LA(1) ) - { - case IDENT: - case LITERAL_const: - { - parameterDeclaration(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case REST: - { - parameterRestDeclaration(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - match(COMMA); - { - switch ( LA(1) ) - { - case IDENT: - case LITERAL_const: - { - parameterDeclaration(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case REST: - { - parameterRestDeclaration(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - } - else - { - goto _loop50_breakloop; - } - - } -_loop50_breakloop: ; - } // ( ... )* - break; - } - case RPAREN: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - e = LT(1); - e_AST = astFactory.create(e); - match(RPAREN); - if (0==inputState.guessing) - { - parameterDeclarationList_AST = (AST)currentAST.root; - parameterDeclarationList_AST = (AST) astFactory.make(astFactory.create(PARAMS,"PARAMS"), parameterDeclarationList_AST); - setRegionInfo(parameterDeclarationList_AST,s_AST,e_AST); - currentAST.root = parameterDeclarationList_AST; - if ( (null != parameterDeclarationList_AST) && (null != parameterDeclarationList_AST.getFirstChild()) ) - currentAST.child = parameterDeclarationList_AST.getFirstChild(); - else - currentAST.child = parameterDeclarationList_AST; - currentAST.advanceChildToEnd(); - } - parameterDeclarationList_AST = currentAST.root; - returnAST = parameterDeclarationList_AST; - } - - public void typeExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST parameterDeclarationList_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LPAREN); + { + switch ( LA(1) ) + { + case IDENT: + case LITERAL_const: + case REST: + { + { + switch ( LA(1) ) + { + case IDENT: + case LITERAL_const: + { + parameterDeclaration(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case REST: + { + parameterRestDeclaration(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + match(COMMA); + { + switch ( LA(1) ) + { + case IDENT: + case LITERAL_const: + { + parameterDeclaration(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case REST: + { + parameterRestDeclaration(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + } + else + { + goto _loop50_breakloop; + } + + } +_loop50_breakloop: ; + } // ( ... )* + break; + } + case RPAREN: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + e = LT(1); + e_AST = astFactory.create(e); + match(RPAREN); + if (0==inputState.guessing) + { + parameterDeclarationList_AST = (AST)currentAST.root; + parameterDeclarationList_AST = (AST) astFactory.make(astFactory.create(PARAMS,"PARAMS"), parameterDeclarationList_AST); + setRegionInfo(parameterDeclarationList_AST,s_AST,e_AST); + currentAST.root = parameterDeclarationList_AST; + if ( (null != parameterDeclarationList_AST) && (null != parameterDeclarationList_AST.getFirstChild()) ) + currentAST.child = parameterDeclarationList_AST.getFirstChild(); + else + currentAST.child = parameterDeclarationList_AST; + currentAST.advanceChildToEnd(); + } + parameterDeclarationList_AST = currentAST.root; + returnAST = parameterDeclarationList_AST; + } + + public void typeExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST typeExpression_AST = null; - - { - switch ( LA(1) ) - { - case COLON: - { - match(COLON); - identifier(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - typeExpression_AST = (AST)currentAST.root; - typeExpression_AST = (AST) astFactory.make(astFactory.create(TYPE_SPEC,"TYPE_SPEC"), typeExpression_AST); - currentAST.root = typeExpression_AST; - if ( (null != typeExpression_AST) && (null != typeExpression_AST.getFirstChild()) ) - currentAST.child = typeExpression_AST.getFirstChild(); - else - currentAST.child = typeExpression_AST; - currentAST.advanceChildToEnd(); - } - break; - } - case LCURLY: - case SEMI: - case RCURLY: - case LITERAL_import: - case LBRACK: - case COMMA: - case LPAREN: - case RPAREN: - case LITERAL_class: - case LITERAL_interface: - case LITERAL_function: - case IDENT: - case LITERAL_namespace: - case LITERAL_var: - case LITERAL_const: - case ASSIGN: - case LITERAL_while: - case LITERAL_do: - case LITERAL_with: - case LITERAL_if: - case LITERAL_else: - case LITERAL_throw: - case LITERAL_return: - case LITERAL_continue: - case LITERAL_break: - case LITERAL_switch: - case LITERAL_case: - case LITERAL_default: - case LITERAL_for: - case LITERAL_in: - case LITERAL_public: - case LITERAL_private: - case LITERAL_protected: - case LITERAL_internal: - case LITERAL_static: - case LITERAL_final: - case LITERAL_enumerable: - case LITERAL_explicit: - case LITERAL_override: - case LITERAL_dynamic: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - typeExpression_AST = currentAST.root; - returnAST = typeExpression_AST; - } - - public void block() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST typeExpression_AST = null; + + { + switch ( LA(1) ) + { + case COLON: + { + match(COLON); + identifier(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + typeExpression_AST = (AST)currentAST.root; + typeExpression_AST = (AST) astFactory.make(astFactory.create(TYPE_SPEC,"TYPE_SPEC"), typeExpression_AST); + currentAST.root = typeExpression_AST; + if ( (null != typeExpression_AST) && (null != typeExpression_AST.getFirstChild()) ) + currentAST.child = typeExpression_AST.getFirstChild(); + else + currentAST.child = typeExpression_AST; + currentAST.advanceChildToEnd(); + } + break; + } + case LCURLY: + case SEMI: + case RCURLY: + case LITERAL_import: + case LBRACK: + case COMMA: + case LPAREN: + case RPAREN: + case LITERAL_class: + case LITERAL_interface: + case LITERAL_function: + case IDENT: + case LITERAL_namespace: + case LITERAL_var: + case LITERAL_const: + case ASSIGN: + case LITERAL_while: + case LITERAL_do: + case LITERAL_with: + case LITERAL_if: + case LITERAL_else: + case LITERAL_throw: + case LITERAL_return: + case LITERAL_continue: + case LITERAL_break: + case LITERAL_switch: + case LITERAL_case: + case LITERAL_default: + case LITERAL_for: + case LITERAL_in: + case LITERAL_public: + case LITERAL_private: + case LITERAL_protected: + case LITERAL_internal: + case LITERAL_static: + case LITERAL_final: + case LITERAL_enumerable: + case LITERAL_explicit: + case LITERAL_override: + case LITERAL_dynamic: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + typeExpression_AST = currentAST.root; + returnAST = typeExpression_AST; + } + + public void block() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST block_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LCURLY); - { // ( ... )* - for (;;) - { - if ((tokenSet_1_.member(LA(1)))) - { - statement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop58_breakloop; - } - - } -_loop58_breakloop: ; - } // ( ... )* - e = LT(1); - e_AST = astFactory.create(e); - match(RCURLY); - if (0==inputState.guessing) - { - block_AST = (AST)currentAST.root; - block_AST = (AST) astFactory.make(astFactory.create(BLOCK,"BLOCK"), block_AST); - setRegionInfo(block_AST,s_AST,e_AST); - currentAST.root = block_AST; - if ( (null != block_AST) && (null != block_AST.getFirstChild()) ) - currentAST.child = block_AST.getFirstChild(); - else - currentAST.child = block_AST; - currentAST.advanceChildToEnd(); - } - block_AST = currentAST.root; - returnAST = block_AST; - } - - public void variableDeclarator( - AST mods - ) //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST block_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LCURLY); + { // ( ... )* + for (;;) + { + if ((tokenSet_1_.member(LA(1)))) + { + statement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop58_breakloop; + } + + } +_loop58_breakloop: ; + } // ( ... )* + e = LT(1); + e_AST = astFactory.create(e); + match(RCURLY); + if (0==inputState.guessing) + { + block_AST = (AST)currentAST.root; + block_AST = (AST) astFactory.make(astFactory.create(BLOCK,"BLOCK"), block_AST); + setRegionInfo(block_AST,s_AST,e_AST); + currentAST.root = block_AST; + if ( (null != block_AST) && (null != block_AST.getFirstChild()) ) + currentAST.child = block_AST.getFirstChild(); + else + currentAST.child = block_AST; + currentAST.advanceChildToEnd(); + } + block_AST = currentAST.root; + returnAST = block_AST; + } + + public void variableDeclarator( + AST mods + ) //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST variableDeclarator_AST = null; - IToken s = null; - AST s_AST = null; - AST e1_AST = null; - AST e2_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.addASTChild(ref currentAST, s_AST); - match(IDENT); - typeExpression(); - if (0 == inputState.guessing) - { - e1_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { - switch ( LA(1) ) - { - case ASSIGN: - { - variableInitializer(); - if (0 == inputState.guessing) - { - e2_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LCURLY: - case SEMI: - case RCURLY: - case LITERAL_import: - case LBRACK: - case COMMA: - case LPAREN: - case LITERAL_class: - case LITERAL_interface: - case LITERAL_function: - case IDENT: - case LITERAL_namespace: - case LITERAL_var: - case LITERAL_const: - case LITERAL_while: - case LITERAL_do: - case LITERAL_with: - case LITERAL_if: - case LITERAL_else: - case LITERAL_throw: - case LITERAL_return: - case LITERAL_continue: - case LITERAL_break: - case LITERAL_switch: - case LITERAL_case: - case LITERAL_default: - case LITERAL_for: - case LITERAL_in: - case LITERAL_public: - case LITERAL_private: - case LITERAL_protected: - case LITERAL_internal: - case LITERAL_static: - case LITERAL_final: - case LITERAL_enumerable: - case LITERAL_explicit: - case LITERAL_override: - case LITERAL_dynamic: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - variableDeclarator_AST = (AST)currentAST.root; - variableDeclarator_AST = (AST) astFactory.make(astFactory.create(VARIABLE_DEF,"VARIABLE_DEF"), variableDeclarator_AST, mods); - setRegionInfo(variableDeclarator_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - currentAST.root = variableDeclarator_AST; - if ( (null != variableDeclarator_AST) && (null != variableDeclarator_AST.getFirstChild()) ) - currentAST.child = variableDeclarator_AST.getFirstChild(); - else - currentAST.child = variableDeclarator_AST; - currentAST.advanceChildToEnd(); - } - variableDeclarator_AST = currentAST.root; - returnAST = variableDeclarator_AST; - } - - public void variableInitializer() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST variableDeclarator_AST = null; + IToken s = null; + AST s_AST = null; + AST e1_AST = null; + AST e2_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.addASTChild(ref currentAST, s_AST); + match(IDENT); + typeExpression(); + if (0 == inputState.guessing) + { + e1_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { + switch ( LA(1) ) + { + case ASSIGN: + { + variableInitializer(); + if (0 == inputState.guessing) + { + e2_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LCURLY: + case SEMI: + case RCURLY: + case LITERAL_import: + case LBRACK: + case COMMA: + case LPAREN: + case LITERAL_class: + case LITERAL_interface: + case LITERAL_function: + case IDENT: + case LITERAL_namespace: + case LITERAL_var: + case LITERAL_const: + case LITERAL_while: + case LITERAL_do: + case LITERAL_with: + case LITERAL_if: + case LITERAL_else: + case LITERAL_throw: + case LITERAL_return: + case LITERAL_continue: + case LITERAL_break: + case LITERAL_switch: + case LITERAL_case: + case LITERAL_default: + case LITERAL_for: + case LITERAL_in: + case LITERAL_public: + case LITERAL_private: + case LITERAL_protected: + case LITERAL_internal: + case LITERAL_static: + case LITERAL_final: + case LITERAL_enumerable: + case LITERAL_explicit: + case LITERAL_override: + case LITERAL_dynamic: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + variableDeclarator_AST = (AST)currentAST.root; + variableDeclarator_AST = (AST) astFactory.make(astFactory.create(VARIABLE_DEF,"VARIABLE_DEF"), variableDeclarator_AST, mods); + setRegionInfo(variableDeclarator_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + currentAST.root = variableDeclarator_AST; + if ( (null != variableDeclarator_AST) && (null != variableDeclarator_AST.getFirstChild()) ) + currentAST.child = variableDeclarator_AST.getFirstChild(); + else + currentAST.child = variableDeclarator_AST; + currentAST.advanceChildToEnd(); + } + variableDeclarator_AST = currentAST.root; + returnAST = variableDeclarator_AST; + } + + public void variableInitializer() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST variableInitializer_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(ASSIGN); - expression(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - variableInitializer_AST = (AST)currentAST.root; - setRegionInfo(variableInitializer_AST,s_AST,e_AST); - } - variableInitializer_AST = currentAST.root; - returnAST = variableInitializer_AST; - } - - public void declaration() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST variableInitializer_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(ASSIGN); + expression(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + variableInitializer_AST = (AST)currentAST.root; + setRegionInfo(variableInitializer_AST,s_AST,e_AST); + } + variableInitializer_AST = currentAST.root; + returnAST = variableInitializer_AST; + } + + public void declaration() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST declaration_AST = null; - - match(LITERAL_var); - variableDeclarator(null); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - match(COMMA); - variableDeclarator(null); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop43_breakloop; - } - - } -_loop43_breakloop: ; - } // ( ... )* - declaration_AST = currentAST.root; - returnAST = declaration_AST; - } - - public void parameterDeclaration() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST declaration_AST = null; + + match(LITERAL_var); + variableDeclarator(null); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + match(COMMA); + variableDeclarator(null); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop43_breakloop; + } + + } +_loop43_breakloop: ; + } // ( ... )* + declaration_AST = currentAST.root; + returnAST = declaration_AST; + } + + public void parameterDeclaration() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST parameterDeclaration_AST = null; - - { - switch ( LA(1) ) - { - case LITERAL_const: - { - AST tmp28_AST = null; - tmp28_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp28_AST); - match(LITERAL_const); - break; - } - case IDENT: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - AST tmp29_AST = null; - tmp29_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp29_AST); - match(IDENT); - typeExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { - switch ( LA(1) ) - { - case ASSIGN: - { - AST tmp30_AST = null; - tmp30_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp30_AST); - match(ASSIGN); - assignmentExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case COMMA: - case RPAREN: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - parameterDeclaration_AST = (AST)currentAST.root; - parameterDeclaration_AST = (AST) astFactory.make(astFactory.create(PARAM,"PARAM"), parameterDeclaration_AST); - currentAST.root = parameterDeclaration_AST; - if ( (null != parameterDeclaration_AST) && (null != parameterDeclaration_AST.getFirstChild()) ) - currentAST.child = parameterDeclaration_AST.getFirstChild(); - else - currentAST.child = parameterDeclaration_AST; - currentAST.advanceChildToEnd(); - } - parameterDeclaration_AST = currentAST.root; - returnAST = parameterDeclaration_AST; - } - - public void parameterRestDeclaration() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST parameterDeclaration_AST = null; + + { + switch ( LA(1) ) + { + case LITERAL_const: + { + AST tmp28_AST = null; + tmp28_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp28_AST); + match(LITERAL_const); + break; + } + case IDENT: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + AST tmp29_AST = null; + tmp29_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp29_AST); + match(IDENT); + typeExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { + switch ( LA(1) ) + { + case ASSIGN: + { + AST tmp30_AST = null; + tmp30_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp30_AST); + match(ASSIGN); + assignmentExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case COMMA: + case RPAREN: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + parameterDeclaration_AST = (AST)currentAST.root; + parameterDeclaration_AST = (AST) astFactory.make(astFactory.create(PARAM,"PARAM"), parameterDeclaration_AST); + currentAST.root = parameterDeclaration_AST; + if ( (null != parameterDeclaration_AST) && (null != parameterDeclaration_AST.getFirstChild()) ) + currentAST.child = parameterDeclaration_AST.getFirstChild(); + else + currentAST.child = parameterDeclaration_AST; + currentAST.advanceChildToEnd(); + } + parameterDeclaration_AST = currentAST.root; + returnAST = parameterDeclaration_AST; + } + + public void parameterRestDeclaration() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST parameterRestDeclaration_AST = null; - - AST tmp31_AST = null; - tmp31_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp31_AST); - match(REST); - { - switch ( LA(1) ) - { - case LITERAL_const: - { - AST tmp32_AST = null; - tmp32_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp32_AST); - match(LITERAL_const); - break; - } - case IDENT: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - AST tmp33_AST = null; - tmp33_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp33_AST); - match(IDENT); - if (0==inputState.guessing) - { - parameterRestDeclaration_AST = (AST)currentAST.root; - parameterRestDeclaration_AST = (AST) astFactory.make(astFactory.create(PARAM,"PARAM"), parameterRestDeclaration_AST); - currentAST.root = parameterRestDeclaration_AST; - if ( (null != parameterRestDeclaration_AST) && (null != parameterRestDeclaration_AST.getFirstChild()) ) - currentAST.child = parameterRestDeclaration_AST.getFirstChild(); - else - currentAST.child = parameterRestDeclaration_AST; - currentAST.advanceChildToEnd(); - } - parameterRestDeclaration_AST = currentAST.root; - returnAST = parameterRestDeclaration_AST; - } - - public void assignmentExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST parameterRestDeclaration_AST = null; + + AST tmp31_AST = null; + tmp31_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp31_AST); + match(REST); + { + switch ( LA(1) ) + { + case LITERAL_const: + { + AST tmp32_AST = null; + tmp32_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp32_AST); + match(LITERAL_const); + break; + } + case IDENT: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + AST tmp33_AST = null; + tmp33_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp33_AST); + match(IDENT); + if (0==inputState.guessing) + { + parameterRestDeclaration_AST = (AST)currentAST.root; + parameterRestDeclaration_AST = (AST) astFactory.make(astFactory.create(PARAM,"PARAM"), parameterRestDeclaration_AST); + currentAST.root = parameterRestDeclaration_AST; + if ( (null != parameterRestDeclaration_AST) && (null != parameterRestDeclaration_AST.getFirstChild()) ) + currentAST.child = parameterRestDeclaration_AST.getFirstChild(); + else + currentAST.child = parameterRestDeclaration_AST; + currentAST.advanceChildToEnd(); + } + parameterRestDeclaration_AST = currentAST.root; + returnAST = parameterRestDeclaration_AST; + } + + public void assignmentExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST assignmentExpression_AST = null; - AST s_AST = null; - AST e_AST = null; - - conditionalExpression(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { - bool synPredMatched147 = false; - if (((tokenSet_2_.member(LA(1))) && (tokenSet_3_.member(LA(2))))) - { - int _m147 = mark(); - synPredMatched147 = true; - inputState.guessing++; - try { - { - { - switch ( LA(1) ) - { - case ASSIGN: - { - match(ASSIGN); - break; - } - case STAR_ASSIGN: - { - match(STAR_ASSIGN); - break; - } - case DIV_ASSIGN: - { - match(DIV_ASSIGN); - break; - } - case MOD_ASSIGN: - { - match(MOD_ASSIGN); - break; - } - case PLUS_ASSIGN: - { - match(PLUS_ASSIGN); - break; - } - case MINUS_ASSIGN: - { - match(MINUS_ASSIGN); - break; - } - case SL_ASSIGN: - { - match(SL_ASSIGN); - break; - } - case SR_ASSIGN: - { - match(SR_ASSIGN); - break; - } - case BSR_ASSIGN: - { - match(BSR_ASSIGN); - break; - } - case BAND_ASSIGN: - { - match(BAND_ASSIGN); - break; - } - case BXOR_ASSIGN: - { - match(BXOR_ASSIGN); - break; - } - case BOR_ASSIGN: - { - match(BOR_ASSIGN); - break; - } - case LAND_ASSIGN: - { - match(LAND_ASSIGN); - break; - } - case LOR_ASSIGN: - { - match(LOR_ASSIGN); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - matchNot(ASSIGN); - } - } - catch (RecognitionException) - { - synPredMatched147 = false; - } - rewind(_m147); - inputState.guessing--; - } - if ( synPredMatched147 ) - { - { - switch ( LA(1) ) - { - case ASSIGN: - { - AST tmp34_AST = null; - tmp34_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp34_AST); - match(ASSIGN); - break; - } - case STAR_ASSIGN: - { - AST tmp35_AST = null; - tmp35_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp35_AST); - match(STAR_ASSIGN); - break; - } - case DIV_ASSIGN: - { - AST tmp36_AST = null; - tmp36_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp36_AST); - match(DIV_ASSIGN); - break; - } - case MOD_ASSIGN: - { - AST tmp37_AST = null; - tmp37_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp37_AST); - match(MOD_ASSIGN); - break; - } - case PLUS_ASSIGN: - { - AST tmp38_AST = null; - tmp38_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp38_AST); - match(PLUS_ASSIGN); - break; - } - case MINUS_ASSIGN: - { - AST tmp39_AST = null; - tmp39_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp39_AST); - match(MINUS_ASSIGN); - break; - } - case SL_ASSIGN: - { - AST tmp40_AST = null; - tmp40_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp40_AST); - match(SL_ASSIGN); - break; - } - case SR_ASSIGN: - { - AST tmp41_AST = null; - tmp41_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp41_AST); - match(SR_ASSIGN); - break; - } - case BSR_ASSIGN: - { - AST tmp42_AST = null; - tmp42_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp42_AST); - match(BSR_ASSIGN); - break; - } - case BAND_ASSIGN: - { - AST tmp43_AST = null; - tmp43_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp43_AST); - match(BAND_ASSIGN); - break; - } - case BXOR_ASSIGN: - { - AST tmp44_AST = null; - tmp44_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp44_AST); - match(BXOR_ASSIGN); - break; - } - case BOR_ASSIGN: - { - AST tmp45_AST = null; - tmp45_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp45_AST); - match(BOR_ASSIGN); - break; - } - case LAND_ASSIGN: - { - AST tmp46_AST = null; - tmp46_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp46_AST); - match(LAND_ASSIGN); - break; - } - case LOR_ASSIGN: - { - AST tmp47_AST = null; - tmp47_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp47_AST); - match(LOR_ASSIGN); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - assignmentExpression(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - assignmentExpression_AST = (AST)currentAST.root; - setRegionInfo(assignmentExpression_AST,s_AST,e_AST); - } - } - else if ((tokenSet_4_.member(LA(1))) && (tokenSet_5_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - assignmentExpression_AST = currentAST.root; - returnAST = assignmentExpression_AST; - } - - public void statement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST assignmentExpression_AST = null; + AST s_AST = null; + AST e_AST = null; + + conditionalExpression(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { + bool synPredMatched147 = false; + if (((tokenSet_2_.member(LA(1))) && (tokenSet_3_.member(LA(2))))) + { + int _m147 = mark(); + synPredMatched147 = true; + inputState.guessing++; + try { + { + { + switch ( LA(1) ) + { + case ASSIGN: + { + match(ASSIGN); + break; + } + case STAR_ASSIGN: + { + match(STAR_ASSIGN); + break; + } + case DIV_ASSIGN: + { + match(DIV_ASSIGN); + break; + } + case MOD_ASSIGN: + { + match(MOD_ASSIGN); + break; + } + case PLUS_ASSIGN: + { + match(PLUS_ASSIGN); + break; + } + case MINUS_ASSIGN: + { + match(MINUS_ASSIGN); + break; + } + case SL_ASSIGN: + { + match(SL_ASSIGN); + break; + } + case SR_ASSIGN: + { + match(SR_ASSIGN); + break; + } + case BSR_ASSIGN: + { + match(BSR_ASSIGN); + break; + } + case BAND_ASSIGN: + { + match(BAND_ASSIGN); + break; + } + case BXOR_ASSIGN: + { + match(BXOR_ASSIGN); + break; + } + case BOR_ASSIGN: + { + match(BOR_ASSIGN); + break; + } + case LAND_ASSIGN: + { + match(LAND_ASSIGN); + break; + } + case LOR_ASSIGN: + { + match(LOR_ASSIGN); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + matchNot(ASSIGN); + } + } + catch (RecognitionException) + { + synPredMatched147 = false; + } + rewind(_m147); + inputState.guessing--; + } + if ( synPredMatched147 ) + { + { + switch ( LA(1) ) + { + case ASSIGN: + { + AST tmp34_AST = null; + tmp34_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp34_AST); + match(ASSIGN); + break; + } + case STAR_ASSIGN: + { + AST tmp35_AST = null; + tmp35_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp35_AST); + match(STAR_ASSIGN); + break; + } + case DIV_ASSIGN: + { + AST tmp36_AST = null; + tmp36_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp36_AST); + match(DIV_ASSIGN); + break; + } + case MOD_ASSIGN: + { + AST tmp37_AST = null; + tmp37_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp37_AST); + match(MOD_ASSIGN); + break; + } + case PLUS_ASSIGN: + { + AST tmp38_AST = null; + tmp38_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp38_AST); + match(PLUS_ASSIGN); + break; + } + case MINUS_ASSIGN: + { + AST tmp39_AST = null; + tmp39_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp39_AST); + match(MINUS_ASSIGN); + break; + } + case SL_ASSIGN: + { + AST tmp40_AST = null; + tmp40_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp40_AST); + match(SL_ASSIGN); + break; + } + case SR_ASSIGN: + { + AST tmp41_AST = null; + tmp41_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp41_AST); + match(SR_ASSIGN); + break; + } + case BSR_ASSIGN: + { + AST tmp42_AST = null; + tmp42_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp42_AST); + match(BSR_ASSIGN); + break; + } + case BAND_ASSIGN: + { + AST tmp43_AST = null; + tmp43_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp43_AST); + match(BAND_ASSIGN); + break; + } + case BXOR_ASSIGN: + { + AST tmp44_AST = null; + tmp44_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp44_AST); + match(BXOR_ASSIGN); + break; + } + case BOR_ASSIGN: + { + AST tmp45_AST = null; + tmp45_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp45_AST); + match(BOR_ASSIGN); + break; + } + case LAND_ASSIGN: + { + AST tmp46_AST = null; + tmp46_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp46_AST); + match(LAND_ASSIGN); + break; + } + case LOR_ASSIGN: + { + AST tmp47_AST = null; + tmp47_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp47_AST); + match(LOR_ASSIGN); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + assignmentExpression(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + assignmentExpression_AST = (AST)currentAST.root; + setRegionInfo(assignmentExpression_AST,s_AST,e_AST); + } + } + else if ((tokenSet_4_.member(LA(1))) && (tokenSet_5_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + assignmentExpression_AST = currentAST.root; + returnAST = assignmentExpression_AST; + } + + public void statement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST statement_AST = null; - AST s1_AST = null; - IToken e1 = null; - AST e1_AST = null; - AST s2_AST = null; - IToken e2 = null; - AST e2_AST = null; - - switch ( LA(1) ) - { - case LITERAL_var: - { - declaration(); - if (0 == inputState.guessing) - { - s1_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { - if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) - { - { - e1 = LT(1); - e1_AST = astFactory.create(e1); - match(SEMI); - } - } - else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - if (0==inputState.guessing) - { - statement_AST = (AST)currentAST.root; - setRegionInfo(statement_AST,s1_AST,e1_AST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_if: - { - ifStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_for: - { - forStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_while: - { - AST tmp48_AST = null; - tmp48_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp48_AST); - match(LITERAL_while); - match(LPAREN); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - match(RPAREN); - statement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_do: - { - AST tmp51_AST = null; - tmp51_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp51_AST); - match(LITERAL_do); - statement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - match(LITERAL_while); - match(LPAREN); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - match(RPAREN); - statement_AST = currentAST.root; - break; - } - case LITERAL_with: - { - AST tmp55_AST = null; - tmp55_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp55_AST); - match(LITERAL_with); - match(LPAREN); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - match(RPAREN); - statement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_switch: - { - switchStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_break: - { - breakStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_continue: - { - continueStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_return: - { - returnStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case LITERAL_throw: - { - throwStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - statement_AST = currentAST.root; - break; - } - case SEMI: - { - match(SEMI); - statement_AST = currentAST.root; - break; - } - default: - if (((LA(1)==LCURLY) && (tokenSet_8_.member(LA(2))))&&(LA(1)==LCURLY)) - { - { - block(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - statement_AST = currentAST.root; - } - else if ((tokenSet_3_.member(LA(1))) && (tokenSet_9_.member(LA(2)))) { - assignmentExpression(); - if (0 == inputState.guessing) - { - s2_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { - if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) - { - { - e2 = LT(1); - e2_AST = astFactory.create(e2); - match(SEMI); - } - } - else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - if (0==inputState.guessing) - { - statement_AST = (AST)currentAST.root; - statement_AST = (AST) astFactory.make(astFactory.create(EXPR_STMNT,"EXPR_STMNT"), statement_AST); - setRegionInfo(statement_AST,s2_AST,e2_AST); - currentAST.root = statement_AST; - if ( (null != statement_AST) && (null != statement_AST.getFirstChild()) ) - currentAST.child = statement_AST.getFirstChild(); - else - currentAST.child = statement_AST; - currentAST.advanceChildToEnd(); - } - statement_AST = currentAST.root; - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - break; } - returnAST = statement_AST; - } - - public void ifStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST statement_AST = null; + AST s1_AST = null; + IToken e1 = null; + AST e1_AST = null; + AST s2_AST = null; + IToken e2 = null; + AST e2_AST = null; + + switch ( LA(1) ) + { + case LITERAL_var: + { + declaration(); + if (0 == inputState.guessing) + { + s1_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { + if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) + { + { + e1 = LT(1); + e1_AST = astFactory.create(e1); + match(SEMI); + } + } + else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + if (0==inputState.guessing) + { + statement_AST = (AST)currentAST.root; + setRegionInfo(statement_AST,s1_AST,e1_AST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_if: + { + ifStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_for: + { + forStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_while: + { + AST tmp48_AST = null; + tmp48_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp48_AST); + match(LITERAL_while); + match(LPAREN); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + match(RPAREN); + statement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_do: + { + AST tmp51_AST = null; + tmp51_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp51_AST); + match(LITERAL_do); + statement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + match(LITERAL_while); + match(LPAREN); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + match(RPAREN); + statement_AST = currentAST.root; + break; + } + case LITERAL_with: + { + AST tmp55_AST = null; + tmp55_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp55_AST); + match(LITERAL_with); + match(LPAREN); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + match(RPAREN); + statement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_switch: + { + switchStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_break: + { + breakStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_continue: + { + continueStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_return: + { + returnStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case LITERAL_throw: + { + throwStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + statement_AST = currentAST.root; + break; + } + case SEMI: + { + match(SEMI); + statement_AST = currentAST.root; + break; + } + default: + if (((LA(1)==LCURLY) && (tokenSet_8_.member(LA(2))))&&(LA(1)==LCURLY)) + { + { + block(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + statement_AST = currentAST.root; + } + else if ((tokenSet_3_.member(LA(1))) && (tokenSet_9_.member(LA(2)))) { + assignmentExpression(); + if (0 == inputState.guessing) + { + s2_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { + if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) + { + { + e2 = LT(1); + e2_AST = astFactory.create(e2); + match(SEMI); + } + } + else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + if (0==inputState.guessing) + { + statement_AST = (AST)currentAST.root; + statement_AST = (AST) astFactory.make(astFactory.create(EXPR_STMNT,"EXPR_STMNT"), statement_AST); + setRegionInfo(statement_AST,s2_AST,e2_AST); + currentAST.root = statement_AST; + if ( (null != statement_AST) && (null != statement_AST.getFirstChild()) ) + currentAST.child = statement_AST.getFirstChild(); + else + currentAST.child = statement_AST; + currentAST.advanceChildToEnd(); + } + statement_AST = currentAST.root; + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + break; } + returnAST = statement_AST; + } + + public void ifStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST ifStatement_AST = null; - IToken s = null; - AST s_AST = null; - AST e1_AST = null; - AST e2_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_if); - match(LPAREN); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - match(RPAREN); - statement(); - if (0 == inputState.guessing) - { - e1_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==LITERAL_else) && (tokenSet_1_.member(LA(2)))) - { - elseStatement(); - if (0 == inputState.guessing) - { - e2_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop67_breakloop; - } - - } -_loop67_breakloop: ; - } // ( ... )* - if (0==inputState.guessing) - { - ifStatement_AST = (AST)currentAST.root; - setRegionInfo(ifStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - } - ifStatement_AST = currentAST.root; - returnAST = ifStatement_AST; - } - - public void forStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST ifStatement_AST = null; + IToken s = null; + AST s_AST = null; + AST e1_AST = null; + AST e2_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_if); + match(LPAREN); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + match(RPAREN); + statement(); + if (0 == inputState.guessing) + { + e1_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==LITERAL_else) && (tokenSet_1_.member(LA(2)))) + { + elseStatement(); + if (0 == inputState.guessing) + { + e2_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop67_breakloop; + } + + } +_loop67_breakloop: ; + } // ( ... )* + if (0==inputState.guessing) + { + ifStatement_AST = (AST)currentAST.root; + setRegionInfo(ifStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + } + ifStatement_AST = currentAST.root; + returnAST = ifStatement_AST; + } + + public void forStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST forStatement_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_for); - { - bool synPredMatched96 = false; - if (((LA(1)==LPAREN) && (tokenSet_10_.member(LA(2))))) - { - int _m96 = mark(); - synPredMatched96 = true; - inputState.guessing++; - try { - { - match(LPAREN); - forInit(); - match(SEMI); - } - } - catch (RecognitionException) - { - synPredMatched96 = false; - } - rewind(_m96); - inputState.guessing--; - } - if ( synPredMatched96 ) - { - traditionalForClause(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else if ((LA(1)==LITERAL_each)) { - { - AST tmp61_AST = null; - tmp61_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp61_AST); - match(LITERAL_each); - forInClause(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - } - else if ((LA(1)==LPAREN) && (LA(2)==LITERAL_var)) { - forInClause(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - statement(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - forStatement_AST = (AST)currentAST.root; - setRegionInfo(forStatement_AST,s_AST,e_AST); - } - forStatement_AST = currentAST.root; - returnAST = forStatement_AST; - } - - public void switchStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST forStatement_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_for); + { + bool synPredMatched96 = false; + if (((LA(1)==LPAREN) && (tokenSet_10_.member(LA(2))))) + { + int _m96 = mark(); + synPredMatched96 = true; + inputState.guessing++; + try { + { + match(LPAREN); + forInit(); + match(SEMI); + } + } + catch (RecognitionException) + { + synPredMatched96 = false; + } + rewind(_m96); + inputState.guessing--; + } + if ( synPredMatched96 ) + { + traditionalForClause(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else if ((LA(1)==LITERAL_each)) { + { + AST tmp61_AST = null; + tmp61_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp61_AST); + match(LITERAL_each); + forInClause(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + } + else if ((LA(1)==LPAREN) && (LA(2)==LITERAL_var)) { + forInClause(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + statement(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + forStatement_AST = (AST)currentAST.root; + setRegionInfo(forStatement_AST,s_AST,e_AST); + } + forStatement_AST = currentAST.root; + returnAST = forStatement_AST; + } + + public void switchStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST switchStatement_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_switch); - match(LPAREN); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - match(RPAREN); - switchBlock(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - switchStatement_AST = (AST)currentAST.root; - setRegionInfo(switchStatement_AST,s_AST,e_AST); - } - switchStatement_AST = currentAST.root; - returnAST = switchStatement_AST; - } - - public void breakStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST switchStatement_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_switch); + match(LPAREN); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + match(RPAREN); + switchBlock(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + switchStatement_AST = (AST)currentAST.root; + setRegionInfo(switchStatement_AST,s_AST,e_AST); + } + switchStatement_AST = currentAST.root; + returnAST = switchStatement_AST; + } + + public void breakStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST breakStatement_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_break); - { - if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) - { - { - e = LT(1); - e_AST = astFactory.create(e); - match(SEMI); - } - } - else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - if (0==inputState.guessing) - { - breakStatement_AST = (AST)currentAST.root; - setRegionInfo(breakStatement_AST,s_AST,e_AST); - } - breakStatement_AST = currentAST.root; - returnAST = breakStatement_AST; - } - - public void continueStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST breakStatement_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_break); + { + if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) + { + { + e = LT(1); + e_AST = astFactory.create(e); + match(SEMI); + } + } + else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + if (0==inputState.guessing) + { + breakStatement_AST = (AST)currentAST.root; + setRegionInfo(breakStatement_AST,s_AST,e_AST); + } + breakStatement_AST = currentAST.root; + returnAST = breakStatement_AST; + } + + public void continueStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST continueStatement_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_continue); - { - if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) - { - { - e = LT(1); - e_AST = astFactory.create(e); - match(SEMI); - } - } - else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - if (0==inputState.guessing) - { - continueStatement_AST = (AST)currentAST.root; - setRegionInfo(continueStatement_AST,s_AST,e_AST); - } - continueStatement_AST = currentAST.root; - returnAST = continueStatement_AST; - } - - public void returnStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST continueStatement_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_continue); + { + if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) + { + { + e = LT(1); + e_AST = astFactory.create(e); + match(SEMI); + } + } + else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + if (0==inputState.guessing) + { + continueStatement_AST = (AST)currentAST.root; + setRegionInfo(continueStatement_AST,s_AST,e_AST); + } + continueStatement_AST = currentAST.root; + returnAST = continueStatement_AST; + } + + public void returnStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST returnStatement_AST = null; - IToken s = null; - AST s_AST = null; - AST e1_AST = null; - IToken e2 = null; - AST e2_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_return); - { - if ((tokenSet_3_.member(LA(1))) && (tokenSet_9_.member(LA(2)))) - { - expression(); - if (0 == inputState.guessing) - { - e1_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - { - if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) - { - { - e2 = LT(1); - e2_AST = astFactory.create(e2); - match(SEMI); - } - } - else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - if (0==inputState.guessing) - { - returnStatement_AST = (AST)currentAST.root; - setRegionInfo(returnStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - } - returnStatement_AST = currentAST.root; - returnAST = returnStatement_AST; - } - - public void throwStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST returnStatement_AST = null; + IToken s = null; + AST s_AST = null; + AST e1_AST = null; + IToken e2 = null; + AST e2_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_return); + { + if ((tokenSet_3_.member(LA(1))) && (tokenSet_9_.member(LA(2)))) + { + expression(); + if (0 == inputState.guessing) + { + e1_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + { + if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) + { + { + e2 = LT(1); + e2_AST = astFactory.create(e2); + match(SEMI); + } + } + else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + if (0==inputState.guessing) + { + returnStatement_AST = (AST)currentAST.root; + setRegionInfo(returnStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + } + returnStatement_AST = currentAST.root; + returnAST = returnStatement_AST; + } + + public void throwStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST throwStatement_AST = null; - IToken s = null; - AST s_AST = null; - AST e1_AST = null; - IToken e2 = null; - AST e2_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_throw); - expression(); - if (0 == inputState.guessing) - { - e1_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { - if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) - { - { - e2 = LT(1); - e2_AST = astFactory.create(e2); - match(SEMI); - } - } - else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - if (0==inputState.guessing) - { - throwStatement_AST = (AST)currentAST.root; - setRegionInfo(throwStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - } - throwStatement_AST = currentAST.root; - returnAST = throwStatement_AST; - } - - public void elseStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST throwStatement_AST = null; + IToken s = null; + AST s_AST = null; + AST e1_AST = null; + IToken e2 = null; + AST e2_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_throw); + expression(); + if (0 == inputState.guessing) + { + e1_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { + if (((LA(1)==SEMI) && (tokenSet_6_.member(LA(2))))&&(LA(1)==SEMI)) + { + { + e2 = LT(1); + e2_AST = astFactory.create(e2); + match(SEMI); + } + } + else if ((tokenSet_6_.member(LA(1))) && (tokenSet_7_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + if (0==inputState.guessing) + { + throwStatement_AST = (AST)currentAST.root; + setRegionInfo(throwStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + } + throwStatement_AST = currentAST.root; + returnAST = throwStatement_AST; + } + + public void elseStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST elseStatement_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_else); - statement(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - elseStatement_AST = (AST)currentAST.root; - setRegionInfo(elseStatement_AST,s_AST,e_AST); - } - elseStatement_AST = currentAST.root; - returnAST = elseStatement_AST; - } - - public void switchBlock() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST elseStatement_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_else); + statement(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + elseStatement_AST = (AST)currentAST.root; + setRegionInfo(elseStatement_AST,s_AST,e_AST); + } + elseStatement_AST = currentAST.root; + returnAST = elseStatement_AST; + } + + public void switchBlock() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST switchBlock_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LCURLY); - { // ( ... )* - for (;;) - { - if ((LA(1)==LITERAL_case)) - { - caseStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop85_breakloop; - } - - } -_loop85_breakloop: ; - } // ( ... )* - { - switch ( LA(1) ) - { - case LITERAL_default: - { - defaultStatement(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case RCURLY: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - e = LT(1); - e_AST = astFactory.create(e); - match(RCURLY); - if (0==inputState.guessing) - { - switchBlock_AST = (AST)currentAST.root; - switchBlock_AST = (AST) astFactory.make(astFactory.create(BLOCK,"BLOCK"), switchBlock_AST); - setRegionInfo(switchBlock_AST,s_AST,e_AST); - currentAST.root = switchBlock_AST; - if ( (null != switchBlock_AST) && (null != switchBlock_AST.getFirstChild()) ) - currentAST.child = switchBlock_AST.getFirstChild(); - else - currentAST.child = switchBlock_AST; - currentAST.advanceChildToEnd(); - } - switchBlock_AST = currentAST.root; - returnAST = switchBlock_AST; - } - - public void caseStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST switchBlock_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LCURLY); + { // ( ... )* + for (;;) + { + if ((LA(1)==LITERAL_case)) + { + caseStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop85_breakloop; + } + + } +_loop85_breakloop: ; + } // ( ... )* + { + switch ( LA(1) ) + { + case LITERAL_default: + { + defaultStatement(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case RCURLY: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + e = LT(1); + e_AST = astFactory.create(e); + match(RCURLY); + if (0==inputState.guessing) + { + switchBlock_AST = (AST)currentAST.root; + switchBlock_AST = (AST) astFactory.make(astFactory.create(BLOCK,"BLOCK"), switchBlock_AST); + setRegionInfo(switchBlock_AST,s_AST,e_AST); + currentAST.root = switchBlock_AST; + if ( (null != switchBlock_AST) && (null != switchBlock_AST.getFirstChild()) ) + currentAST.child = switchBlock_AST.getFirstChild(); + else + currentAST.child = switchBlock_AST; + currentAST.advanceChildToEnd(); + } + switchBlock_AST = currentAST.root; + returnAST = switchBlock_AST; + } + + public void caseStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST caseStatement_AST = null; - IToken s = null; - AST s_AST = null; - IToken e1 = null; - AST e1_AST = null; - AST e2_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_case); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e1 = LT(1); - e1_AST = astFactory.create(e1); - match(COLON); - { // ( ... )* - for (;;) - { - if ((tokenSet_1_.member(LA(1)))) - { - statement(); - if (0 == inputState.guessing) - { - e2_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop89_breakloop; - } - - } -_loop89_breakloop: ; - } // ( ... )* - if (0==inputState.guessing) - { - caseStatement_AST = (AST)currentAST.root; - setRegionInfo(caseStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - } - caseStatement_AST = currentAST.root; - returnAST = caseStatement_AST; - } - - public void defaultStatement() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST caseStatement_AST = null; + IToken s = null; + AST s_AST = null; + IToken e1 = null; + AST e1_AST = null; + AST e2_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_case); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e1 = LT(1); + e1_AST = astFactory.create(e1); + match(COLON); + { // ( ... )* + for (;;) + { + if ((tokenSet_1_.member(LA(1)))) + { + statement(); + if (0 == inputState.guessing) + { + e2_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop89_breakloop; + } + + } +_loop89_breakloop: ; + } // ( ... )* + if (0==inputState.guessing) + { + caseStatement_AST = (AST)currentAST.root; + setRegionInfo(caseStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + } + caseStatement_AST = currentAST.root; + returnAST = caseStatement_AST; + } + + public void defaultStatement() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST defaultStatement_AST = null; - IToken s = null; - AST s_AST = null; - IToken e1 = null; - AST e1_AST = null; - AST e2_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.makeASTRoot(ref currentAST, s_AST); - match(LITERAL_default); - e1 = LT(1); - e1_AST = astFactory.create(e1); - match(COLON); - { // ( ... )* - for (;;) - { - if ((tokenSet_1_.member(LA(1)))) - { - statement(); - if (0 == inputState.guessing) - { - e2_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop92_breakloop; - } - - } -_loop92_breakloop: ; - } // ( ... )* - if (0==inputState.guessing) - { - defaultStatement_AST = (AST)currentAST.root; - setRegionInfo(defaultStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); - } - defaultStatement_AST = currentAST.root; - returnAST = defaultStatement_AST; - } - - public void forInit() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST defaultStatement_AST = null; + IToken s = null; + AST s_AST = null; + IToken e1 = null; + AST e1_AST = null; + AST e2_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.makeASTRoot(ref currentAST, s_AST); + match(LITERAL_default); + e1 = LT(1); + e1_AST = astFactory.create(e1); + match(COLON); + { // ( ... )* + for (;;) + { + if ((tokenSet_1_.member(LA(1)))) + { + statement(); + if (0 == inputState.guessing) + { + e2_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop92_breakloop; + } + + } +_loop92_breakloop: ; + } // ( ... )* + if (0==inputState.guessing) + { + defaultStatement_AST = (AST)currentAST.root; + setRegionInfo(defaultStatement_AST,s_AST,e2_AST==null?e1_AST:e2_AST); + } + defaultStatement_AST = currentAST.root; + returnAST = defaultStatement_AST; + } + + public void forInit() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST forInit_AST = null; - AST s1_AST = null; - AST s2_AST = null; - - { - switch ( LA(1) ) - { - case LITERAL_var: - { - declaration(); - if (0 == inputState.guessing) - { - s1_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case LCURLY: - case LBRACK: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - expressionList(); - if (0 == inputState.guessing) - { - s2_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case SEMI: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - forInit_AST = (AST)currentAST.root; - forInit_AST = (AST) astFactory.make(astFactory.create(FOR_INIT,"FOR_INIT"), forInit_AST); - setRegionInfo(forInit_AST,s2_AST==null?s1_AST:s2_AST,null); - currentAST.root = forInit_AST; - if ( (null != forInit_AST) && (null != forInit_AST.getFirstChild()) ) - currentAST.child = forInit_AST.getFirstChild(); - else - currentAST.child = forInit_AST; - currentAST.advanceChildToEnd(); - } - forInit_AST = currentAST.root; - returnAST = forInit_AST; - } - - public void traditionalForClause() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST forInit_AST = null; + AST s1_AST = null; + AST s2_AST = null; + + { + switch ( LA(1) ) + { + case LITERAL_var: + { + declaration(); + if (0 == inputState.guessing) + { + s1_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case LCURLY: + case LBRACK: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + expressionList(); + if (0 == inputState.guessing) + { + s2_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case SEMI: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + forInit_AST = (AST)currentAST.root; + forInit_AST = (AST) astFactory.make(astFactory.create(FOR_INIT,"FOR_INIT"), forInit_AST); + setRegionInfo(forInit_AST,s2_AST==null?s1_AST:s2_AST,null); + currentAST.root = forInit_AST; + if ( (null != forInit_AST) && (null != forInit_AST.getFirstChild()) ) + currentAST.child = forInit_AST.getFirstChild(); + else + currentAST.child = forInit_AST; + currentAST.advanceChildToEnd(); + } + forInit_AST = currentAST.root; + returnAST = forInit_AST; + } + + public void traditionalForClause() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST traditionalForClause_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LPAREN); - forInit(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - match(SEMI); - forCond(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - match(SEMI); - forIter(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e = LT(1); - e_AST = astFactory.create(e); - match(RPAREN); - if (0==inputState.guessing) - { - traditionalForClause_AST = (AST)currentAST.root; - setRegionInfo(traditionalForClause_AST,s_AST,e_AST); - } - traditionalForClause_AST = currentAST.root; - returnAST = traditionalForClause_AST; - } - - public void forInClause() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST traditionalForClause_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LPAREN); + forInit(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + match(SEMI); + forCond(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + match(SEMI); + forIter(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e = LT(1); + e_AST = astFactory.create(e); + match(RPAREN); + if (0==inputState.guessing) + { + traditionalForClause_AST = (AST)currentAST.root; + setRegionInfo(traditionalForClause_AST,s_AST,e_AST); + } + traditionalForClause_AST = currentAST.root; + returnAST = traditionalForClause_AST; + } + + public void forInClause() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST forInClause_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LPAREN); - declaration(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - AST tmp66_AST = null; - tmp66_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp66_AST); - match(LITERAL_in); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e = LT(1); - e_AST = astFactory.create(e); - match(RPAREN); - if (0==inputState.guessing) - { - forInClause_AST = (AST)currentAST.root; - setRegionInfo(forInClause_AST,s_AST,e_AST); - } - forInClause_AST = currentAST.root; - returnAST = forInClause_AST; - } - - public void forCond() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST forInClause_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LPAREN); + declaration(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + AST tmp66_AST = null; + tmp66_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp66_AST); + match(LITERAL_in); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e = LT(1); + e_AST = astFactory.create(e); + match(RPAREN); + if (0==inputState.guessing) + { + forInClause_AST = (AST)currentAST.root; + setRegionInfo(forInClause_AST,s_AST,e_AST); + } + forInClause_AST = currentAST.root; + returnAST = forInClause_AST; + } + + public void forCond() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST forCond_AST = null; - AST s_AST = null; - - { - switch ( LA(1) ) - { - case LCURLY: - case LBRACK: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - expression(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case SEMI: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - forCond_AST = (AST)currentAST.root; - forCond_AST = (AST) astFactory.make(astFactory.create(FOR_CONDITION,"FOR_CONDITION"), forCond_AST); - setRegionInfo(forCond_AST,s_AST,null); - currentAST.root = forCond_AST; - if ( (null != forCond_AST) && (null != forCond_AST.getFirstChild()) ) - currentAST.child = forCond_AST.getFirstChild(); - else - currentAST.child = forCond_AST; - currentAST.advanceChildToEnd(); - } - forCond_AST = currentAST.root; - returnAST = forCond_AST; - } - - public void forIter() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST forCond_AST = null; + AST s_AST = null; + + { + switch ( LA(1) ) + { + case LCURLY: + case LBRACK: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + expression(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case SEMI: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + forCond_AST = (AST)currentAST.root; + forCond_AST = (AST) astFactory.make(astFactory.create(FOR_CONDITION,"FOR_CONDITION"), forCond_AST); + setRegionInfo(forCond_AST,s_AST,null); + currentAST.root = forCond_AST; + if ( (null != forCond_AST) && (null != forCond_AST.getFirstChild()) ) + currentAST.child = forCond_AST.getFirstChild(); + else + currentAST.child = forCond_AST; + currentAST.advanceChildToEnd(); + } + forCond_AST = currentAST.root; + returnAST = forCond_AST; + } + + public void forIter() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST forIter_AST = null; - AST s_AST = null; - - { - switch ( LA(1) ) - { - case LCURLY: - case LBRACK: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - expressionList(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case RPAREN: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - if (0==inputState.guessing) - { - forIter_AST = (AST)currentAST.root; - forIter_AST = (AST) astFactory.make(astFactory.create(FOR_ITERATOR,"FOR_ITERATOR"), forIter_AST); - setRegionInfo(forIter_AST,s_AST,null); - currentAST.root = forIter_AST; - if ( (null != forIter_AST) && (null != forIter_AST.getFirstChild()) ) - currentAST.child = forIter_AST.getFirstChild(); - else - currentAST.child = forIter_AST; - currentAST.advanceChildToEnd(); - } - forIter_AST = currentAST.root; - returnAST = forIter_AST; - } - - public void expressionList() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST forIter_AST = null; + AST s_AST = null; + + { + switch ( LA(1) ) + { + case LCURLY: + case LBRACK: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + expressionList(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case RPAREN: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + if (0==inputState.guessing) + { + forIter_AST = (AST)currentAST.root; + forIter_AST = (AST) astFactory.make(astFactory.create(FOR_ITERATOR,"FOR_ITERATOR"), forIter_AST); + setRegionInfo(forIter_AST,s_AST,null); + currentAST.root = forIter_AST; + if ( (null != forIter_AST) && (null != forIter_AST.getFirstChild()) ) + currentAST.child = forIter_AST.getFirstChild(); + else + currentAST.child = forIter_AST; + currentAST.advanceChildToEnd(); + } + forIter_AST = currentAST.root; + returnAST = forIter_AST; + } + + public void expressionList() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST expressionList_AST = null; - AST s_AST = null; - AST e_AST = null; - - expression(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - match(COMMA); - expression(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop142_breakloop; - } - - } -_loop142_breakloop: ; - } // ( ... )* - if (0==inputState.guessing) - { - expressionList_AST = (AST)currentAST.root; - expressionList_AST = (AST) astFactory.make(astFactory.create(ELIST,"ELIST"), expressionList_AST); - setRegionInfo(expressionList_AST,s_AST,e_AST); - currentAST.root = expressionList_AST; - if ( (null != expressionList_AST) && (null != expressionList_AST.getFirstChild()) ) - currentAST.child = expressionList_AST.getFirstChild(); - else - currentAST.child = expressionList_AST; - currentAST.advanceChildToEnd(); - } - expressionList_AST = currentAST.root; - returnAST = expressionList_AST; - } - - public void modifier() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST expressionList_AST = null; + AST s_AST = null; + AST e_AST = null; + + expression(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + match(COMMA); + expression(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop142_breakloop; + } + + } +_loop142_breakloop: ; + } // ( ... )* + if (0==inputState.guessing) + { + expressionList_AST = (AST)currentAST.root; + expressionList_AST = (AST) astFactory.make(astFactory.create(ELIST,"ELIST"), expressionList_AST); + setRegionInfo(expressionList_AST,s_AST,e_AST); + currentAST.root = expressionList_AST; + if ( (null != expressionList_AST) && (null != expressionList_AST.getFirstChild()) ) + currentAST.child = expressionList_AST.getFirstChild(); + else + currentAST.child = expressionList_AST; + currentAST.advanceChildToEnd(); + } + expressionList_AST = currentAST.root; + returnAST = expressionList_AST; + } + + public void modifier() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST modifier_AST = null; - - switch ( LA(1) ) - { - case LITERAL_public: - { - AST tmp68_AST = null; - tmp68_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp68_AST); - match(LITERAL_public); - modifier_AST = currentAST.root; - break; - } - case LITERAL_private: - { - AST tmp69_AST = null; - tmp69_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp69_AST); - match(LITERAL_private); - modifier_AST = currentAST.root; - break; - } - case LITERAL_protected: - { - AST tmp70_AST = null; - tmp70_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp70_AST); - match(LITERAL_protected); - modifier_AST = currentAST.root; - break; - } - case LITERAL_internal: - { - AST tmp71_AST = null; - tmp71_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp71_AST); - match(LITERAL_internal); - modifier_AST = currentAST.root; - break; - } - case LITERAL_static: - { - AST tmp72_AST = null; - tmp72_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp72_AST); - match(LITERAL_static); - modifier_AST = currentAST.root; - break; - } - case LITERAL_final: - { - AST tmp73_AST = null; - tmp73_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp73_AST); - match(LITERAL_final); - modifier_AST = currentAST.root; - break; - } - case LITERAL_enumerable: - { - AST tmp74_AST = null; - tmp74_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp74_AST); - match(LITERAL_enumerable); - modifier_AST = currentAST.root; - break; - } - case LITERAL_explicit: - { - AST tmp75_AST = null; - tmp75_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp75_AST); - match(LITERAL_explicit); - modifier_AST = currentAST.root; - break; - } - case LITERAL_override: - { - AST tmp76_AST = null; - tmp76_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp76_AST); - match(LITERAL_override); - modifier_AST = currentAST.root; - break; - } - case LITERAL_dynamic: - { - AST tmp77_AST = null; - tmp77_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp77_AST); - match(LITERAL_dynamic); - modifier_AST = currentAST.root; - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - returnAST = modifier_AST; - } - - public void arguments() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST modifier_AST = null; + + switch ( LA(1) ) + { + case LITERAL_public: + { + AST tmp68_AST = null; + tmp68_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp68_AST); + match(LITERAL_public); + modifier_AST = currentAST.root; + break; + } + case LITERAL_private: + { + AST tmp69_AST = null; + tmp69_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp69_AST); + match(LITERAL_private); + modifier_AST = currentAST.root; + break; + } + case LITERAL_protected: + { + AST tmp70_AST = null; + tmp70_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp70_AST); + match(LITERAL_protected); + modifier_AST = currentAST.root; + break; + } + case LITERAL_internal: + { + AST tmp71_AST = null; + tmp71_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp71_AST); + match(LITERAL_internal); + modifier_AST = currentAST.root; + break; + } + case LITERAL_static: + { + AST tmp72_AST = null; + tmp72_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp72_AST); + match(LITERAL_static); + modifier_AST = currentAST.root; + break; + } + case LITERAL_final: + { + AST tmp73_AST = null; + tmp73_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp73_AST); + match(LITERAL_final); + modifier_AST = currentAST.root; + break; + } + case LITERAL_enumerable: + { + AST tmp74_AST = null; + tmp74_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp74_AST); + match(LITERAL_enumerable); + modifier_AST = currentAST.root; + break; + } + case LITERAL_explicit: + { + AST tmp75_AST = null; + tmp75_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp75_AST); + match(LITERAL_explicit); + modifier_AST = currentAST.root; + break; + } + case LITERAL_override: + { + AST tmp76_AST = null; + tmp76_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp76_AST); + match(LITERAL_override); + modifier_AST = currentAST.root; + break; + } + case LITERAL_dynamic: + { + AST tmp77_AST = null; + tmp77_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp77_AST); + match(LITERAL_dynamic); + modifier_AST = currentAST.root; + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + returnAST = modifier_AST; + } + + public void arguments() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST arguments_AST = null; - - { - switch ( LA(1) ) - { - case LCURLY: - case LBRACK: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - expressionList(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case RPAREN: - { - if (0==inputState.guessing) - { - arguments_AST = (AST)currentAST.root; - arguments_AST = astFactory.create(ELIST,"ELIST"); - currentAST.root = arguments_AST; - if ( (null != arguments_AST) && (null != arguments_AST.getFirstChild()) ) - currentAST.child = arguments_AST.getFirstChild(); - else - currentAST.child = arguments_AST; - currentAST.advanceChildToEnd(); - } - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - arguments_AST = currentAST.root; - returnAST = arguments_AST; - } - - public void arrayLiteral() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST arguments_AST = null; + + { + switch ( LA(1) ) + { + case LCURLY: + case LBRACK: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + expressionList(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case RPAREN: + { + if (0==inputState.guessing) + { + arguments_AST = (AST)currentAST.root; + arguments_AST = astFactory.create(ELIST,"ELIST"); + currentAST.root = arguments_AST; + if ( (null != arguments_AST) && (null != arguments_AST.getFirstChild()) ) + currentAST.child = arguments_AST.getFirstChild(); + else + currentAST.child = arguments_AST; + currentAST.advanceChildToEnd(); + } + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + arguments_AST = currentAST.root; + returnAST = arguments_AST; + } + + public void arrayLiteral() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST arrayLiteral_AST = null; - - AST tmp78_AST = null; - tmp78_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp78_AST); - match(LBRACK); - { - switch ( LA(1) ) - { - case LCURLY: - case LBRACK: - case COMMA: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - elementList(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case RBRACK: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - AST tmp79_AST = null; - tmp79_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp79_AST); - match(RBRACK); - arrayLiteral_AST = currentAST.root; - returnAST = arrayLiteral_AST; - } - - public void elementList() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST arrayLiteral_AST = null; + + AST tmp78_AST = null; + tmp78_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp78_AST); + match(LBRACK); + { + switch ( LA(1) ) + { + case LCURLY: + case LBRACK: + case COMMA: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + elementList(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case RBRACK: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + AST tmp79_AST = null; + tmp79_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp79_AST); + match(RBRACK); + arrayLiteral_AST = currentAST.root; + returnAST = arrayLiteral_AST; + } + + public void elementList() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST elementList_AST = null; - - switch ( LA(1) ) - { - case COMMA: - { - AST tmp80_AST = null; - tmp80_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp80_AST); - match(COMMA); - elementList_AST = currentAST.root; - break; - } - case LCURLY: - case LBRACK: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case PLUS: - case MINUS: - case INC: - case DEC: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - nonemptyElementList(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - elementList_AST = currentAST.root; - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - returnAST = elementList_AST; - } - - public void nonemptyElementList() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST elementList_AST = null; + + switch ( LA(1) ) + { + case COMMA: + { + AST tmp80_AST = null; + tmp80_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp80_AST); + match(COMMA); + elementList_AST = currentAST.root; + break; + } + case LCURLY: + case LBRACK: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case PLUS: + case MINUS: + case INC: + case DEC: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + nonemptyElementList(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + elementList_AST = currentAST.root; + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + returnAST = elementList_AST; + } + + public void nonemptyElementList() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST nonemptyElementList_AST = null; - - assignmentExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - AST tmp81_AST = null; - tmp81_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp81_AST); - match(COMMA); - assignmentExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop129_breakloop; - } - - } -_loop129_breakloop: ; - } // ( ... )* - nonemptyElementList_AST = currentAST.root; - returnAST = nonemptyElementList_AST; - } - - public void element() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST nonemptyElementList_AST = null; + + assignmentExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + AST tmp81_AST = null; + tmp81_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp81_AST); + match(COMMA); + assignmentExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop129_breakloop; + } + + } +_loop129_breakloop: ; + } // ( ... )* + nonemptyElementList_AST = currentAST.root; + returnAST = nonemptyElementList_AST; + } + + public void element() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST element_AST = null; - AST s_AST = null; - - assignmentExpression(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - element_AST = (AST)currentAST.root; - element_AST = (AST) astFactory.make(astFactory.create(ELEMENT,"ELEMENT"), element_AST); - setRegionInfo(element_AST,s_AST,null); - currentAST.root = element_AST; - if ( (null != element_AST) && (null != element_AST.getFirstChild()) ) - currentAST.child = element_AST.getFirstChild(); - else - currentAST.child = element_AST; - currentAST.advanceChildToEnd(); - } - element_AST = currentAST.root; - returnAST = element_AST; - } - - public void objectLiteral() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST element_AST = null; + AST s_AST = null; + + assignmentExpression(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + element_AST = (AST)currentAST.root; + element_AST = (AST) astFactory.make(astFactory.create(ELEMENT,"ELEMENT"), element_AST); + setRegionInfo(element_AST,s_AST,null); + currentAST.root = element_AST; + if ( (null != element_AST) && (null != element_AST.getFirstChild()) ) + currentAST.child = element_AST.getFirstChild(); + else + currentAST.child = element_AST; + currentAST.advanceChildToEnd(); + } + element_AST = currentAST.root; + returnAST = element_AST; + } + + public void objectLiteral() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST objectLiteral_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LCURLY); - { - switch ( LA(1) ) - { - case IDENT: - case NUMBER: - { - fieldList(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case RCURLY: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - e = LT(1); - e_AST = astFactory.create(e); - match(RCURLY); - if (0==inputState.guessing) - { - objectLiteral_AST = (AST)currentAST.root; - objectLiteral_AST = (AST) astFactory.make(astFactory.create(OBJECT_LITERAL,"OBJECT_LITERAL"), objectLiteral_AST); - setRegionInfo(objectLiteral_AST,s_AST,e_AST); - currentAST.root = objectLiteral_AST; - if ( (null != objectLiteral_AST) && (null != objectLiteral_AST.getFirstChild()) ) - currentAST.child = objectLiteral_AST.getFirstChild(); - else - currentAST.child = objectLiteral_AST; - currentAST.advanceChildToEnd(); - } - objectLiteral_AST = currentAST.root; - returnAST = objectLiteral_AST; - } - - public void fieldList() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST objectLiteral_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LCURLY); + { + switch ( LA(1) ) + { + case IDENT: + case NUMBER: + { + fieldList(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case RCURLY: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + e = LT(1); + e_AST = astFactory.create(e); + match(RCURLY); + if (0==inputState.guessing) + { + objectLiteral_AST = (AST)currentAST.root; + objectLiteral_AST = (AST) astFactory.make(astFactory.create(OBJECT_LITERAL,"OBJECT_LITERAL"), objectLiteral_AST); + setRegionInfo(objectLiteral_AST,s_AST,e_AST); + currentAST.root = objectLiteral_AST; + if ( (null != objectLiteral_AST) && (null != objectLiteral_AST.getFirstChild()) ) + currentAST.child = objectLiteral_AST.getFirstChild(); + else + currentAST.child = objectLiteral_AST; + currentAST.advanceChildToEnd(); + } + objectLiteral_AST = currentAST.root; + returnAST = objectLiteral_AST; + } + + public void fieldList() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST fieldList_AST = null; - - literalField(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==COMMA)) - { - match(COMMA); - { - switch ( LA(1) ) - { - case IDENT: - case NUMBER: - { - literalField(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - case RCURLY: - case COMMA: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - } - else - { - goto _loop136_breakloop; - } - - } -_loop136_breakloop: ; - } // ( ... )* - fieldList_AST = currentAST.root; - returnAST = fieldList_AST; - } - - public void literalField() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST fieldList_AST = null; + + literalField(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==COMMA)) + { + match(COMMA); + { + switch ( LA(1) ) + { + case IDENT: + case NUMBER: + { + literalField(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + case RCURLY: + case COMMA: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + } + else + { + goto _loop136_breakloop; + } + + } +_loop136_breakloop: ; + } // ( ... )* + fieldList_AST = currentAST.root; + returnAST = fieldList_AST; + } + + public void literalField() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST literalField_AST = null; - AST s_AST = null; - AST e_AST = null; - - fieldName(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - match(COLON); - element(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - literalField_AST = (AST)currentAST.root; - literalField_AST = (AST) astFactory.make(astFactory.create(OBJECT_FIELD,"OBJECT_FIELD"), literalField_AST); - setRegionInfo(literalField_AST,s_AST,e_AST); - currentAST.root = literalField_AST; - if ( (null != literalField_AST) && (null != literalField_AST.getFirstChild()) ) - currentAST.child = literalField_AST.getFirstChild(); - else - currentAST.child = literalField_AST; - currentAST.advanceChildToEnd(); - } - literalField_AST = currentAST.root; - returnAST = literalField_AST; - } - - public void fieldName() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST literalField_AST = null; + AST s_AST = null; + AST e_AST = null; + + fieldName(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + match(COLON); + element(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + literalField_AST = (AST)currentAST.root; + literalField_AST = (AST) astFactory.make(astFactory.create(OBJECT_FIELD,"OBJECT_FIELD"), literalField_AST); + setRegionInfo(literalField_AST,s_AST,e_AST); + currentAST.root = literalField_AST; + if ( (null != literalField_AST) && (null != literalField_AST.getFirstChild()) ) + currentAST.child = literalField_AST.getFirstChild(); + else + currentAST.child = literalField_AST; + currentAST.advanceChildToEnd(); + } + literalField_AST = currentAST.root; + returnAST = literalField_AST; + } + + public void fieldName() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST fieldName_AST = null; - - switch ( LA(1) ) - { - case IDENT: - { - AST tmp84_AST = null; - tmp84_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp84_AST); - match(IDENT); - fieldName_AST = currentAST.root; - break; - } - case NUMBER: - { - AST tmp85_AST = null; - tmp85_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp85_AST); - match(NUMBER); - fieldName_AST = currentAST.root; - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - returnAST = fieldName_AST; - } - - public void conditionalExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST fieldName_AST = null; + + switch ( LA(1) ) + { + case IDENT: + { + AST tmp84_AST = null; + tmp84_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp84_AST); + match(IDENT); + fieldName_AST = currentAST.root; + break; + } + case NUMBER: + { + AST tmp85_AST = null; + tmp85_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp85_AST); + match(NUMBER); + fieldName_AST = currentAST.root; + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + returnAST = fieldName_AST; + } + + public void conditionalExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST conditionalExpression_AST = null; - AST s_AST = null; - AST e_AST = null; - - logicalOrExpression(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==QUESTION) && (tokenSet_3_.member(LA(2)))) - { - AST tmp86_AST = null; - tmp86_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp86_AST); - match(QUESTION); - conditionalSubExpression(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - conditionalExpression_AST = (AST)currentAST.root; - setRegionInfo(conditionalExpression_AST,s_AST,e_AST); - } - } - else - { - goto _loop151_breakloop; - } - - } -_loop151_breakloop: ; - } // ( ... )* - conditionalExpression_AST = currentAST.root; - returnAST = conditionalExpression_AST; - } - - public void logicalOrExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST conditionalExpression_AST = null; + AST s_AST = null; + AST e_AST = null; + + logicalOrExpression(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==QUESTION) && (tokenSet_3_.member(LA(2)))) + { + AST tmp86_AST = null; + tmp86_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp86_AST); + match(QUESTION); + conditionalSubExpression(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + conditionalExpression_AST = (AST)currentAST.root; + setRegionInfo(conditionalExpression_AST,s_AST,e_AST); + } + } + else + { + goto _loop151_breakloop; + } + + } +_loop151_breakloop: ; + } // ( ... )* + conditionalExpression_AST = currentAST.root; + returnAST = conditionalExpression_AST; + } + + public void logicalOrExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST logicalOrExpression_AST = null; - - logicalAndExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==LOR)) - { - AST tmp87_AST = null; - tmp87_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp87_AST); - match(LOR); - logicalAndExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop155_breakloop; - } - - } -_loop155_breakloop: ; - } // ( ... )* - logicalOrExpression_AST = currentAST.root; - returnAST = logicalOrExpression_AST; - } - - public void conditionalSubExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST logicalOrExpression_AST = null; + + logicalAndExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==LOR)) + { + AST tmp87_AST = null; + tmp87_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp87_AST); + match(LOR); + logicalAndExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop155_breakloop; + } + + } +_loop155_breakloop: ; + } // ( ... )* + logicalOrExpression_AST = currentAST.root; + returnAST = logicalOrExpression_AST; + } + + public void conditionalSubExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST conditionalSubExpression_AST = null; - AST s_AST = null; - AST e_AST = null; - - assignmentExpression(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - AST tmp88_AST = null; - tmp88_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp88_AST); - match(COLON); - assignmentExpression(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - conditionalSubExpression_AST = (AST)currentAST.root; - setRegionInfo(conditionalSubExpression_AST,s_AST,e_AST); - } - conditionalSubExpression_AST = currentAST.root; - returnAST = conditionalSubExpression_AST; - } - - public void logicalAndExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST conditionalSubExpression_AST = null; + AST s_AST = null; + AST e_AST = null; + + assignmentExpression(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + AST tmp88_AST = null; + tmp88_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp88_AST); + match(COLON); + assignmentExpression(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + conditionalSubExpression_AST = (AST)currentAST.root; + setRegionInfo(conditionalSubExpression_AST,s_AST,e_AST); + } + conditionalSubExpression_AST = currentAST.root; + returnAST = conditionalSubExpression_AST; + } + + public void logicalAndExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST logicalAndExpression_AST = null; - - bitwiseOrExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==LAND)) - { - AST tmp89_AST = null; - tmp89_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp89_AST); - match(LAND); - bitwiseOrExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop158_breakloop; - } - - } -_loop158_breakloop: ; - } // ( ... )* - logicalAndExpression_AST = currentAST.root; - returnAST = logicalAndExpression_AST; - } - - public void bitwiseOrExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST logicalAndExpression_AST = null; + + bitwiseOrExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==LAND)) + { + AST tmp89_AST = null; + tmp89_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp89_AST); + match(LAND); + bitwiseOrExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop158_breakloop; + } + + } +_loop158_breakloop: ; + } // ( ... )* + logicalAndExpression_AST = currentAST.root; + returnAST = logicalAndExpression_AST; + } + + public void bitwiseOrExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST bitwiseOrExpression_AST = null; - - bitwiseXorExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==BOR)) - { - AST tmp90_AST = null; - tmp90_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp90_AST); - match(BOR); - bitwiseXorExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop161_breakloop; - } - - } -_loop161_breakloop: ; - } // ( ... )* - bitwiseOrExpression_AST = currentAST.root; - returnAST = bitwiseOrExpression_AST; - } - - public void bitwiseXorExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST bitwiseOrExpression_AST = null; + + bitwiseXorExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==BOR)) + { + AST tmp90_AST = null; + tmp90_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp90_AST); + match(BOR); + bitwiseXorExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop161_breakloop; + } + + } +_loop161_breakloop: ; + } // ( ... )* + bitwiseOrExpression_AST = currentAST.root; + returnAST = bitwiseOrExpression_AST; + } + + public void bitwiseXorExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST bitwiseXorExpression_AST = null; - - bitwiseAndExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==BXOR)) - { - AST tmp91_AST = null; - tmp91_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp91_AST); - match(BXOR); - bitwiseAndExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop164_breakloop; - } - - } -_loop164_breakloop: ; - } // ( ... )* - bitwiseXorExpression_AST = currentAST.root; - returnAST = bitwiseXorExpression_AST; - } - - public void bitwiseAndExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST bitwiseXorExpression_AST = null; + + bitwiseAndExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==BXOR)) + { + AST tmp91_AST = null; + tmp91_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp91_AST); + match(BXOR); + bitwiseAndExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop164_breakloop; + } + + } +_loop164_breakloop: ; + } // ( ... )* + bitwiseXorExpression_AST = currentAST.root; + returnAST = bitwiseXorExpression_AST; + } + + public void bitwiseAndExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST bitwiseAndExpression_AST = null; - - equalityExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==BAND)) - { - AST tmp92_AST = null; - tmp92_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp92_AST); - match(BAND); - equalityExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop167_breakloop; - } - - } -_loop167_breakloop: ; - } // ( ... )* - bitwiseAndExpression_AST = currentAST.root; - returnAST = bitwiseAndExpression_AST; - } - - public void equalityExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST bitwiseAndExpression_AST = null; + + equalityExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==BAND)) + { + AST tmp92_AST = null; + tmp92_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp92_AST); + match(BAND); + equalityExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop167_breakloop; + } + + } +_loop167_breakloop: ; + } // ( ... )* + bitwiseAndExpression_AST = currentAST.root; + returnAST = bitwiseAndExpression_AST; + } + + public void equalityExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST equalityExpression_AST = null; - - relationalExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if (((LA(1) >= STRICT_EQUAL && LA(1) <= EQUAL))) - { - { - switch ( LA(1) ) - { - case STRICT_EQUAL: - { - AST tmp93_AST = null; - tmp93_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp93_AST); - match(STRICT_EQUAL); - break; - } - case STRICT_NOT_EQUAL: - { - AST tmp94_AST = null; - tmp94_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp94_AST); - match(STRICT_NOT_EQUAL); - break; - } - case NOT_EQUAL: - { - AST tmp95_AST = null; - tmp95_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp95_AST); - match(NOT_EQUAL); - break; - } - case EQUAL: - { - AST tmp96_AST = null; - tmp96_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp96_AST); - match(EQUAL); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - relationalExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop171_breakloop; - } - - } -_loop171_breakloop: ; - } // ( ... )* - equalityExpression_AST = currentAST.root; - returnAST = equalityExpression_AST; - } - - public void relationalExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST equalityExpression_AST = null; + + relationalExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if (((LA(1) >= STRICT_EQUAL && LA(1) <= EQUAL))) + { + { + switch ( LA(1) ) + { + case STRICT_EQUAL: + { + AST tmp93_AST = null; + tmp93_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp93_AST); + match(STRICT_EQUAL); + break; + } + case STRICT_NOT_EQUAL: + { + AST tmp94_AST = null; + tmp94_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp94_AST); + match(STRICT_NOT_EQUAL); + break; + } + case NOT_EQUAL: + { + AST tmp95_AST = null; + tmp95_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp95_AST); + match(NOT_EQUAL); + break; + } + case EQUAL: + { + AST tmp96_AST = null; + tmp96_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp96_AST); + match(EQUAL); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + relationalExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop171_breakloop; + } + + } +_loop171_breakloop: ; + } // ( ... )* + equalityExpression_AST = currentAST.root; + returnAST = equalityExpression_AST; + } + + public void relationalExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST relationalExpression_AST = null; - - shiftExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if (((LA(1) >= LWT && LA(1) <= LITERAL_as))) - { - { - switch ( LA(1) ) - { - case LWT: - { - AST tmp97_AST = null; - tmp97_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp97_AST); - match(LWT); - break; - } - case GT: - { - AST tmp98_AST = null; - tmp98_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp98_AST); - match(GT); - break; - } - case LE: - { - AST tmp99_AST = null; - tmp99_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp99_AST); - match(LE); - break; - } - case GE: - { - AST tmp100_AST = null; - tmp100_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp100_AST); - match(GE); - break; - } - case LITERAL_is: - { - AST tmp101_AST = null; - tmp101_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp101_AST); - match(LITERAL_is); - break; - } - case LITERAL_as: - { - AST tmp102_AST = null; - tmp102_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp102_AST); - match(LITERAL_as); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - shiftExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop175_breakloop; - } - - } -_loop175_breakloop: ; - } // ( ... )* - relationalExpression_AST = currentAST.root; - returnAST = relationalExpression_AST; - } - - public void shiftExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST relationalExpression_AST = null; + + shiftExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if (((LA(1) >= LWT && LA(1) <= LITERAL_as))) + { + { + switch ( LA(1) ) + { + case LWT: + { + AST tmp97_AST = null; + tmp97_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp97_AST); + match(LWT); + break; + } + case GT: + { + AST tmp98_AST = null; + tmp98_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp98_AST); + match(GT); + break; + } + case LE: + { + AST tmp99_AST = null; + tmp99_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp99_AST); + match(LE); + break; + } + case GE: + { + AST tmp100_AST = null; + tmp100_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp100_AST); + match(GE); + break; + } + case LITERAL_is: + { + AST tmp101_AST = null; + tmp101_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp101_AST); + match(LITERAL_is); + break; + } + case LITERAL_as: + { + AST tmp102_AST = null; + tmp102_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp102_AST); + match(LITERAL_as); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + shiftExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop175_breakloop; + } + + } +_loop175_breakloop: ; + } // ( ... )* + relationalExpression_AST = currentAST.root; + returnAST = relationalExpression_AST; + } + + public void shiftExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST shiftExpression_AST = null; - - additiveExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if (((LA(1) >= SL && LA(1) <= BSR))) - { - { - switch ( LA(1) ) - { - case SL: - { - AST tmp103_AST = null; - tmp103_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp103_AST); - match(SL); - break; - } - case SR: - { - AST tmp104_AST = null; - tmp104_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp104_AST); - match(SR); - break; - } - case BSR: - { - AST tmp105_AST = null; - tmp105_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp105_AST); - match(BSR); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - additiveExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop179_breakloop; - } - - } -_loop179_breakloop: ; - } // ( ... )* - shiftExpression_AST = currentAST.root; - returnAST = shiftExpression_AST; - } - - public void additiveExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST shiftExpression_AST = null; + + additiveExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if (((LA(1) >= SL && LA(1) <= BSR))) + { + { + switch ( LA(1) ) + { + case SL: + { + AST tmp103_AST = null; + tmp103_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp103_AST); + match(SL); + break; + } + case SR: + { + AST tmp104_AST = null; + tmp104_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp104_AST); + match(SR); + break; + } + case BSR: + { + AST tmp105_AST = null; + tmp105_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp105_AST); + match(BSR); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + additiveExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop179_breakloop; + } + + } +_loop179_breakloop: ; + } // ( ... )* + shiftExpression_AST = currentAST.root; + returnAST = shiftExpression_AST; + } + + public void additiveExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST additiveExpression_AST = null; - - multiplicativeExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==PLUS||LA(1)==MINUS) && (tokenSet_3_.member(LA(2)))) - { - { - switch ( LA(1) ) - { - case PLUS: - { - AST tmp106_AST = null; - tmp106_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp106_AST); - match(PLUS); - break; - } - case MINUS: - { - AST tmp107_AST = null; - tmp107_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp107_AST); - match(MINUS); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - multiplicativeExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop183_breakloop; - } - - } -_loop183_breakloop: ; - } // ( ... )* - additiveExpression_AST = currentAST.root; - returnAST = additiveExpression_AST; - } - - public void multiplicativeExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST additiveExpression_AST = null; + + multiplicativeExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==PLUS||LA(1)==MINUS) && (tokenSet_3_.member(LA(2)))) + { + { + switch ( LA(1) ) + { + case PLUS: + { + AST tmp106_AST = null; + tmp106_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp106_AST); + match(PLUS); + break; + } + case MINUS: + { + AST tmp107_AST = null; + tmp107_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp107_AST); + match(MINUS); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + multiplicativeExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop183_breakloop; + } + + } +_loop183_breakloop: ; + } // ( ... )* + additiveExpression_AST = currentAST.root; + returnAST = additiveExpression_AST; + } + + public void multiplicativeExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST multiplicativeExpression_AST = null; - - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==STAR||LA(1)==DIV||LA(1)==MOD)) - { - { - switch ( LA(1) ) - { - case STAR: - { - AST tmp108_AST = null; - tmp108_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp108_AST); - match(STAR); - break; - } - case DIV: - { - AST tmp109_AST = null; - tmp109_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp109_AST); - match(DIV); - break; - } - case MOD: - { - AST tmp110_AST = null; - tmp110_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp110_AST); - match(MOD); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - } - else - { - goto _loop187_breakloop; - } - - } -_loop187_breakloop: ; - } // ( ... )* - multiplicativeExpression_AST = currentAST.root; - returnAST = multiplicativeExpression_AST; - } - - public void unaryExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST multiplicativeExpression_AST = null; + + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==STAR||LA(1)==DIV||LA(1)==MOD)) + { + { + switch ( LA(1) ) + { + case STAR: + { + AST tmp108_AST = null; + tmp108_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp108_AST); + match(STAR); + break; + } + case DIV: + { + AST tmp109_AST = null; + tmp109_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp109_AST); + match(DIV); + break; + } + case MOD: + { + AST tmp110_AST = null; + tmp110_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp110_AST); + match(MOD); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + } + else + { + goto _loop187_breakloop; + } + + } +_loop187_breakloop: ; + } // ( ... )* + multiplicativeExpression_AST = currentAST.root; + returnAST = multiplicativeExpression_AST; + } + + public void unaryExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST unaryExpression_AST = null; - - switch ( LA(1) ) - { - case INC: - { - AST tmp111_AST = null; - tmp111_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp111_AST); - match(INC); - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpression_AST = currentAST.root; - break; - } - case DEC: - { - AST tmp112_AST = null; - tmp112_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp112_AST); - match(DEC); - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpression_AST = currentAST.root; - break; - } - case MINUS: - { - AST tmp113_AST = null; - tmp113_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp113_AST); - match(MINUS); - if (0==inputState.guessing) - { - tmp113_AST.setType(UNARY_MINUS); - } - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpression_AST = currentAST.root; - break; - } - case PLUS: - { - AST tmp114_AST = null; - tmp114_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp114_AST); - match(PLUS); - if (0==inputState.guessing) - { - tmp114_AST.setType(UNARY_PLUS); - } - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpression_AST = currentAST.root; - break; - } - case LCURLY: - case LBRACK: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case LITERAL_delete: - case LITERAL_typeof: - case LNOT: - case BNOT: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - unaryExpressionNotPlusMinus(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpression_AST = currentAST.root; - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - returnAST = unaryExpression_AST; - } - - public void unaryExpressionNotPlusMinus() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST unaryExpression_AST = null; + + switch ( LA(1) ) + { + case INC: + { + AST tmp111_AST = null; + tmp111_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp111_AST); + match(INC); + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpression_AST = currentAST.root; + break; + } + case DEC: + { + AST tmp112_AST = null; + tmp112_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp112_AST); + match(DEC); + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpression_AST = currentAST.root; + break; + } + case MINUS: + { + AST tmp113_AST = null; + tmp113_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp113_AST); + match(MINUS); + if (0==inputState.guessing) + { + tmp113_AST.setType(UNARY_MINUS); + } + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpression_AST = currentAST.root; + break; + } + case PLUS: + { + AST tmp114_AST = null; + tmp114_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp114_AST); + match(PLUS); + if (0==inputState.guessing) + { + tmp114_AST.setType(UNARY_PLUS); + } + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpression_AST = currentAST.root; + break; + } + case LCURLY: + case LBRACK: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case LITERAL_delete: + case LITERAL_typeof: + case LNOT: + case BNOT: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + unaryExpressionNotPlusMinus(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpression_AST = currentAST.root; + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + returnAST = unaryExpression_AST; + } + + public void unaryExpressionNotPlusMinus() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST unaryExpressionNotPlusMinus_AST = null; - - switch ( LA(1) ) - { - case LITERAL_delete: - { - AST tmp115_AST = null; - tmp115_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp115_AST); - match(LITERAL_delete); - postfixExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpressionNotPlusMinus_AST = currentAST.root; - break; - } - case LITERAL_typeof: - { - AST tmp116_AST = null; - tmp116_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp116_AST); - match(LITERAL_typeof); - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpressionNotPlusMinus_AST = currentAST.root; - break; - } - case LNOT: - { - AST tmp117_AST = null; - tmp117_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp117_AST); - match(LNOT); - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpressionNotPlusMinus_AST = currentAST.root; - break; - } - case BNOT: - { - AST tmp118_AST = null; - tmp118_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp118_AST); - match(BNOT); - unaryExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpressionNotPlusMinus_AST = currentAST.root; - break; - } - case LCURLY: - case LBRACK: - case LPAREN: - case LITERAL_function: - case IDENT: - case NUMBER: - case LITERAL_null: - case LITERAL_true: - case LITERAL_false: - case LITERAL_undefined: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - case LITERAL_new: - { - postfixExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - unaryExpressionNotPlusMinus_AST = currentAST.root; - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - returnAST = unaryExpressionNotPlusMinus_AST; - } - - public void postfixExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST unaryExpressionNotPlusMinus_AST = null; + + switch ( LA(1) ) + { + case LITERAL_delete: + { + AST tmp115_AST = null; + tmp115_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp115_AST); + match(LITERAL_delete); + postfixExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpressionNotPlusMinus_AST = currentAST.root; + break; + } + case LITERAL_typeof: + { + AST tmp116_AST = null; + tmp116_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp116_AST); + match(LITERAL_typeof); + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpressionNotPlusMinus_AST = currentAST.root; + break; + } + case LNOT: + { + AST tmp117_AST = null; + tmp117_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp117_AST); + match(LNOT); + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpressionNotPlusMinus_AST = currentAST.root; + break; + } + case BNOT: + { + AST tmp118_AST = null; + tmp118_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp118_AST); + match(BNOT); + unaryExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpressionNotPlusMinus_AST = currentAST.root; + break; + } + case LCURLY: + case LBRACK: + case LPAREN: + case LITERAL_function: + case IDENT: + case NUMBER: + case LITERAL_null: + case LITERAL_true: + case LITERAL_false: + case LITERAL_undefined: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + case LITERAL_new: + { + postfixExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + unaryExpressionNotPlusMinus_AST = currentAST.root; + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + returnAST = unaryExpressionNotPlusMinus_AST; + } + + public void postfixExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST postfixExpression_AST = null; - AST s_AST = null; - IToken e11 = null; - AST e11_AST = null; - AST e12_AST = null; - IToken t1 = null; - AST t1_AST = null; - IToken e2 = null; - AST e2_AST = null; - IToken t2 = null; - AST t2_AST = null; - IToken e3 = null; - AST e3_AST = null; - IToken t3 = null; - AST t3_AST = null; - IToken e4 = null; - AST e4_AST = null; - IToken oin = null; - AST oin_AST = null; - IToken ode = null; - AST ode_AST = null; - - primaryExpression(); - if (0 == inputState.guessing) - { - s_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==LBRACK||LA(1)==DOT||LA(1)==E4X_DESC) && (tokenSet_11_.member(LA(2)))) - { - { - switch ( LA(1) ) - { - case DOT: - { - match(DOT); - { - if ((LA(1)==IDENT) && (tokenSet_12_.member(LA(2)))) - { - e11 = LT(1); - e11_AST = astFactory.create(e11); - astFactory.makeASTRoot(ref currentAST, e11_AST); - match(IDENT); - if (0==inputState.guessing) - { - setRegionInfo(e11_AST,s_AST,e11_AST); - } - } - else if ((LA(1)==IDENT||LA(1)==STAR||LA(1)==E4X_ATTRI) && (tokenSet_12_.member(LA(2)))) { - e4xExpression(); - if (0 == inputState.guessing) - { - e12_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - setRegionInfo(e12_AST,s_AST,e12_AST); - } - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - break; - } - case LBRACK: - { - { - t1 = LT(1); - t1_AST = astFactory.create(t1); - astFactory.makeASTRoot(ref currentAST, t1_AST); - match(LBRACK); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e2 = LT(1); - e2_AST = astFactory.create(e2); - match(RBRACK); - if (0==inputState.guessing) - { - t1_AST.setType(ARRAY_ACC); - t1_AST.setText("ARRAY_ACC"); - setRegionInfo(t1_AST,s_AST,e2_AST); - } - } - break; - } - case E4X_DESC: - { - AST tmp120_AST = null; - tmp120_AST = astFactory.create(LT(1)); - astFactory.makeASTRoot(ref currentAST, tmp120_AST); - match(E4X_DESC); - e4xExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - { - if ((LA(1)==LPAREN) && (tokenSet_13_.member(LA(2)))) - { - t2 = LT(1); - t2_AST = astFactory.create(t2); - astFactory.makeASTRoot(ref currentAST, t2_AST); - match(LPAREN); - arguments(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e3 = LT(1); - e3_AST = astFactory.create(e3); - match(RPAREN); - if (0==inputState.guessing) - { - t2_AST.setType(METHOD_CALL); - t2_AST.setText("METHOD_CALL"); - setRegionInfo(t2_AST,s_AST,e3_AST); - } - { // ( ... )* - for (;;) - { - if ((LA(1)==LPAREN) && (tokenSet_13_.member(LA(2)))) - { - t3 = LT(1); - t3_AST = astFactory.create(t3); - astFactory.makeASTRoot(ref currentAST, t3_AST); - match(LPAREN); - arguments(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e4 = LT(1); - e4_AST = astFactory.create(e4); - match(RPAREN); - if (0==inputState.guessing) - { - t3_AST.setType(METHOD_CALL); - t3_AST.setText("METHOD_CALL"); - setRegionInfo(t3_AST,s_AST,e4_AST); - } - } - else - { - goto _loop197_breakloop; - } - - } -_loop197_breakloop: ; - } // ( ... )* - } - else if ((tokenSet_12_.member(LA(1))) && (tokenSet_14_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - } - else - { - goto _loop198_breakloop; - } - - } -_loop198_breakloop: ; - } // ( ... )* - { - if ((LA(1)==INC) && (tokenSet_12_.member(LA(2)))) - { - oin = LT(1); - oin_AST = astFactory.create(oin); - astFactory.makeASTRoot(ref currentAST, oin_AST); - match(INC); - if (0==inputState.guessing) - { - oin_AST.setType(POST_INC); - } - } - else if ((LA(1)==DEC) && (tokenSet_12_.member(LA(2)))) { - ode = LT(1); - ode_AST = astFactory.create(ode); - astFactory.makeASTRoot(ref currentAST, ode_AST); - match(DEC); - if (0==inputState.guessing) - { - ode_AST.setType(POST_DEC); - } - } - else if ((tokenSet_12_.member(LA(1))) && (tokenSet_14_.member(LA(2)))) { - } - else - { - throw new NoViableAltException(LT(1), getFilename()); - } - - } - postfixExpression_AST = currentAST.root; - returnAST = postfixExpression_AST; - } - - public void primaryExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST postfixExpression_AST = null; + AST s_AST = null; + IToken e11 = null; + AST e11_AST = null; + AST e12_AST = null; + IToken t1 = null; + AST t1_AST = null; + IToken e2 = null; + AST e2_AST = null; + IToken t2 = null; + AST t2_AST = null; + IToken e3 = null; + AST e3_AST = null; + IToken t3 = null; + AST t3_AST = null; + IToken e4 = null; + AST e4_AST = null; + IToken oin = null; + AST oin_AST = null; + IToken ode = null; + AST ode_AST = null; + + primaryExpression(); + if (0 == inputState.guessing) + { + s_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==LBRACK||LA(1)==DOT||LA(1)==E4X_DESC) && (tokenSet_11_.member(LA(2)))) + { + { + switch ( LA(1) ) + { + case DOT: + { + match(DOT); + { + if ((LA(1)==IDENT) && (tokenSet_12_.member(LA(2)))) + { + e11 = LT(1); + e11_AST = astFactory.create(e11); + astFactory.makeASTRoot(ref currentAST, e11_AST); + match(IDENT); + if (0==inputState.guessing) + { + setRegionInfo(e11_AST,s_AST,e11_AST); + } + } + else if ((LA(1)==IDENT||LA(1)==STAR||LA(1)==E4X_ATTRI) && (tokenSet_12_.member(LA(2)))) { + e4xExpression(); + if (0 == inputState.guessing) + { + e12_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + setRegionInfo(e12_AST,s_AST,e12_AST); + } + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + break; + } + case LBRACK: + { + { + t1 = LT(1); + t1_AST = astFactory.create(t1); + astFactory.makeASTRoot(ref currentAST, t1_AST); + match(LBRACK); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e2 = LT(1); + e2_AST = astFactory.create(e2); + match(RBRACK); + if (0==inputState.guessing) + { + t1_AST.setType(ARRAY_ACC); + t1_AST.setText("ARRAY_ACC"); + setRegionInfo(t1_AST,s_AST,e2_AST); + } + } + break; + } + case E4X_DESC: + { + AST tmp120_AST = null; + tmp120_AST = astFactory.create(LT(1)); + astFactory.makeASTRoot(ref currentAST, tmp120_AST); + match(E4X_DESC); + e4xExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + { + if ((LA(1)==LPAREN) && (tokenSet_13_.member(LA(2)))) + { + t2 = LT(1); + t2_AST = astFactory.create(t2); + astFactory.makeASTRoot(ref currentAST, t2_AST); + match(LPAREN); + arguments(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e3 = LT(1); + e3_AST = astFactory.create(e3); + match(RPAREN); + if (0==inputState.guessing) + { + t2_AST.setType(METHOD_CALL); + t2_AST.setText("METHOD_CALL"); + setRegionInfo(t2_AST,s_AST,e3_AST); + } + { // ( ... )* + for (;;) + { + if ((LA(1)==LPAREN) && (tokenSet_13_.member(LA(2)))) + { + t3 = LT(1); + t3_AST = astFactory.create(t3); + astFactory.makeASTRoot(ref currentAST, t3_AST); + match(LPAREN); + arguments(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e4 = LT(1); + e4_AST = astFactory.create(e4); + match(RPAREN); + if (0==inputState.guessing) + { + t3_AST.setType(METHOD_CALL); + t3_AST.setText("METHOD_CALL"); + setRegionInfo(t3_AST,s_AST,e4_AST); + } + } + else + { + goto _loop197_breakloop; + } + + } +_loop197_breakloop: ; + } // ( ... )* + } + else if ((tokenSet_12_.member(LA(1))) && (tokenSet_14_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + } + else + { + goto _loop198_breakloop; + } + + } +_loop198_breakloop: ; + } // ( ... )* + { + if ((LA(1)==INC) && (tokenSet_12_.member(LA(2)))) + { + oin = LT(1); + oin_AST = astFactory.create(oin); + astFactory.makeASTRoot(ref currentAST, oin_AST); + match(INC); + if (0==inputState.guessing) + { + oin_AST.setType(POST_INC); + } + } + else if ((LA(1)==DEC) && (tokenSet_12_.member(LA(2)))) { + ode = LT(1); + ode_AST = astFactory.create(ode); + astFactory.makeASTRoot(ref currentAST, ode_AST); + match(DEC); + if (0==inputState.guessing) + { + ode_AST.setType(POST_DEC); + } + } + else if ((tokenSet_12_.member(LA(1))) && (tokenSet_14_.member(LA(2)))) { + } + else + { + throw new NoViableAltException(LT(1), getFilename()); + } + + } + postfixExpression_AST = currentAST.root; + returnAST = postfixExpression_AST; + } + + public void primaryExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST primaryExpression_AST = null; - - switch ( LA(1) ) - { - case IDENT: - { - identPrimary(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - primaryExpression_AST = currentAST.root; - break; - } - case LITERAL_null: - { - AST tmp121_AST = null; - tmp121_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp121_AST); - match(LITERAL_null); - primaryExpression_AST = currentAST.root; - break; - } - case LITERAL_true: - { - AST tmp122_AST = null; - tmp122_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp122_AST); - match(LITERAL_true); - primaryExpression_AST = currentAST.root; - break; - } - case LITERAL_false: - { - AST tmp123_AST = null; - tmp123_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp123_AST); - match(LITERAL_false); - primaryExpression_AST = currentAST.root; - break; - } - case LITERAL_undefined: - { - AST tmp124_AST = null; - tmp124_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp124_AST); - match(LITERAL_undefined); - primaryExpression_AST = currentAST.root; - break; - } - case NUMBER: - case STRING_LITERAL: - case REGEX_LITERAL: - case XML_LITERAL: - { - constant(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - primaryExpression_AST = currentAST.root; - break; - } - case LBRACK: - { - arrayLiteral(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - primaryExpression_AST = currentAST.root; - break; - } - case LCURLY: - { - objectLiteral(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - primaryExpression_AST = currentAST.root; - break; - } - case LITERAL_function: - { - functionDefinition(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - primaryExpression_AST = currentAST.root; - break; - } - case LITERAL_new: - { - newExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - primaryExpression_AST = currentAST.root; - break; - } - case LPAREN: - { - encapsulatedExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - primaryExpression_AST = currentAST.root; - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - returnAST = primaryExpression_AST; - } - - public void e4xExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST primaryExpression_AST = null; + + switch ( LA(1) ) + { + case IDENT: + { + identPrimary(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + primaryExpression_AST = currentAST.root; + break; + } + case LITERAL_null: + { + AST tmp121_AST = null; + tmp121_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp121_AST); + match(LITERAL_null); + primaryExpression_AST = currentAST.root; + break; + } + case LITERAL_true: + { + AST tmp122_AST = null; + tmp122_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp122_AST); + match(LITERAL_true); + primaryExpression_AST = currentAST.root; + break; + } + case LITERAL_false: + { + AST tmp123_AST = null; + tmp123_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp123_AST); + match(LITERAL_false); + primaryExpression_AST = currentAST.root; + break; + } + case LITERAL_undefined: + { + AST tmp124_AST = null; + tmp124_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp124_AST); + match(LITERAL_undefined); + primaryExpression_AST = currentAST.root; + break; + } + case NUMBER: + case STRING_LITERAL: + case REGEX_LITERAL: + case XML_LITERAL: + { + constant(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + primaryExpression_AST = currentAST.root; + break; + } + case LBRACK: + { + arrayLiteral(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + primaryExpression_AST = currentAST.root; + break; + } + case LCURLY: + { + objectLiteral(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + primaryExpression_AST = currentAST.root; + break; + } + case LITERAL_function: + { + functionDefinition(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + primaryExpression_AST = currentAST.root; + break; + } + case LITERAL_new: + { + newExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + primaryExpression_AST = currentAST.root; + break; + } + case LPAREN: + { + encapsulatedExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + primaryExpression_AST = currentAST.root; + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + returnAST = primaryExpression_AST; + } + + public void e4xExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST e4xExpression_AST = null; - IToken e12 = null; - AST e12_AST = null; - IToken e13 = null; - AST e13_AST = null; - IToken t1 = null; - AST t1_AST = null; - IToken e2 = null; - AST e2_AST = null; - - switch ( LA(1) ) - { - case IDENT: - { - AST tmp125_AST = null; - tmp125_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp125_AST); - match(IDENT); - e4xExpression_AST = currentAST.root; - break; - } - case STAR: - { - e12 = LT(1); - e12_AST = astFactory.create(e12); - astFactory.makeASTRoot(ref currentAST, e12_AST); - match(STAR); - e4xExpression_AST = currentAST.root; - break; - } - case E4X_ATTRI: - { - e13 = LT(1); - e13_AST = astFactory.create(e13); - astFactory.makeASTRoot(ref currentAST, e13_AST); - match(E4X_ATTRI); - { - switch ( LA(1) ) - { - case IDENT: - { - AST tmp126_AST = null; - tmp126_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp126_AST); - match(IDENT); - break; - } - case LBRACK: - case STAR: - { - { - switch ( LA(1) ) - { - case STAR: - { - AST tmp127_AST = null; - tmp127_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp127_AST); - match(STAR); - break; - } - case LBRACK: - { - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - t1 = LT(1); - t1_AST = astFactory.create(t1); - astFactory.makeASTRoot(ref currentAST, t1_AST); - match(LBRACK); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e2 = LT(1); - e2_AST = astFactory.create(e2); - match(RBRACK); - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - } - e4xExpression_AST = currentAST.root; - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - returnAST = e4xExpression_AST; - } - - public void identPrimary() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST e4xExpression_AST = null; + IToken e12 = null; + AST e12_AST = null; + IToken e13 = null; + AST e13_AST = null; + IToken t1 = null; + AST t1_AST = null; + IToken e2 = null; + AST e2_AST = null; + + switch ( LA(1) ) + { + case IDENT: + { + AST tmp125_AST = null; + tmp125_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp125_AST); + match(IDENT); + e4xExpression_AST = currentAST.root; + break; + } + case STAR: + { + e12 = LT(1); + e12_AST = astFactory.create(e12); + astFactory.makeASTRoot(ref currentAST, e12_AST); + match(STAR); + e4xExpression_AST = currentAST.root; + break; + } + case E4X_ATTRI: + { + e13 = LT(1); + e13_AST = astFactory.create(e13); + astFactory.makeASTRoot(ref currentAST, e13_AST); + match(E4X_ATTRI); + { + switch ( LA(1) ) + { + case IDENT: + { + AST tmp126_AST = null; + tmp126_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp126_AST); + match(IDENT); + break; + } + case LBRACK: + case STAR: + { + { + switch ( LA(1) ) + { + case STAR: + { + AST tmp127_AST = null; + tmp127_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp127_AST); + match(STAR); + break; + } + case LBRACK: + { + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + t1 = LT(1); + t1_AST = astFactory.create(t1); + astFactory.makeASTRoot(ref currentAST, t1_AST); + match(LBRACK); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e2 = LT(1); + e2_AST = astFactory.create(e2); + match(RBRACK); + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + } + e4xExpression_AST = currentAST.root; + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + returnAST = e4xExpression_AST; + } + + public void identPrimary() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST identPrimary_AST = null; - IToken s = null; - AST s_AST = null; - IToken e1 = null; - AST e1_AST = null; - IToken t1 = null; - AST t1_AST = null; - IToken e2 = null; - AST e2_AST = null; - IToken t2 = null; - AST t2_AST = null; - IToken e3 = null; - AST e3_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.addASTChild(ref currentAST, s_AST); - match(IDENT); - { // ( ... )* - for (;;) - { - if ((LA(1)==DOT) && (LA(2)==IDENT)) - { - match(DOT); - e1 = LT(1); - e1_AST = astFactory.create(e1); - astFactory.makeASTRoot(ref currentAST, e1_AST); - match(IDENT); - if (0==inputState.guessing) - { - setRegionInfo(e1_AST,s_AST,e1_AST); - } - } - else if ((LA(1)==LBRACK) && (tokenSet_3_.member(LA(2)))) { - { - t1 = LT(1); - t1_AST = astFactory.create(t1); - astFactory.makeASTRoot(ref currentAST, t1_AST); - match(LBRACK); - expression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e2 = LT(1); - e2_AST = astFactory.create(e2); - match(RBRACK); - if (0==inputState.guessing) - { - t1_AST.setType(ARRAY_ACC); - t1_AST.setText("ARRAY_ACC"); - setRegionInfo(t1_AST,s_AST,e2_AST); - } - } - } - else - { - goto _loop207_breakloop; - } - - } -_loop207_breakloop: ; - } // ( ... )* - { // ( ... )* - for (;;) - { - if ((LA(1)==LPAREN) && (tokenSet_13_.member(LA(2)))) - { - t2 = LT(1); - t2_AST = astFactory.create(t2); - astFactory.makeASTRoot(ref currentAST, t2_AST); - match(LPAREN); - arguments(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e3 = LT(1); - e3_AST = astFactory.create(e3); - match(RPAREN); - if (0==inputState.guessing) - { - t2_AST.setType(METHOD_CALL); - t2_AST.setText("METHOD_CALL"); - setRegionInfo(t2_AST,s_AST,e3_AST); - } - } - else - { - goto _loop209_breakloop; - } - - } -_loop209_breakloop: ; - } // ( ... )* - identPrimary_AST = currentAST.root; - returnAST = identPrimary_AST; - } - - public void constant() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST identPrimary_AST = null; + IToken s = null; + AST s_AST = null; + IToken e1 = null; + AST e1_AST = null; + IToken t1 = null; + AST t1_AST = null; + IToken e2 = null; + AST e2_AST = null; + IToken t2 = null; + AST t2_AST = null; + IToken e3 = null; + AST e3_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.addASTChild(ref currentAST, s_AST); + match(IDENT); + { // ( ... )* + for (;;) + { + if ((LA(1)==DOT) && (LA(2)==IDENT)) + { + match(DOT); + e1 = LT(1); + e1_AST = astFactory.create(e1); + astFactory.makeASTRoot(ref currentAST, e1_AST); + match(IDENT); + if (0==inputState.guessing) + { + setRegionInfo(e1_AST,s_AST,e1_AST); + } + } + else if ((LA(1)==LBRACK) && (tokenSet_3_.member(LA(2)))) { + { + t1 = LT(1); + t1_AST = astFactory.create(t1); + astFactory.makeASTRoot(ref currentAST, t1_AST); + match(LBRACK); + expression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e2 = LT(1); + e2_AST = astFactory.create(e2); + match(RBRACK); + if (0==inputState.guessing) + { + t1_AST.setType(ARRAY_ACC); + t1_AST.setText("ARRAY_ACC"); + setRegionInfo(t1_AST,s_AST,e2_AST); + } + } + } + else + { + goto _loop207_breakloop; + } + + } +_loop207_breakloop: ; + } // ( ... )* + { // ( ... )* + for (;;) + { + if ((LA(1)==LPAREN) && (tokenSet_13_.member(LA(2)))) + { + t2 = LT(1); + t2_AST = astFactory.create(t2); + astFactory.makeASTRoot(ref currentAST, t2_AST); + match(LPAREN); + arguments(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e3 = LT(1); + e3_AST = astFactory.create(e3); + match(RPAREN); + if (0==inputState.guessing) + { + t2_AST.setType(METHOD_CALL); + t2_AST.setText("METHOD_CALL"); + setRegionInfo(t2_AST,s_AST,e3_AST); + } + } + else + { + goto _loop209_breakloop; + } + + } +_loop209_breakloop: ; + } // ( ... )* + identPrimary_AST = currentAST.root; + returnAST = identPrimary_AST; + } + + public void constant() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST constant_AST = null; - - switch ( LA(1) ) - { - case NUMBER: - { - AST tmp129_AST = null; - tmp129_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp129_AST); - match(NUMBER); - constant_AST = currentAST.root; - break; - } - case STRING_LITERAL: - { - AST tmp130_AST = null; - tmp130_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp130_AST); - match(STRING_LITERAL); - constant_AST = currentAST.root; - break; - } - case REGEX_LITERAL: - { - AST tmp131_AST = null; - tmp131_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp131_AST); - match(REGEX_LITERAL); - constant_AST = currentAST.root; - break; - } - case XML_LITERAL: - { - AST tmp132_AST = null; - tmp132_AST = astFactory.create(LT(1)); - astFactory.addASTChild(ref currentAST, tmp132_AST); - match(XML_LITERAL); - constant_AST = currentAST.root; - break; - } - default: - { - throw new NoViableAltException(LT(1), getFilename()); - } - } - returnAST = constant_AST; - } - - public void functionDefinition() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST constant_AST = null; + + switch ( LA(1) ) + { + case NUMBER: + { + AST tmp129_AST = null; + tmp129_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp129_AST); + match(NUMBER); + constant_AST = currentAST.root; + break; + } + case STRING_LITERAL: + { + AST tmp130_AST = null; + tmp130_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp130_AST); + match(STRING_LITERAL); + constant_AST = currentAST.root; + break; + } + case REGEX_LITERAL: + { + AST tmp131_AST = null; + tmp131_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp131_AST); + match(REGEX_LITERAL); + constant_AST = currentAST.root; + break; + } + case XML_LITERAL: + { + AST tmp132_AST = null; + tmp132_AST = astFactory.create(LT(1)); + astFactory.addASTChild(ref currentAST, tmp132_AST); + match(XML_LITERAL); + constant_AST = currentAST.root; + break; + } + default: + { + throw new NoViableAltException(LT(1), getFilename()); + } + } + returnAST = constant_AST; + } + + public void functionDefinition() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST functionDefinition_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.addASTChild(ref currentAST, s_AST); - match(LITERAL_function); - parameterDeclarationList(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - typeExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - block(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - functionDefinition_AST = (AST)currentAST.root; - functionDefinition_AST = (AST) astFactory.make(astFactory.create(FUNC_DEF,"FUNC_DEF"), functionDefinition_AST); - setRegionInfo(functionDefinition_AST,s_AST,e_AST); - currentAST.root = functionDefinition_AST; - if ( (null != functionDefinition_AST) && (null != functionDefinition_AST.getFirstChild()) ) - currentAST.child = functionDefinition_AST.getFirstChild(); - else - currentAST.child = functionDefinition_AST; - currentAST.advanceChildToEnd(); - } - functionDefinition_AST = currentAST.root; - returnAST = functionDefinition_AST; - } - - public void newExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST functionDefinition_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.addASTChild(ref currentAST, s_AST); + match(LITERAL_function); + parameterDeclarationList(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + typeExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + block(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + functionDefinition_AST = (AST)currentAST.root; + functionDefinition_AST = (AST) astFactory.make(astFactory.create(FUNC_DEF,"FUNC_DEF"), functionDefinition_AST); + setRegionInfo(functionDefinition_AST,s_AST,e_AST); + currentAST.root = functionDefinition_AST; + if ( (null != functionDefinition_AST) && (null != functionDefinition_AST.getFirstChild()) ) + currentAST.child = functionDefinition_AST.getFirstChild(); + else + currentAST.child = functionDefinition_AST; + currentAST.advanceChildToEnd(); + } + functionDefinition_AST = currentAST.root; + returnAST = functionDefinition_AST; + } + + public void newExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST newExpression_AST = null; - IToken s = null; - AST s_AST = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - astFactory.addASTChild(ref currentAST, s_AST); - match(LITERAL_new); - postfixExpression(); - if (0 == inputState.guessing) - { - e_AST = (AST)returnAST; - astFactory.addASTChild(ref currentAST, returnAST); - } - if (0==inputState.guessing) - { - newExpression_AST = (AST)currentAST.root; - newExpression_AST = (AST) astFactory.make(astFactory.create(NEW_EXPR,"NEW_EXPR"), newExpression_AST); - setRegionInfo(newExpression_AST,s_AST,e_AST); - currentAST.root = newExpression_AST; - if ( (null != newExpression_AST) && (null != newExpression_AST.getFirstChild()) ) - currentAST.child = newExpression_AST.getFirstChild(); - else - currentAST.child = newExpression_AST; - currentAST.advanceChildToEnd(); - } - newExpression_AST = currentAST.root; - returnAST = newExpression_AST; - } - - public void encapsulatedExpression() //throws RecognitionException, TokenStreamException + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST newExpression_AST = null; + IToken s = null; + AST s_AST = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + astFactory.addASTChild(ref currentAST, s_AST); + match(LITERAL_new); + postfixExpression(); + if (0 == inputState.guessing) + { + e_AST = (AST)returnAST; + astFactory.addASTChild(ref currentAST, returnAST); + } + if (0==inputState.guessing) + { + newExpression_AST = (AST)currentAST.root; + newExpression_AST = (AST) astFactory.make(astFactory.create(NEW_EXPR,"NEW_EXPR"), newExpression_AST); + setRegionInfo(newExpression_AST,s_AST,e_AST); + currentAST.root = newExpression_AST; + if ( (null != newExpression_AST) && (null != newExpression_AST.getFirstChild()) ) + currentAST.child = newExpression_AST.getFirstChild(); + else + currentAST.child = newExpression_AST; + currentAST.advanceChildToEnd(); + } + newExpression_AST = currentAST.root; + returnAST = newExpression_AST; + } + + public void encapsulatedExpression() //throws RecognitionException, TokenStreamException { - - returnAST = null; - ASTPair currentAST = new ASTPair(); - AST encapsulatedExpression_AST = null; - IToken s = null; - AST s_AST = null; - IToken e = null; - AST e_AST = null; - - s = LT(1); - s_AST = astFactory.create(s); - match(LPAREN); - assignmentExpression(); - if (0 == inputState.guessing) - { - astFactory.addASTChild(ref currentAST, returnAST); - } - e = LT(1); - e_AST = astFactory.create(e); - match(RPAREN); - if (0==inputState.guessing) - { - encapsulatedExpression_AST = (AST)currentAST.root; - encapsulatedExpression_AST = (AST) astFactory.make(astFactory.create(ENCPS_EXPR,"ENCPS_EXPR"), encapsulatedExpression_AST); - setRegionInfo(encapsulatedExpression_AST,s_AST,e_AST); - currentAST.root = encapsulatedExpression_AST; - if ( (null != encapsulatedExpression_AST) && (null != encapsulatedExpression_AST.getFirstChild()) ) - currentAST.child = encapsulatedExpression_AST.getFirstChild(); - else - currentAST.child = encapsulatedExpression_AST; - currentAST.advanceChildToEnd(); - } - encapsulatedExpression_AST = currentAST.root; - returnAST = encapsulatedExpression_AST; - } - - private void initializeFactory() - { - if (astFactory == null) - { - astFactory = new ASTFactory(); - } - initializeASTFactory( astFactory ); - } - static public void initializeASTFactory( ASTFactory factory ) - { - factory.setMaxNodeType(160); - } - - public static readonly string[] tokenNames_ = new string[] { - @"""<0>""", - @"""EOF""", - @"""<2>""", - @"""NULL_TREE_LOOKAHEAD""", - @"""COMPILATION_UNIT""", - @"""IMPORT""", - @"""CLASS_DEF""", - @"""INTERFACE_DEF""", - @"""EXTENDS_CLAUSE""", - @"""IMPLEMENTS_CLAUSE""", - @"""TYPE_BLOCK""", - @"""MODIFIERS""", - @"""VARIABLE_DEF""", - @"""METHOD_DEF""", - @"""NAMESPACE_DEF""", - @"""PARAMS""", - @"""PARAM""", - @"""TYPE_SPEC""", - @"""BLOCK""", - @"""EXPR""", - @"""ELIST""", - @"""EXPR_STMNT""", - @"""NEW_EXPR""", - @"""ENCPS_EXPR""", - @"""VAR_INIT""", - @"""METHOD_CALL""", - @"""ARRAY_ACC""", - @"""UNARY_PLUS""", - @"""UNARY_MINUS""", - @"""POST_INC""", - @"""POST_DEC""", - @"""ARRAY_LITERAL""", - @"""ELEMENT""", - @"""OBJECT_LITERAL""", - @"""OBJECT_FIELD""", - @"""FUNC_DEF""", - @"""FOR_INIT""", - @"""FOR_CONDITION""", - @"""FOR_ITERATOR""", - @"""package""", - @"""LCURLY""", - @"""SEMI""", - @"""RCURLY""", - @"""import""", - @"""LBRACK""", - @"""COMMA""", - @"""RBRACK""", - @"""LPAREN""", - @"""RPAREN""", - @"""class""", - @"""interface""", - @"""extends""", - @"""implements""", - @"""function""", - @"""get""", - @"""set""", - @"""/n""", - @"""/r""", - @"""IDENT""", - @"""namespace""", - @"""var""", - @"""const""", - @"""ASSIGN""", - @"""REST""", - @"""while""", - @"""do""", - @"""with""", - @"""if""", - @"""else""", - @"""throw""", - @"""return""", - @"""continue""", - @"""break""", - @"""switch""", - @"""case""", - @"""COLON""", - @"""default""", - @"""for""", - @"""each""", - @"""in""", - @"""DOT""", - @"""STAR""", - @"""public""", - @"""private""", - @"""protected""", - @"""internal""", - @"""static""", - @"""final""", - @"""enumerable""", - @"""explicit""", - @"""override""", - @"""dynamic""", - @"""NUMBER""", - @"""STAR_ASSIGN""", - @"""DIV_ASSIGN""", - @"""MOD_ASSIGN""", - @"""PLUS_ASSIGN""", - @"""MINUS_ASSIGN""", - @"""SL_ASSIGN""", - @"""SR_ASSIGN""", - @"""BSR_ASSIGN""", - @"""BAND_ASSIGN""", - @"""BXOR_ASSIGN""", - @"""BOR_ASSIGN""", - @"""LAND_ASSIGN""", - @"""LOR_ASSIGN""", - @"""QUESTION""", - @"""LOR""", - @"""LAND""", - @"""BOR""", - @"""BXOR""", - @"""BAND""", - @"""STRICT_EQUAL""", - @"""STRICT_NOT_EQUAL""", - @"""NOT_EQUAL""", - @"""EQUAL""", - @"""LWT""", - @"""GT""", - @"""LE""", - @"""GE""", - @"""is""", - @"""as""", - @"""SL""", - @"""SR""", - @"""BSR""", - @"""PLUS""", - @"""MINUS""", - @"""DIV""", - @"""MOD""", - @"""INC""", - @"""DEC""", - @"""delete""", - @"""typeof""", - @"""LNOT""", - @"""BNOT""", - @"""E4X_DESC""", - @"""E4X_ATTRI""", - @"""null""", - @"""true""", - @"""false""", - @"""undefined""", - @"""STRING_LITERAL""", - @"""REGEX_LITERAL""", - @"""XML_LITERAL""", - @"""new""", - @"""DBL_COLON""", - @"""XML_ATTRIBUTE""", - @"""XML_BINDING""", - @"""XML_AS3_EXPRESSION""", - @"""XML_TEXTNODE""", - @"""XML_COMMENT""", - @"""XML_CDATA""", - @"""REGEX_BODY""", - @"""WS""", - @"""NL""", - @"""BOM""", - @"""SL_COMMENT""", - @"""ML_COMMENT""", - @"""EXPONENT""", - @"""HEX_DIGIT""", - @"""ESC""" - }; - - private static long[] mk_tokenSet_0_() - { - long[] data = { -216172782113783824L, -1L, 8589934591L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_()); - private static long[] mk_tokenSet_1_() - { - long[] data = { 1450320708222582784L, 6917529027909526511L, 130686L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_()); - private static long[] mk_tokenSet_2_() - { - long[] data = { 4611686018427387904L, 4397509640192L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_()); - private static long[] mk_tokenSet_3_() - { - long[] data = { 297397004592480256L, 6917529027909517312L, 130686L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_3_ = new BitSet(mk_tokenSet_3_()); - private static long[] mk_tokenSet_4_() - { - long[] data = { 8946399560259862528L, 6917537823733891071L, 130686L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_4_ = new BitSet(mk_tokenSet_4_()); - private static long[] mk_tokenSet_5_() - { - long[] data = { -222929281066467326L, -1L, 130815L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_5_ = new BitSet(mk_tokenSet_5_()); - private static long[] mk_tokenSet_6_() - { - long[] data = { 1450325106269093888L, 6917529027909531647L, 130686L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_6_ = new BitSet(mk_tokenSet_6_()); - private static long[] mk_tokenSet_7_() - { - long[] data = { 8946399560259862528L, -1L, 130815L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_7_ = new BitSet(mk_tokenSet_7_()); - private static long[] mk_tokenSet_8_() - { - long[] data = { 1450325106269093888L, 6917529027909526511L, 130686L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_8_ = new BitSet(mk_tokenSet_8_()); - private static long[] mk_tokenSet_9_() - { - long[] data = { 6062116677812748288L, -268224513L, 130815L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_9_ = new BitSet(mk_tokenSet_9_()); - private static long[] mk_tokenSet_10_() - { - long[] data = { 1450320708222582784L, 6917529027909517312L, 130686L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_10_ = new BitSet(mk_tokenSet_10_()); - private static long[] mk_tokenSet_11_() - { - long[] data = { 297397004592480256L, 6917529027909648384L, 130942L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_11_ = new BitSet(mk_tokenSet_11_()); - private static long[] mk_tokenSet_12_() - { - long[] data = { 8946399560259862528L, -16385L, 130815L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_12_ = new BitSet(mk_tokenSet_12_()); - private static long[] mk_tokenSet_13_() - { - long[] data = { 297678479569190912L, 6917529027909517312L, 130686L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_13_ = new BitSet(mk_tokenSet_13_()); - private static long[] mk_tokenSet_14_() - { - long[] data = { -222929281066467326L, -1L, 131071L, 0L, 0L, 0L}; - return data; - } - public static readonly BitSet tokenSet_14_ = new BitSet(mk_tokenSet_14_()); - + + returnAST = null; + ASTPair currentAST = new ASTPair(); + AST encapsulatedExpression_AST = null; + IToken s = null; + AST s_AST = null; + IToken e = null; + AST e_AST = null; + + s = LT(1); + s_AST = astFactory.create(s); + match(LPAREN); + assignmentExpression(); + if (0 == inputState.guessing) + { + astFactory.addASTChild(ref currentAST, returnAST); + } + e = LT(1); + e_AST = astFactory.create(e); + match(RPAREN); + if (0==inputState.guessing) + { + encapsulatedExpression_AST = (AST)currentAST.root; + encapsulatedExpression_AST = (AST) astFactory.make(astFactory.create(ENCPS_EXPR,"ENCPS_EXPR"), encapsulatedExpression_AST); + setRegionInfo(encapsulatedExpression_AST,s_AST,e_AST); + currentAST.root = encapsulatedExpression_AST; + if ( (null != encapsulatedExpression_AST) && (null != encapsulatedExpression_AST.getFirstChild()) ) + currentAST.child = encapsulatedExpression_AST.getFirstChild(); + else + currentAST.child = encapsulatedExpression_AST; + currentAST.advanceChildToEnd(); + } + encapsulatedExpression_AST = currentAST.root; + returnAST = encapsulatedExpression_AST; + } + + private void initializeFactory() + { + if (astFactory == null) + { + astFactory = new ASTFactory(); + } + initializeASTFactory( astFactory ); + } + static public void initializeASTFactory( ASTFactory factory ) + { + factory.setMaxNodeType(160); + } + + public static readonly string[] tokenNames_ = new string[] { + @"""<0>""", + @"""EOF""", + @"""<2>""", + @"""NULL_TREE_LOOKAHEAD""", + @"""COMPILATION_UNIT""", + @"""IMPORT""", + @"""CLASS_DEF""", + @"""INTERFACE_DEF""", + @"""EXTENDS_CLAUSE""", + @"""IMPLEMENTS_CLAUSE""", + @"""TYPE_BLOCK""", + @"""MODIFIERS""", + @"""VARIABLE_DEF""", + @"""METHOD_DEF""", + @"""NAMESPACE_DEF""", + @"""PARAMS""", + @"""PARAM""", + @"""TYPE_SPEC""", + @"""BLOCK""", + @"""EXPR""", + @"""ELIST""", + @"""EXPR_STMNT""", + @"""NEW_EXPR""", + @"""ENCPS_EXPR""", + @"""VAR_INIT""", + @"""METHOD_CALL""", + @"""ARRAY_ACC""", + @"""UNARY_PLUS""", + @"""UNARY_MINUS""", + @"""POST_INC""", + @"""POST_DEC""", + @"""ARRAY_LITERAL""", + @"""ELEMENT""", + @"""OBJECT_LITERAL""", + @"""OBJECT_FIELD""", + @"""FUNC_DEF""", + @"""FOR_INIT""", + @"""FOR_CONDITION""", + @"""FOR_ITERATOR""", + @"""package""", + @"""LCURLY""", + @"""SEMI""", + @"""RCURLY""", + @"""import""", + @"""LBRACK""", + @"""COMMA""", + @"""RBRACK""", + @"""LPAREN""", + @"""RPAREN""", + @"""class""", + @"""interface""", + @"""extends""", + @"""implements""", + @"""function""", + @"""get""", + @"""set""", + @"""/n""", + @"""/r""", + @"""IDENT""", + @"""namespace""", + @"""var""", + @"""const""", + @"""ASSIGN""", + @"""REST""", + @"""while""", + @"""do""", + @"""with""", + @"""if""", + @"""else""", + @"""throw""", + @"""return""", + @"""continue""", + @"""break""", + @"""switch""", + @"""case""", + @"""COLON""", + @"""default""", + @"""for""", + @"""each""", + @"""in""", + @"""DOT""", + @"""STAR""", + @"""public""", + @"""private""", + @"""protected""", + @"""internal""", + @"""static""", + @"""final""", + @"""enumerable""", + @"""explicit""", + @"""override""", + @"""dynamic""", + @"""NUMBER""", + @"""STAR_ASSIGN""", + @"""DIV_ASSIGN""", + @"""MOD_ASSIGN""", + @"""PLUS_ASSIGN""", + @"""MINUS_ASSIGN""", + @"""SL_ASSIGN""", + @"""SR_ASSIGN""", + @"""BSR_ASSIGN""", + @"""BAND_ASSIGN""", + @"""BXOR_ASSIGN""", + @"""BOR_ASSIGN""", + @"""LAND_ASSIGN""", + @"""LOR_ASSIGN""", + @"""QUESTION""", + @"""LOR""", + @"""LAND""", + @"""BOR""", + @"""BXOR""", + @"""BAND""", + @"""STRICT_EQUAL""", + @"""STRICT_NOT_EQUAL""", + @"""NOT_EQUAL""", + @"""EQUAL""", + @"""LWT""", + @"""GT""", + @"""LE""", + @"""GE""", + @"""is""", + @"""as""", + @"""SL""", + @"""SR""", + @"""BSR""", + @"""PLUS""", + @"""MINUS""", + @"""DIV""", + @"""MOD""", + @"""INC""", + @"""DEC""", + @"""delete""", + @"""typeof""", + @"""LNOT""", + @"""BNOT""", + @"""E4X_DESC""", + @"""E4X_ATTRI""", + @"""null""", + @"""true""", + @"""false""", + @"""undefined""", + @"""STRING_LITERAL""", + @"""REGEX_LITERAL""", + @"""XML_LITERAL""", + @"""new""", + @"""DBL_COLON""", + @"""XML_ATTRIBUTE""", + @"""XML_BINDING""", + @"""XML_AS3_EXPRESSION""", + @"""XML_TEXTNODE""", + @"""XML_COMMENT""", + @"""XML_CDATA""", + @"""REGEX_BODY""", + @"""WS""", + @"""NL""", + @"""BOM""", + @"""SL_COMMENT""", + @"""ML_COMMENT""", + @"""EXPONENT""", + @"""HEX_DIGIT""", + @"""ESC""" + }; + + private static long[] mk_tokenSet_0_() + { + long[] data = { -216172782113783824L, -1L, 8589934591L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_0_ = new BitSet(mk_tokenSet_0_()); + private static long[] mk_tokenSet_1_() + { + long[] data = { 1450320708222582784L, 6917529027909526511L, 130686L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_1_ = new BitSet(mk_tokenSet_1_()); + private static long[] mk_tokenSet_2_() + { + long[] data = { 4611686018427387904L, 4397509640192L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_2_ = new BitSet(mk_tokenSet_2_()); + private static long[] mk_tokenSet_3_() + { + long[] data = { 297397004592480256L, 6917529027909517312L, 130686L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_3_ = new BitSet(mk_tokenSet_3_()); + private static long[] mk_tokenSet_4_() + { + long[] data = { 8946399560259862528L, 6917537823733891071L, 130686L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_4_ = new BitSet(mk_tokenSet_4_()); + private static long[] mk_tokenSet_5_() + { + long[] data = { -222929281066467326L, -1L, 130815L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_5_ = new BitSet(mk_tokenSet_5_()); + private static long[] mk_tokenSet_6_() + { + long[] data = { 1450325106269093888L, 6917529027909531647L, 130686L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_6_ = new BitSet(mk_tokenSet_6_()); + private static long[] mk_tokenSet_7_() + { + long[] data = { 8946399560259862528L, -1L, 130815L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_7_ = new BitSet(mk_tokenSet_7_()); + private static long[] mk_tokenSet_8_() + { + long[] data = { 1450325106269093888L, 6917529027909526511L, 130686L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_8_ = new BitSet(mk_tokenSet_8_()); + private static long[] mk_tokenSet_9_() + { + long[] data = { 6062116677812748288L, -268224513L, 130815L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_9_ = new BitSet(mk_tokenSet_9_()); + private static long[] mk_tokenSet_10_() + { + long[] data = { 1450320708222582784L, 6917529027909517312L, 130686L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_10_ = new BitSet(mk_tokenSet_10_()); + private static long[] mk_tokenSet_11_() + { + long[] data = { 297397004592480256L, 6917529027909648384L, 130942L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_11_ = new BitSet(mk_tokenSet_11_()); + private static long[] mk_tokenSet_12_() + { + long[] data = { 8946399560259862528L, -16385L, 130815L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_12_ = new BitSet(mk_tokenSet_12_()); + private static long[] mk_tokenSet_13_() + { + long[] data = { 297678479569190912L, 6917529027909517312L, 130686L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_13_ = new BitSet(mk_tokenSet_13_()); + private static long[] mk_tokenSet_14_() + { + long[] data = { -222929281066467326L, -1L, 131071L, 0L, 0L, 0L}; + return data; + } + public static readonly BitSet tokenSet_14_ = new BitSet(mk_tokenSet_14_()); + } } diff --git a/External/Plugins/AS3Context/Grammar/AS3TokenTypes.cs b/External/Plugins/AS3Context/Grammar/AS3TokenTypes.cs index ed0eaf3130..8ffff27eea 100644 --- a/External/Plugins/AS3Context/Grammar/AS3TokenTypes.cs +++ b/External/Plugins/AS3Context/Grammar/AS3TokenTypes.cs @@ -34,167 +34,167 @@ namespace AS3Context.Grammar { - public class AS3TokenTypes - { - public const int EOF = 1; - public const int NULL_TREE_LOOKAHEAD = 3; - public const int COMPILATION_UNIT = 4; - public const int IMPORT = 5; - public const int CLASS_DEF = 6; - public const int INTERFACE_DEF = 7; - public const int EXTENDS_CLAUSE = 8; - public const int IMPLEMENTS_CLAUSE = 9; - public const int TYPE_BLOCK = 10; - public const int MODIFIERS = 11; - public const int VARIABLE_DEF = 12; - public const int METHOD_DEF = 13; - public const int NAMESPACE_DEF = 14; - public const int PARAMS = 15; - public const int PARAM = 16; - public const int TYPE_SPEC = 17; - public const int BLOCK = 18; - public const int EXPR = 19; - public const int ELIST = 20; - public const int EXPR_STMNT = 21; - public const int NEW_EXPR = 22; - public const int ENCPS_EXPR = 23; - public const int VAR_INIT = 24; - public const int METHOD_CALL = 25; - public const int ARRAY_ACC = 26; - public const int UNARY_PLUS = 27; - public const int UNARY_MINUS = 28; - public const int POST_INC = 29; - public const int POST_DEC = 30; - public const int ARRAY_LITERAL = 31; - public const int ELEMENT = 32; - public const int OBJECT_LITERAL = 33; - public const int OBJECT_FIELD = 34; - public const int FUNC_DEF = 35; - public const int FOR_INIT = 36; - public const int FOR_CONDITION = 37; - public const int FOR_ITERATOR = 38; - public const int LITERAL_package = 39; - public const int LCURLY = 40; - public const int SEMI = 41; - public const int RCURLY = 42; - public const int LITERAL_import = 43; - public const int LBRACK = 44; - public const int COMMA = 45; - public const int RBRACK = 46; - public const int LPAREN = 47; - public const int RPAREN = 48; - public const int LITERAL_class = 49; - public const int LITERAL_interface = 50; - public const int LITERAL_extends = 51; - public const int LITERAL_implements = 52; - public const int LITERAL_function = 53; - public const int LITERAL_get = 54; - public const int LITERAL_set = 55; - // "/n" = 56 - // "/r" = 57 - public const int IDENT = 58; - public const int LITERAL_namespace = 59; - public const int LITERAL_var = 60; - public const int LITERAL_const = 61; - public const int ASSIGN = 62; - public const int REST = 63; - public const int LITERAL_while = 64; - public const int LITERAL_do = 65; - public const int LITERAL_with = 66; - public const int LITERAL_if = 67; - public const int LITERAL_else = 68; - public const int LITERAL_throw = 69; - public const int LITERAL_return = 70; - public const int LITERAL_continue = 71; - public const int LITERAL_break = 72; - public const int LITERAL_switch = 73; - public const int LITERAL_case = 74; - public const int COLON = 75; - public const int LITERAL_default = 76; - public const int LITERAL_for = 77; - public const int LITERAL_each = 78; - public const int LITERAL_in = 79; - public const int DOT = 80; - public const int STAR = 81; - public const int LITERAL_public = 82; - public const int LITERAL_private = 83; - public const int LITERAL_protected = 84; - public const int LITERAL_internal = 85; - public const int LITERAL_static = 86; - public const int LITERAL_final = 87; - public const int LITERAL_enumerable = 88; - public const int LITERAL_explicit = 89; - public const int LITERAL_override = 90; - public const int LITERAL_dynamic = 91; - public const int NUMBER = 92; - public const int STAR_ASSIGN = 93; - public const int DIV_ASSIGN = 94; - public const int MOD_ASSIGN = 95; - public const int PLUS_ASSIGN = 96; - public const int MINUS_ASSIGN = 97; - public const int SL_ASSIGN = 98; - public const int SR_ASSIGN = 99; - public const int BSR_ASSIGN = 100; - public const int BAND_ASSIGN = 101; - public const int BXOR_ASSIGN = 102; - public const int BOR_ASSIGN = 103; - public const int LAND_ASSIGN = 104; - public const int LOR_ASSIGN = 105; - public const int QUESTION = 106; - public const int LOR = 107; - public const int LAND = 108; - public const int BOR = 109; - public const int BXOR = 110; - public const int BAND = 111; - public const int STRICT_EQUAL = 112; - public const int STRICT_NOT_EQUAL = 113; - public const int NOT_EQUAL = 114; - public const int EQUAL = 115; - public const int LWT = 116; - public const int GT = 117; - public const int LE = 118; - public const int GE = 119; - public const int LITERAL_is = 120; - public const int LITERAL_as = 121; - public const int SL = 122; - public const int SR = 123; - public const int BSR = 124; - public const int PLUS = 125; - public const int MINUS = 126; - public const int DIV = 127; - public const int MOD = 128; - public const int INC = 129; - public const int DEC = 130; - public const int LITERAL_delete = 131; - public const int LITERAL_typeof = 132; - public const int LNOT = 133; - public const int BNOT = 134; - public const int E4X_DESC = 135; - public const int E4X_ATTRI = 136; - public const int LITERAL_null = 137; - public const int LITERAL_true = 138; - public const int LITERAL_false = 139; - public const int LITERAL_undefined = 140; - public const int STRING_LITERAL = 141; - public const int REGEX_LITERAL = 142; - public const int XML_LITERAL = 143; - public const int LITERAL_new = 144; - public const int DBL_COLON = 145; - public const int XML_ATTRIBUTE = 146; - public const int XML_BINDING = 147; - public const int XML_AS3_EXPRESSION = 148; - public const int XML_TEXTNODE = 149; - public const int XML_COMMENT = 150; - public const int XML_CDATA = 151; - public const int REGEX_BODY = 152; - public const int WS = 153; - public const int NL = 154; - public const int BOM = 155; - public const int SL_COMMENT = 156; - public const int ML_COMMENT = 157; - public const int EXPONENT = 158; - public const int HEX_DIGIT = 159; - public const int ESC = 160; - - } + public class AS3TokenTypes + { + public const int EOF = 1; + public const int NULL_TREE_LOOKAHEAD = 3; + public const int COMPILATION_UNIT = 4; + public const int IMPORT = 5; + public const int CLASS_DEF = 6; + public const int INTERFACE_DEF = 7; + public const int EXTENDS_CLAUSE = 8; + public const int IMPLEMENTS_CLAUSE = 9; + public const int TYPE_BLOCK = 10; + public const int MODIFIERS = 11; + public const int VARIABLE_DEF = 12; + public const int METHOD_DEF = 13; + public const int NAMESPACE_DEF = 14; + public const int PARAMS = 15; + public const int PARAM = 16; + public const int TYPE_SPEC = 17; + public const int BLOCK = 18; + public const int EXPR = 19; + public const int ELIST = 20; + public const int EXPR_STMNT = 21; + public const int NEW_EXPR = 22; + public const int ENCPS_EXPR = 23; + public const int VAR_INIT = 24; + public const int METHOD_CALL = 25; + public const int ARRAY_ACC = 26; + public const int UNARY_PLUS = 27; + public const int UNARY_MINUS = 28; + public const int POST_INC = 29; + public const int POST_DEC = 30; + public const int ARRAY_LITERAL = 31; + public const int ELEMENT = 32; + public const int OBJECT_LITERAL = 33; + public const int OBJECT_FIELD = 34; + public const int FUNC_DEF = 35; + public const int FOR_INIT = 36; + public const int FOR_CONDITION = 37; + public const int FOR_ITERATOR = 38; + public const int LITERAL_package = 39; + public const int LCURLY = 40; + public const int SEMI = 41; + public const int RCURLY = 42; + public const int LITERAL_import = 43; + public const int LBRACK = 44; + public const int COMMA = 45; + public const int RBRACK = 46; + public const int LPAREN = 47; + public const int RPAREN = 48; + public const int LITERAL_class = 49; + public const int LITERAL_interface = 50; + public const int LITERAL_extends = 51; + public const int LITERAL_implements = 52; + public const int LITERAL_function = 53; + public const int LITERAL_get = 54; + public const int LITERAL_set = 55; + // "/n" = 56 + // "/r" = 57 + public const int IDENT = 58; + public const int LITERAL_namespace = 59; + public const int LITERAL_var = 60; + public const int LITERAL_const = 61; + public const int ASSIGN = 62; + public const int REST = 63; + public const int LITERAL_while = 64; + public const int LITERAL_do = 65; + public const int LITERAL_with = 66; + public const int LITERAL_if = 67; + public const int LITERAL_else = 68; + public const int LITERAL_throw = 69; + public const int LITERAL_return = 70; + public const int LITERAL_continue = 71; + public const int LITERAL_break = 72; + public const int LITERAL_switch = 73; + public const int LITERAL_case = 74; + public const int COLON = 75; + public const int LITERAL_default = 76; + public const int LITERAL_for = 77; + public const int LITERAL_each = 78; + public const int LITERAL_in = 79; + public const int DOT = 80; + public const int STAR = 81; + public const int LITERAL_public = 82; + public const int LITERAL_private = 83; + public const int LITERAL_protected = 84; + public const int LITERAL_internal = 85; + public const int LITERAL_static = 86; + public const int LITERAL_final = 87; + public const int LITERAL_enumerable = 88; + public const int LITERAL_explicit = 89; + public const int LITERAL_override = 90; + public const int LITERAL_dynamic = 91; + public const int NUMBER = 92; + public const int STAR_ASSIGN = 93; + public const int DIV_ASSIGN = 94; + public const int MOD_ASSIGN = 95; + public const int PLUS_ASSIGN = 96; + public const int MINUS_ASSIGN = 97; + public const int SL_ASSIGN = 98; + public const int SR_ASSIGN = 99; + public const int BSR_ASSIGN = 100; + public const int BAND_ASSIGN = 101; + public const int BXOR_ASSIGN = 102; + public const int BOR_ASSIGN = 103; + public const int LAND_ASSIGN = 104; + public const int LOR_ASSIGN = 105; + public const int QUESTION = 106; + public const int LOR = 107; + public const int LAND = 108; + public const int BOR = 109; + public const int BXOR = 110; + public const int BAND = 111; + public const int STRICT_EQUAL = 112; + public const int STRICT_NOT_EQUAL = 113; + public const int NOT_EQUAL = 114; + public const int EQUAL = 115; + public const int LWT = 116; + public const int GT = 117; + public const int LE = 118; + public const int GE = 119; + public const int LITERAL_is = 120; + public const int LITERAL_as = 121; + public const int SL = 122; + public const int SR = 123; + public const int BSR = 124; + public const int PLUS = 125; + public const int MINUS = 126; + public const int DIV = 127; + public const int MOD = 128; + public const int INC = 129; + public const int DEC = 130; + public const int LITERAL_delete = 131; + public const int LITERAL_typeof = 132; + public const int LNOT = 133; + public const int BNOT = 134; + public const int E4X_DESC = 135; + public const int E4X_ATTRI = 136; + public const int LITERAL_null = 137; + public const int LITERAL_true = 138; + public const int LITERAL_false = 139; + public const int LITERAL_undefined = 140; + public const int STRING_LITERAL = 141; + public const int REGEX_LITERAL = 142; + public const int XML_LITERAL = 143; + public const int LITERAL_new = 144; + public const int DBL_COLON = 145; + public const int XML_ATTRIBUTE = 146; + public const int XML_BINDING = 147; + public const int XML_AS3_EXPRESSION = 148; + public const int XML_TEXTNODE = 149; + public const int XML_COMMENT = 150; + public const int XML_CDATA = 151; + public const int REGEX_BODY = 152; + public const int WS = 153; + public const int NL = 154; + public const int BOM = 155; + public const int SL_COMMENT = 156; + public const int ML_COMMENT = 157; + public const int EXPONENT = 158; + public const int HEX_DIGIT = 159; + public const int ESC = 160; + + } } diff --git a/External/Plugins/AS3Context/MxmlComplete.cs b/External/Plugins/AS3Context/MxmlComplete.cs index 5cbd704ca9..0506b3edd4 100644 --- a/External/Plugins/AS3Context/MxmlComplete.cs +++ b/External/Plugins/AS3Context/MxmlComplete.cs @@ -1,28 +1,32 @@ using System; using System.Collections.Generic; +using System.Diagnostics; +using System.Drawing; +using System.IO; using System.Text; -using XMLCompletion; -using ASCompletion.Model; +using System.Text.RegularExpressions; +using ASCompletion; using ASCompletion.Completion; +using ASCompletion.Context; +using ASCompletion.Model; using PluginCore; using PluginCore.Controls; -using System.Text.RegularExpressions; -using System.IO; using PluginCore.Helpers; +using XMLCompletion; namespace AS3Context { class MxmlComplete { - static public bool IsDirty; - static public Context context; - static public MxmlFilterContext mxmlContext; + public static bool IsDirty; + public static Context context; + public static MxmlFilterContext mxmlContext; #region shortcuts public static bool GotoDeclaration() { - ScintillaNet.ScintillaControl sci = PluginBase.MainForm.CurrentDocument.SciControl; - if (sci == null) return false; + var sci = PluginBase.MainForm.CurrentDocument?.SciControl; + if (sci is null) return false; if (sci.ConfigurationLanguage != "xml") return false; int pos = sci.CurrentPos; @@ -33,13 +37,11 @@ public static bool GotoDeclaration() if (c <= 32 || c == '/' || c == '>') break; pos ++; } - XMLContextTag ctag = XMLComplete.GetXMLContextTag(sci, pos); - if (ctag.Name == null) return true; + var ctag = XMLComplete.GetXMLContextTag(sci, pos); + if (ctag.Name is null) return true; string word = sci.GetWordFromPosition(sci.CurrentPos); - string type = ResolveType(mxmlContext, ctag.Name); - ClassModel model = context.ResolveType(type, mxmlContext.model); - + var model = context.ResolveType(type, mxmlContext.model); if (model.IsVoid()) // try resolving tag as member of parent tag { parentTag = XMLComplete.GetParentTag(sci, ctag); @@ -53,16 +55,14 @@ public static bool GotoDeclaration() else return true; } - if (!ctag.Name.EndsWith(word)) + if (word != null && !ctag.Name.EndsWithOrdinal(word)) { - ASResult found = ResolveAttribute(model, word); + var found = ResolveAttribute(model, word); ASComplete.OpenDocumentToDeclaration(sci, found); } else { - ASResult found = new ASResult(); - found.InFile = model.InFile; - found.Type = model; + var found = new ASResult {InFile = model.InFile, Type = model}; ASComplete.OpenDocumentToDeclaration(sci, found); } return true; @@ -70,21 +70,23 @@ public static bool GotoDeclaration() #endregion #region tag completion - static private XMLContextTag tagContext; - static private XMLContextTag parentTag; - static private string tokenContext; - static private string checksum; - static private Dictionary> allTags; + + static XMLContextTag tagContext; + static XMLContextTag parentTag; + static string tokenContext; + static string checksum; + + static Dictionary> allTags; //static private Regex reIncPath = new Regex("[\"']([^\"']+)", RegexOptions.Compiled); - static private Regex reIncPath = new Regex("(\"|')([^\r\n]+)(\\1)", RegexOptions.Compiled); - static private Dictionary includesCache = new Dictionary(); + static readonly Regex reIncPath = new Regex("(\"|')([^\r\n]+)(\\1)", RegexOptions.Compiled); + static readonly Dictionary includesCache = new Dictionary(); /// /// Called /// /// /// - static public bool HandleElement(object data) + public static bool HandleElement(object data) { if (!GetContext(data)) return false; @@ -97,19 +99,19 @@ static public bool HandleElement(object data) bool isContainer = AddParentAttributes(mix, excludes); // current tag attributes if (isContainer) // container children tag - foreach (string ns in mxmlContext.namespaces.Keys) - { - string uri = mxmlContext.namespaces[ns]; - if (ns != "*") mix.Add(new NamespaceItem(ns, uri)); - - if (!allTags.ContainsKey(ns)) - continue; - foreach (string tag in allTags[ns]) + foreach (string ns in mxmlContext.namespaces.Keys) { - if (ns == "*") mix.Add(new HtmlTagItem(tag, tag)); - else mix.Add(new HtmlTagItem(tag, ns + ":" + tag, uri)); + string uri = mxmlContext.namespaces[ns]; + if (ns != "*") mix.Add(new NamespaceItem(ns, uri)); + + if (!allTags.ContainsKey(ns)) + continue; + foreach (string tag in allTags[ns]) + { + if (ns == "*") mix.Add(new HtmlTagItem(tag, tag)); + else mix.Add(new HtmlTagItem(tag, ns + ":" + tag, uri)); + } } - } // cleanup and show list mix.Sort(new MXMLListItemComparer()); @@ -130,7 +132,7 @@ static public bool HandleElement(object data) return true; } - private static bool AddParentAttributes(List mix, List excludes) + static bool AddParentAttributes(List mix, List excludes) { bool isContainer = true; if (parentTag.Name != null) // add parent tag members @@ -142,8 +144,8 @@ private static bool AddParentAttributes(List mix, List mix, List mix = new List(); - List excludes = new List(); - - bool isContainer = AddParentAttributes(mix, excludes); // current tag attributes - + var ns = tagContext.Name.Substring(0, p); + if (!mxmlContext.namespaces.ContainsKey(ns)) return true; + var uri = mxmlContext.namespaces[ns]; + var mix = new List(); + var excludes = new List(); + var isContainer = AddParentAttributes(mix, excludes); // current tag attributes if (isContainer && allTags.ContainsKey(ns)) // container children tags foreach (string tag in allTags[ns]) mix.Add(new HtmlTagItem(tag, ns + ":" + tag, uri)); // cleanup and show list mix.Sort(new MXMLListItemComparer()); - List items = new List(); + var items = new List(); string previous = null; - foreach (ICompletionListItem item in mix) + foreach (var item in mix) { if (previous == item.Label) continue; previous = item.Label; @@ -193,31 +189,29 @@ static public bool HandleNamespace(object data) return true; } - static public bool HandleElementClose(object data) + public static bool HandleElementClose(object data) { if (!GetContext(data)) return false; - if (tagContext.Closing) return false; - - string type = ResolveType(mxmlContext, tagContext.Name); - ScintillaNet.ScintillaControl sci = PluginBase.MainForm.CurrentDocument.SciControl; - - if (type.StartsWith("mx.builtin.") || type.StartsWith("fx.builtin.")) // special tags + var sci = PluginBase.MainForm.CurrentDocument?.SciControl; + if (sci is null) return false; + var type = ResolveType(mxmlContext, tagContext.Name); + if (type.StartsWithOrdinal("mx.builtin.") || type.StartsWithOrdinal("fx.builtin.")) // special tags { - if (type.EndsWith(".Script")) + if (type.EndsWithOrdinal(".Script")) { string snip = "$(Boundary)\n\t\n"; SnippetHelper.InsertSnippetText(sci, sci.CurrentPos, snip); return true; } - if (type.EndsWith(".Style")) + if (type.EndsWithOrdinal(".Style")) { string snip = "$(Boundary)"; foreach (string ns in mxmlContext.namespaces.Keys) { string uri = mxmlContext.namespaces[ns]; if (ns != "fx") - snip += String.Format("\n\t@namespace {0} \"{1}\";", ns, uri); + snip += $"\n\t@namespace {ns} \"{uri}\";"; } snip += "\n\t$(EntryPoint)\n"; SnippetHelper.InsertSnippetText(sci, sci.CurrentPos, snip); @@ -227,30 +221,80 @@ static public bool HandleElementClose(object data) return false; } - static public bool HandleAttribute(object data) + public static bool HandleAttribute(object data) { if (!GetContext(data)) return false; - - string type = ResolveType(mxmlContext, tagContext.Name); - ClassModel tagClass = context.ResolveType(type, mxmlContext.model); + var type = ResolveType(mxmlContext, tagContext.Name); + var tagClass = context.ResolveType(type, mxmlContext.model); if (tagClass.IsVoid()) return true; tagClass.ResolveExtends(); - - List mix = new List(); - List excludes = new List(); + var mix = new List(); + var excludes = new List(); GetTagAttributes(tagClass, mix, excludes, null); // cleanup and show list mix.Sort(new MXMLListItemComparer()); - List items = new List(); + var items = new List(); string previous = null; - foreach (ICompletionListItem item in mix) + foreach (var item in mix) { if (previous == item.Label) continue; previous = item.Label; if (excludes.Contains(previous)) continue; items.Add(item); } + if (items.Count == 0) return true; + if (!string.IsNullOrEmpty(tokenContext)) CompletionList.Show(items, false, tokenContext); + else CompletionList.Show(items, true); + CompletionList.MinWordLength = 0; + return true; + } + + public static bool HandleAttributeValue(object data) + { + if (!GetContext(data)) return false; + var type = ResolveType(mxmlContext, tagContext.Name); + var tagClass = context.ResolveType(type, mxmlContext.model); + if (tagClass.IsVoid()) return true; + tagClass.ResolveExtends(); + var caBuilder = new StringBuilder(); + bool possibleStartFound = false, startFound = false; + for (int i = tagContext.Tag.Length - 1; i >= 0; i--) + { + char currChar = tagContext.Tag[i]; + if (currChar == '=') + { + possibleStartFound = true; + } + else if (startFound) + { + if (char.IsWhiteSpace(currChar)) + break; + + caBuilder.Insert(0, currChar); + } + else if (possibleStartFound && !char.IsWhiteSpace(currChar)) + { + startFound = true; + caBuilder.Insert(0, currChar); + } + } + + var currentAttribute = caBuilder.ToString(); + + var mix = GetTagAttributeValues(tagClass, null, currentAttribute); + if (mix.IsNullOrEmpty()) return true; + + // cleanup and show list + mix.Sort(new MXMLListItemComparer()); + var items = new List(); + string previous = null; + foreach (var item in mix) + { + if (previous == item.Label) continue; + previous = item.Label; + items.Add(item); + } if (items.Count == 0) return true; if (!string.IsNullOrEmpty(tokenContext)) CompletionList.Show(items, false, tokenContext); @@ -259,13 +303,13 @@ static public bool HandleAttribute(object data) return true; } - private static bool GetTagAttributes(ClassModel tagClass, List mix, List excludes, string ns) + static bool GetTagAttributes(ClassModel tagClass, ICollection mix, ICollection excludes, string ns) { - ClassModel curClass = mxmlContext.model.GetPublicClass(); - ClassModel tmpClass = tagClass; - FlagType mask = FlagType.Variable | FlagType.Setter; - Visibility acc = context.TypesAffinity(curClass, tmpClass); - bool isContainer = false; + var curClass = mxmlContext.model.GetPublicClass(); + var tmpClass = tagClass; + var mask = FlagType.Variable | FlagType.Setter; + var acc = context.TypesAffinity(curClass, tmpClass); + var isContainer = false; if (tmpClass.InFile.Package != "mx.builtin" && tmpClass.InFile.Package != "fx.builtin") mix.Add(new HtmlAttributeItem("id", "String", null, ns)); @@ -275,11 +319,16 @@ private static bool GetTagAttributes(ClassModel tagClass, List 0 && (member.Flags & mask) > 0 @@ -289,17 +338,15 @@ private static bool GetTagAttributes(ClassModel tagClass, List 0) { - if (member.Parameters != null && member.Parameters.Count > 0) - mtype = member.Parameters[0].Type; - else mtype = null; + mtype = !member.Parameters.IsNullOrEmpty() ? member.Parameters[0].Type : null; } mix.Add(new HtmlAttributeItem(member.Name, mtype, className, ns)); } - ExploreMetadatas(tmpClass.InFile, mix, excludes, ns); + ExploreMetadatas(tmpClass, mix, excludes, ns, tagClass == tmpClass); tmpClass = tmpClass.Extends; - if (tmpClass != null && tmpClass.InFile.Package == "" && tmpClass.Name == "Object") + if (tmpClass.InFile.Package == "" && tmpClass.Name == "Object") break; // members visibility acc = context.TypesAffinity(curClass, tmpClass); @@ -308,22 +355,271 @@ private static bool GetTagAttributes(ClassModel tagClass, List mix, List excludes, string ns) + static List GetTagAttributeValues(ClassModel tagClass, string ns, string attribute) { - if (fileModel == null || fileModel.MetaDatas == null) - return; - ClassModel model = fileModel.GetPublicClass(); - string className = model.IsVoid() ? Path.GetFileNameWithoutExtension(fileModel.FileName) : model.Name; - foreach (ASMetaData meta in fileModel.MetaDatas) + var curClass = mxmlContext.model.GetPublicClass(); + var tmpClass = tagClass; + var mask = FlagType.Variable | FlagType.Setter | FlagType.Getter; + var acc = context.TypesAffinity(curClass, tmpClass); + + if (tmpClass.InFile.Package != "mx.builtin" && tmpClass.InFile.Package != "fx.builtin" && attribute == "id") + return null; + + // Inspectable metadata should be appended to getter types, and according to latest guidelines, the attribute have both a getter and setter + // However, if a component has just a setter I want to autocomplete it if possible, also, the getter or setter may be defined in a super class + bool hasGetterSetter = false; + List metas = null; + string setterType = null; + while (tmpClass != null && !tmpClass.IsVoid()) + { + foreach (MemberModel member in tmpClass.Members) + if ((member.Flags & FlagType.Dynamic) > 0 && (member.Flags & mask) > 0 + && (member.Access & acc) > 0) + { + if (member.Name == attribute) + { + string mtype = member.Type; + + if ((member.Flags & FlagType.Setter) > 0) + { + mtype = !member.Parameters.IsNullOrEmpty() ? member.Parameters[0].Type : null; + if (!hasGetterSetter) + { + hasGetterSetter = true; + setterType = mtype; + continue; + } + return GetAutoCompletionValuesFromInspectable(mtype, metas); + } + + if ((member.Flags & FlagType.Getter) > 0) + { + if (!hasGetterSetter) + { + hasGetterSetter = true; + metas = member.MetaDatas; + continue; + } + return GetAutoCompletionValuesFromInspectable(setterType, metas); + } + + return GetAutoCompletionValuesFromType(mtype); + } + + } + + List retVal; + if (GetAutoCompletionValuesFromMetaData(tmpClass, attribute, tagClass, tmpClass, out retVal)) + return retVal; + + tmpClass = tmpClass.Extends; + if (tmpClass.InFile.Package == "" && tmpClass.Name == "Object") + break; + // members visibility + acc = context.TypesAffinity(curClass, tmpClass); + } + + if (setterType != null) + return GetAutoCompletionValuesFromType(setterType); + + return null; + } + + static List GetAutoCompletionValuesFromInspectable(string type, List metas) + { + if (metas.IsNullOrEmpty()) return GetAutoCompletionValuesFromType(type); + foreach (var meta in metas) + { + if (meta.Name != "Inspectable") continue; + + string enumValues = null; + if (meta.Params.TryGetValue("enumeration", out enumValues)) + { + var retVal = new List(); + foreach (string value in enumValues.Split(',')) + { + var tValue = value.Trim(); + if (tValue.Length != 0) retVal.Add(new HtmlAttributeItem(tValue)); + } + + if (retVal.Count > 0) return retVal; + } + } + + return GetAutoCompletionValuesFromType(type); + } + + static bool GetAutoCompletionValuesFromMetaData(ClassModel model, string attribute, ClassModel tagClass, ClassModel tmpClass, out List result) + { + if (model?.MetaDatas != null) + { + foreach (ASMetaData meta in model.MetaDatas) + { + if (!meta.Params.TryGetValue("name", out var name) || name != attribute) continue; + + string type = null; + switch (meta.Kind) + { + case ASMetaKind.Event: + if (!meta.Params.TryGetValue("type", out var eventType)) eventType = "flash.events.Event"; + result = GetAutoCompletionValuesFromEventType(eventType); + return true; + case ASMetaKind.Style: + if (meta.Params.TryGetValue("inherit", out var inherit) && inherit == "no" && tagClass != tmpClass) + continue; + meta.Params.TryGetValue("type", out type); + break; + case ASMetaKind.Effect: + type = meta.Params["event"]; + break; + case ASMetaKind.Exclude: + break; + case ASMetaKind.Include: // TODO: Check this case... + Debug.Assert(false, "Please, check this case"); + FileModel incModel = ParseInclude(model.InFile, meta); + return GetAutoCompletionValuesFromMetaData(incModel.GetPublicClass(), attribute, tagClass, tmpClass, out result); + } + if (meta.Params.ContainsKey("enumeration")) + { + var retVal = new List(); + foreach (string value in meta.Params["enumeration"].Split(',')) + { + var tValue = value.Trim(); + if (tValue.Length != 0) retVal.Add(new HtmlAttributeItem(tValue)); + } + result = retVal; + + return true; + } + + result = GetAutoCompletionValuesFromType(type); + + return true; + } + } + + result = null; + return false; + } + + static List GetAutoCompletionValuesFromEventType(string type) + { + ClassModel tmpClass = mxmlContext.model.GetPublicClass(); + ClassModel eventClass = context.ResolveType(type, mxmlContext.model); + Visibility acc = Visibility.Default | Visibility.Internal | Visibility.Private | Visibility.Protected | Visibility.Public; + + tmpClass.ResolveExtends(); + eventClass.ResolveExtends(); + + List result = null; + var validTypes = new Dictionary(); + while (!tmpClass.IsVoid()) + { + foreach (MemberModel member in tmpClass.Members) + if ((member.Flags & FlagType.Function) > 0 && (member.Access & acc) > 0 && !member.Parameters.IsNullOrEmpty()) + { + bool validFunction = true; + var argType = member.Parameters[0].Type; + if (argType != type && argType != "Object" && argType != "*" && !validTypes.TryGetValue(argType, out validFunction)) + { + ClassModel argClass = context.ResolveType(argType, tmpClass.InFile); + if (argClass.IsVoid()) + validTypes[argType] = validFunction = false; + else + { + validTypes[argType] = validFunction = (context.TypesAffinity(eventClass, argClass) & Visibility.Protected) > 0; + if (argType != argClass.Type) validTypes[argClass.Type] = validFunction; + } + } + + if (!validFunction) continue; + + for (int i = 1, count = member.Parameters.Count; i < count; i++) + { + if (member.Parameters[i].Value != null) + { + validFunction = false; + break; + } + } + + if (!validFunction) continue; + + result ??= new List(); + result.Add(new MxmlEventHandlerItem(member)); + } + + tmpClass = tmpClass.Extends; + if (tmpClass.InFile.Package == "" && tmpClass.Name == "Object") + break; + // members visibility + // TODO: Take into account namespaces! + acc = Visibility.Protected | Visibility.Public; + } + + return result; + } + + static List GetAutoCompletionValuesFromType(string type) + { + if (type == "Boolean") + { + return new List() + { + new HtmlAttributeItem("true"), + new HtmlAttributeItem("false") + }; + } + + if (type == "Class") + { + ASComplete.HandleAllClassesCompletion(PluginBase.MainForm.CurrentDocument?.SciControl, tokenContext, + true, false); + } + else if (type == "Function") + { + var tmpClass = mxmlContext.model.GetPublicClass(); + var access = Visibility.Default | Visibility.Internal | Visibility.Private | Visibility.Protected | Visibility.Public; + tmpClass.ResolveExtends(); + List result = null; + while (!tmpClass.IsVoid()) + { + foreach (MemberModel member in tmpClass.Members) + if ((member.Flags & FlagType.Function) > 0 && (member.Access & access) > 0) + { + result ??= new List(); + result.Add(new MemberItem(member)); + } + + tmpClass = tmpClass.Extends; + if (tmpClass.InFile.Package == "" && tmpClass.Name == "Object") + break; + // members visibility + // TODO: Take into account namespaces! + access = Visibility.Protected | Visibility.Public; + } + return result; + } + return null; + } + + static void ExploreMetadatas(ClassModel model, ICollection mix, ICollection excludes, string ns, bool isCurrentModel) + { + if (model?.MetaDatas is null) return; + string className = model.IsVoid() ? Path.GetFileNameWithoutExtension(model.InFile.FileName) : model.Name; + foreach (ASMetaData meta in model.MetaDatas) { string add = null; string type = null; switch (meta.Kind) { case ASMetaKind.Event: add = ":e"; break; - case ASMetaKind.Style: - add = ":s"; - if (meta.Params != null) type = meta.Params["type"]; + case ASMetaKind.Style: + if (meta.Params is null || !meta.Params.TryGetValue("inherit", out var inherit) || inherit != "no" || isCurrentModel) + { + add = ":s"; + if (meta.Params is null || !meta.Params.TryGetValue("type", out type)) type = "Object"; + } break; case ASMetaKind.Effect: add = ":x"; @@ -333,8 +629,8 @@ private static void ExploreMetadatas(FileModel fileModel, List nss = mxmlContext.namespaces; - MemberList allClasses = context.GetAllProjectClasses(); - Dictionary packages = new Dictionary(); + var nss = mxmlContext.namespaces; + var allClasses = context.GetAllProjectClasses(); + var packages = new Dictionary(); allTags = new Dictionary>(); foreach (string key in nss.Keys) { string uri = nss[key]; - if (uri.EndsWith(".*")) + if (uri.EndsWithOrdinal(".*")) packages[uri.Substring(0, uri.LastIndexOf('.') + 1)] = key; else if (uri == "*") packages["*"] = key; @@ -448,8 +744,8 @@ private static void GetAllTags() continue; p = model.Type.LastIndexOf('.'); - string pkg = model.Type.Substring(0, p + 1); - if (pkg == "") pkg = "*"; + var pkg = model.Type.Substring(0, p + 1); + if (pkg.Length == 0) pkg = "*"; if (packages.ContainsKey(pkg)) { string ns = packages[pkg]; @@ -460,7 +756,7 @@ private static void GetAllTags() foreach (MxmlCatalog cat in mxmlContext.catalogs) { - List cls = allTags.ContainsKey(cat.NS) ? allTags[cat.NS] : new List(); + var cls = allTags.ContainsKey(cat.NS) ? allTags[cat.NS] : new List(); cls.AddRange(cat.Keys); allTags[cat.NS] = cls; } @@ -468,10 +764,10 @@ private static void GetAllTags() public static string ResolveType(MxmlFilterContext ctx, string tag) { - if (tag == null || ctx == null) return "void"; + if (tag is null || ctx is null) return "void"; int p = tag.IndexOf(':'); if (p < 0) return ResolveType(ctx, "*", tag); - else return ResolveType(ctx, tag.Substring(0, p), tag.Substring(p + 1)); + return ResolveType(ctx, tag.Substring(0, p), tag.Substring(p + 1)); } public static string ResolveType(MxmlFilterContext ctx, string ns, string name) @@ -482,7 +778,7 @@ public static string ResolveType(MxmlFilterContext ctx, string ns, string name) string uri = ctx.namespaces[ns]; if (uri == "*") return name; - if (uri.EndsWith(".*")) + if (uri.EndsWithOrdinal(".*")) return uri.Substring(0, uri.Length - 1) + name; if (uri == MxmlFilter.BETA_MX || uri == MxmlFilter.OLD_MX) @@ -496,16 +792,14 @@ public static string ResolveType(MxmlFilterContext ctx, string ns, string name) return name; } - private static ASResult ResolveAttribute(ClassModel model, string word) + static ASResult ResolveAttribute(ClassModel model, string word) { - ASResult result = new ASResult(); - ClassModel curClass = mxmlContext.model.GetPublicClass(); - ClassModel tmpClass = model; - Visibility acc = context.TypesAffinity(curClass, tmpClass); - List excludes = new List(); + var result = new ASResult(); + var curClass = mxmlContext.model.GetPublicClass(); + var tmpClass = model; + var acc = context.TypesAffinity(curClass, tmpClass); tmpClass.ResolveExtends(); - - while (tmpClass != null && !tmpClass.IsVoid()) + while (!tmpClass.IsVoid()) { foreach (MemberModel member in tmpClass.Members) if ((member.Flags & FlagType.Dynamic) > 0 && (member.Access & acc) > 0 @@ -519,7 +813,7 @@ private static ASResult ResolveAttribute(ClassModel model, string word) if (result.InFile.Classes.Count > 0) { result.InClass = result.InFile.Classes[0]; - result.Member = result.InClass.Members.Search(member.Name, member.Flags, 0); + result.Member = result.InClass.Members.Search(member.Name, member.Flags); } } else result.Member = member; @@ -529,7 +823,7 @@ private static ASResult ResolveAttribute(ClassModel model, string word) // TODO inspect metadata & includes tmpClass = tmpClass.Extends; - if (tmpClass != null && tmpClass.InFile.Package == "" && tmpClass.Name == "Object") + if (tmpClass.InFile.Package == "" && tmpClass.Name == "Object") break; // members visibility acc = context.TypesAffinity(curClass, tmpClass); @@ -541,31 +835,55 @@ private static ASResult ResolveAttribute(ClassModel model, string word) class MXMLListItemComparer : IComparer { - public int Compare(ICompletionListItem a, ICompletionListItem b) { string a1; string b1; if (a.Label.Equals(b.Label, StringComparison.OrdinalIgnoreCase)) { - int c = String.Compare("a", "b"); if (a is HtmlAttributeItem && b is HtmlTagItem) return 1; - else if (b is HtmlAttributeItem && a is HtmlTagItem) return -1; + if (b is HtmlAttributeItem && a is HtmlTagItem) return -1; } - if (a is IHtmlCompletionListItem) + if (a is IHtmlCompletionListItem aItem) { - a1 = ((IHtmlCompletionListItem)a).Name; - if (a.Value.StartsWith("mx:")) a1 += "z"; // push down mx: tags + a1 = aItem.Name; + if (aItem.Value.StartsWithOrdinal("mx:")) a1 += "z"; // push down mx: tags } else a1 = a.Label; - if (b is IHtmlCompletionListItem) + if (b is IHtmlCompletionListItem bItem) { - b1 = ((IHtmlCompletionListItem)b).Name; - if (b.Value.StartsWith("mx:")) b1 += "z"; // push down mx: tags + b1 = bItem.Name; + if (bItem.Value.StartsWithOrdinal("mx:")) b1 += "z"; // push down mx: tags } else b1 = b.Label; return string.Compare(a1, b1); } } + + #region completion list + /// + /// Event member completion list item + /// + public class MxmlEventHandlerItem : ICompletionListItem + { + readonly MemberModel member; + readonly int icon; + + public MxmlEventHandlerItem(MemberModel oMember) + { + member = oMember; + icon = PluginUI.GetIcon(member.Flags, member.Access); + } + + public string Label => member.FullName; + + public string Description => ClassModel.MemberDeclaration(member) + ASDocumentation.GetTipDetails(member, null); + + public Bitmap Icon => (Bitmap)ASContext.Panel.GetIcon(icon); + + public string Value => member.Name + "(event)"; + } + #endregion + } diff --git a/External/Plugins/AS3Context/MxmlFilter.cs b/External/Plugins/AS3Context/MxmlFilter.cs index 58ed8fe07e..0d10403dfe 100644 --- a/External/Plugins/AS3Context/MxmlFilter.cs +++ b/External/Plugins/AS3Context/MxmlFilter.cs @@ -1,14 +1,13 @@ using System; using System.Collections.Generic; -using System.Text; -using ASCompletion.Model; using System.IO; +using System.Text; using System.Text.RegularExpressions; -using ASCompletion.Context; using System.Xml; -using ProjectManager.Projects.AS3; +using ASCompletion.Model; using PluginCore; using PluginCore.Helpers; +using ProjectManager.Projects.AS3; namespace AS3Context { @@ -25,104 +24,91 @@ class MxmlFilterContext #region MXML Filter class MxmlFilter { - static private readonly Regex tagName = new Regex("<(?[a-z][a-z0-9_:]*)[\\s>]", RegexOptions.Compiled | RegexOptions.IgnoreCase); - static public string OLD_MX = "http://www.adobe.com/2006/mxml"; - static public string BETA_MX = "library://ns.adobe.com/flex/halo"; - static public string NEW_MX = "library://ns.adobe.com/flex/mx"; + static readonly Regex tagName = new Regex("<(?[a-z][a-z0-9_:]*)[\\s>]", RegexOptions.Compiled | RegexOptions.IgnoreCase); + public static string OLD_MX = "http://www.adobe.com/2006/mxml"; + public static string BETA_MX = "library://ns.adobe.com/flex/halo"; + public static string NEW_MX = "library://ns.adobe.com/flex/mx"; - static private Dictionary catalogs = new Dictionary(); - static private Dictionary archive = new Dictionary(); + static readonly List catalogs = new List(); + static readonly Dictionary archive = new Dictionary(); /// /// Reset catalogs for new classpath definition /// - static public void ClearCatalogs() - { - // keep catalogs in memory - foreach (string key in catalogs.Keys) - if (!archive.ContainsKey(key)) archive[key] = catalogs[key]; - - catalogs.Clear(); - } + public static void ClearCatalogs() => catalogs.Clear(); /// /// Look in current project configuration for user-defined namespaces /// - static public void AddProjectManifests() + public static void AddProjectManifests() { - AS3Project project = PluginBase.CurrentProject as AS3Project; - if (project != null) + var project = PluginBase.CurrentProject as AS3Project; + //-compiler.namespaces.namespace http://e4xu.googlecode.com run\manifest.xml + if (project?.CompilerOptions.Additional is null) return; + foreach (var line in project.CompilerOptions.Additional) { - //-compiler.namespaces.namespace http://e4xu.googlecode.com run\manifest.xml - if (project.CompilerOptions.Additional != null) - foreach (string line in project.CompilerOptions.Additional) - { - string temp = line.Trim(); - if (temp.StartsWith("-compiler.namespaces.namespace") || temp.StartsWith("-namespace")) - { - int p = temp.IndexOf(' '); - if (p < 0) p = temp.IndexOf('='); - if (p < 0) continue; - temp = temp.Substring(p + 1).Trim(); - p = temp.IndexOf(' '); - if (p < 0) p = temp.IndexOf(','); - if (p < 0) continue; - string uri = temp.Substring(0, p); - string path = temp.Substring(p + 1).Trim(); - if (path.StartsWith("\"")) path = path.Substring(1, path.Length - 2); - AddManifest(uri, PathHelper.ResolvePath(path, project.Directory)); - } - } + var temp = line.Trim(); + if (temp.StartsWithOrdinal("-compiler.namespaces.namespace") || temp.StartsWithOrdinal("-namespace")) + { + int p = temp.IndexOf(' '); + if (p < 0) p = temp.IndexOf('='); + if (p < 0) continue; + temp = temp.Substring(p + 1).Trim(); + p = temp.IndexOf(' '); + if (p < 0) p = temp.IndexOf(','); + if (p < 0) continue; + string uri = temp.Substring(0, p); + string path = temp.Substring(p + 1).Trim(); + if (path.StartsWith('\"')) path = path.Substring(1, path.Length - 2); + AddManifest(uri, PathHelper.ResolvePath(path, project.Directory)); + } } } /// /// Check if a catalog was already extracted from indicated SWC /// - static public bool HasCatalog(string file) - { - return archive.ContainsKey(file); - } + public static bool HasCatalog(string file) => archive.ContainsKey(file); /// /// Read a SWC catalog file /// - static public void AddCatalog(string file, byte[] rawData) + public static void AddCatalogs(string file, byte[] rawData) { try { FileInfo info = new FileInfo(file); - MxmlCatalog cat; + MxmlCatalogs cat; if (HasCatalog(file)) { cat = archive[file]; if (cat.TimeStamp == info.LastWriteTime) { if (cat.Count > 0) - catalogs[file] = cat; + catalogs.AddRange(cat.Values); return; } } - - cat = new MxmlCatalog(); + + cat = new MxmlCatalogs(); cat.Read(file, rawData); cat.TimeStamp = info.LastWriteTime; - + archive[file] = cat; if (cat.Count > 0) - catalogs[file] = cat; + catalogs.AddRange(cat.Values); } catch (XmlException ex) { Console.WriteLine(ex.Message); } - catch (Exception) { } + catch { } } /// /// Add an archived SWC catalog /// - static public void AddCatalog(string file) + public static void AddCatalog(string file) { - MxmlCatalog cat = archive[file]; + MxmlCatalogs cat = archive[file]; if (cat.Count > 0) - catalogs[file] = cat; + catalogs.AddRange(cat.Values); } /// @@ -130,33 +116,32 @@ static public void AddCatalog(string file) /// /// /// - static public void AddManifest(string uri, string file) + public static void AddManifest(string uri, string file) { try { FileInfo info = new FileInfo(file); - MxmlCatalog cat; + MxmlCatalogs cat; if (archive.ContainsKey(file)) { cat = archive[file]; if (cat.TimeStamp == info.LastWriteTime) { if (cat.Count > 0) - catalogs[file] = cat; + catalogs.AddRange(cat.Values); return; } } - cat = new MxmlCatalog(); - cat.URI = uri; + cat = new MxmlCatalogs(); cat.TimeStamp = info.LastWriteTime; - cat.Read(file, null); - + cat.Read(file, null, uri); + archive[file] = cat; if (cat.Count > 0) - catalogs[file] = cat; + catalogs.AddRange(cat.Values); } catch (XmlException ex) { Console.WriteLine(ex.Message); } - catch (Exception) { } + catch { } } /// @@ -165,7 +150,7 @@ static public void AddManifest(string uri, string file) /// /// /// - static public string FilterSource(string name, string src, MxmlFilterContext ctx) + public static string FilterSource(string name, string src, MxmlFilterContext ctx) { List as3ranges = ctx.as3ranges; MemberList mxmlMembers = ctx.mxmlMembers; @@ -215,7 +200,8 @@ static public string FilterSource(string name, string src, MxmlFilterContext ctx i += 3; continue; } - else if (src[i + 2] == '[' && src.Substring(i + 2, 7) == "[CDATA[") + + if (src[i + 2] == '[' && src.Substring(i + 2, 7) == "[CDATA[") { i += 8; skip = false; @@ -231,7 +217,7 @@ static public string FilterSource(string name, string src, MxmlFilterContext ctx if (firstNode && src[i + 1] != '?') { - int space = src.IndexOfAny(new char[] { ' ', '\n' }, i); + int space = src.IndexOfAny(new[] { ' ', '\n' }, i); string tag = GetXMLContextTag(src, space); if (tag != null && space > 0) { @@ -293,17 +279,17 @@ static public string FilterSource(string name, string src, MxmlFilterContext ctx return sb.ToString(); } - private static void ReadNamespaces(MxmlFilterContext ctx, string src, int i) + static void ReadNamespaces(MxmlFilterContext ctx, string src, int i) { // declared ns int len = src.Length; while (i < len) { string name = GetAttributeName(src, ref i); - if (name == null) break; + if (name is null) break; string value = GetAttributeValue(src, ref i); - if (value == null) break; - if (name.StartsWith("xmlns")) + if (value is null) break; + if (name.StartsWithOrdinal("xmlns")) { string[] qname = name.Split(':'); if (qname.Length == 1) ctx.namespaces["*"] = value; @@ -314,9 +300,9 @@ private static void ReadNamespaces(MxmlFilterContext ctx, string src, int i) foreach (string ns in ctx.namespaces.Keys) { string uri = ctx.namespaces[ns]; - string temp = (uri == OLD_MX || uri == BETA_MX) ? NEW_MX : uri; - foreach (MxmlCatalog cat in catalogs.Values) - if (cat.URI == temp) + if (uri == OLD_MX || uri == BETA_MX) uri = NEW_MX; + foreach (MxmlCatalog cat in catalogs) + if (cat.URI == uri) { cat.NS = ns; ctx.catalogs.Add(cat); @@ -327,24 +313,24 @@ private static void ReadNamespaces(MxmlFilterContext ctx, string src, int i) /// /// Get the attribute name /// - private static string GetAttributeName(string src, ref int i) + static string GetAttributeName(string src, ref int i) { string name = ""; - char c; int oldPos = 0; int len = src.Length; bool skip = true; while (i < len) { - c = src[i++]; + var c = src[i++]; if (c == '>') return null; if (skip && c > 32) skip = false; if (c == '=') { if (!skip) return name; - else break; + break; } - else if (!skip && c > 32) name += c; + + if (!skip && c > 32) name += c; } i = oldPos; return null; @@ -353,21 +339,20 @@ private static string GetAttributeName(string src, ref int i) /// /// Get the attribute value /// - private static string GetAttributeValue(string src, ref int i) + static string GetAttributeValue(string src, ref int i) { string value = ""; - char c; int oldPos = i; int len = src.Length; bool skip = true; while (i < len) { - c = src[i++]; + var c = src[i++]; if (c == 10 || c == 13) break; if (c == '"') { if (!skip) return value; - else skip = false; + skip = false; } else if (!skip) value += c; } @@ -378,7 +363,7 @@ private static string GetAttributeValue(string src, ref int i) /// /// Gets the xml context tag /// - private static string GetXMLContextTag(string src, int position) + static string GetXMLContextTag(string src, int position) { if (position < 0) return null; StringBuilder sb = new StringBuilder(); @@ -396,7 +381,7 @@ private static string GetXMLContextTag(string src, int position) string tag = sb.ToString(); Match mTag = tagName.Match(tag + " "); if (mTag.Success) return mTag.Groups["name"].Value; - else return null; + return null; } /// @@ -405,13 +390,13 @@ private static string GetXMLContextTag(string src, int position) /// /// /// - static public void FilterSource(FileModel model, MxmlFilterContext ctx) + public static void FilterSource(FileModel model, MxmlFilterContext ctx) { ctx.model = model; model.InlinedIn = "xml"; model.InlinedRanges = ctx.as3ranges; - if (model.MetaDatas == null) model.MetaDatas = new List(); + model.MetaDatas ??= new List(); foreach (string key in ctx.namespaces.Keys) { ASMetaData meta = new ASMetaData("Namespace"); @@ -420,23 +405,23 @@ static public void FilterSource(FileModel model, MxmlFilterContext ctx) model.MetaDatas.Add(meta); } - ClassModel aClass = model.GetPublicClass(); + var aClass = model.GetPublicClass(); if (aClass == ClassModel.VoidClass) return; aClass.Comments = "<" + ctx.baseTag + "/>"; - Dictionary resolved = new Dictionary(); - foreach (MemberModel mxmember in ctx.mxmlMembers) + var resolved = new Dictionary(); + foreach (var mxmember in ctx.mxmlMembers) { - string tag = mxmember.Type; - string type = null; + var tag = mxmember.Type; + string type; if (resolved.ContainsKey(tag)) type = resolved[tag]; else { type = MxmlComplete.ResolveType(ctx, tag); resolved[tag] = type; } - MemberModel member = aClass.Members.Search(mxmember.Name, FlagType.Variable, Visibility.Public); + var member = aClass.Members.Search(mxmember.Name, FlagType.Variable, Visibility.Public); if (member != null) { member.Comments = "<" + tag + "/>"; @@ -448,36 +433,49 @@ static public void FilterSource(FileModel model, MxmlFilterContext ctx) #endregion #region Catalogs - class MxmlCatalog : Dictionary + class MxmlCatalogs : Dictionary { - public string URI; - public string NS; + public string FileName; public DateTime TimeStamp; - public void Read(string fileName, byte[] rawData) + public void Read(string fileName, byte[] rawData) => Read(fileName, rawData, null); + + public void Read(string fileName, byte[] rawData, string defaultURI) { - XmlReader reader; - if (rawData == null) reader = new XmlTextReader(fileName); - else reader = new XmlTextReader(new MemoryStream(rawData)); + FileName = fileName; + using XmlReader reader = rawData is null + ? new XmlTextReader(fileName) + : new XmlTextReader(new MemoryStream(rawData)); + MxmlCatalog cat = null; reader.MoveToContent(); while (reader.Read()) { - if (reader.NodeType == XmlNodeType.Element - && reader.Name == "component") + if (reader.NodeType == XmlNodeType.Element && reader.Name == "component") { - string className = reader.GetAttribute("className") ?? reader.GetAttribute("class"); - string name = reader.GetAttribute("name") ?? reader.GetAttribute("id"); - string uri = reader.GetAttribute("uri"); - - this[name] = className.Replace(':', '.'); - if (URI == null) URI = uri; + var className = reader.GetAttribute("className") ?? reader.GetAttribute("class"); + var name = reader.GetAttribute("name") ?? reader.GetAttribute("id"); + var uri = reader.GetAttribute("uri") ?? defaultURI; + if (uri == MxmlFilter.BETA_MX || uri == MxmlFilter.OLD_MX) uri = MxmlFilter.NEW_MX; + if (cat is null || cat.URI != uri) + { + if (ContainsKey(uri)) cat = this[uri]; + else + { + cat = new MxmlCatalog {URI = uri}; + Add(uri, cat); + } + } + cat[name] = className.Replace(':', '.'); } } - - if (URI == MxmlFilter.BETA_MX || URI == MxmlFilter.OLD_MX) - URI = MxmlFilter.NEW_MX; } } + + class MxmlCatalog : Dictionary + { + public string URI; + public string NS; + } #endregion } diff --git a/External/Plugins/AS3Context/PluginMain.cs b/External/Plugins/AS3Context/PluginMain.cs index 809a763ec6..b4897f1ab9 100644 --- a/External/Plugins/AS3Context/PluginMain.cs +++ b/External/Plugins/AS3Context/PluginMain.cs @@ -1,103 +1,77 @@ using System; -using System.IO; -using System.Text; -using System.ComponentModel; using System.Collections.Generic; +using System.ComponentModel; +using System.Drawing; +using System.Globalization; +using System.IO; using System.Text.RegularExpressions; -using PluginCore.Localization; +using System.Windows.Forms; +using AS3Context.Compiler; +using AS3Context.Controls; +using ASCompletion.Commands; +using ASCompletion.Completion; +using ASCompletion.Context; +using ASCompletion.Model; +using PluginCore; using PluginCore.Helpers; +using PluginCore.Localization; using PluginCore.Managers; using PluginCore.Utilities; -using AS3Context.Compiler; -using ASCompletion.Model; -using ASCompletion.Completion; -using ASCompletion.Commands; -using AS3Context.Controls; +using SwfOp; using WeifenLuo.WinFormsUI.Docking; -using System.Windows.Forms; -using PluginCore; namespace AS3Context { public class PluginMain : IPlugin, InstalledSDKOwner { - private String pluginName = "AS3Context"; - private String pluginGuid = "ccf2c534-db6b-4c58-b90e-cd0b837e61c4"; - private String pluginHelp = "www.flashdevelop.org/community/"; - private String pluginDesc = "ActionScript 3 context for the ASCompletion engine."; - private String pluginAuth = "FlashDevelop Team"; - static private AS3Settings settingObject; - private Context contextInstance; - private String settingFilename; - private bool inMXML; - private System.Drawing.Image pluginIcon; - private ProfilerUI profilerUI; - private DockContent profilerPanel; - private ToolStripButton viewButton; + Context contextInstance; + string settingFilename; + bool inMXML; + Image pluginIcon; + ProfilerUI profilerUI; + DockContent profilerPanel; + ToolStripButton viewButton; #region Required Properties /// /// Api level of the plugin /// - public Int32 Api - { - get { return 1; } - } + public int Api => 1; /// /// Name of the plugin /// - public String Name - { - get { return this.pluginName; } - } + public string Name { get; } = nameof(AS3Context); /// /// GUID of the plugin /// - public String Guid - { - get { return this.pluginGuid; } - } + public string Guid { get; } = "ccf2c534-db6b-4c58-b90e-cd0b837e61c4"; /// /// Author of the plugin /// - public String Author - { - get { return this.pluginAuth; } - } + public string Author { get; } = "FlashDevelop Team"; /// /// Description of the plugin /// - public String Description - { - get { return this.pluginDesc; } - } + public string Description { get; set; } = "ActionScript 3 context for the ASCompletion engine."; /// /// Web address for help /// - public String Help - { - get { return this.pluginHelp; } - } + public string Help { get; } = "https://www.flashdevelop.org/community/"; /// /// Object that contains the settings /// [Browsable(false)] - Object IPlugin.Settings - { - get { return settingObject; } - } + object IPlugin.Settings => Settings; + + public static AS3Settings Settings { get; set; } - static public AS3Settings Settings - { - get { return settingObject as AS3Settings; } - } #endregion #region Required Methods @@ -107,11 +81,11 @@ static public AS3Settings Settings /// public void Initialize() { - this.InitBasics(); - this.LoadSettings(); - this.CreatePanels(); - this.CreateMenuItems(); - this.AddEventHandlers(); + InitBasics(); + LoadSettings(); + CreatePanels(); + CreateMenuItems(); + AddEventHandlers(); } /// @@ -120,95 +94,85 @@ public void Initialize() public void Dispose() { FlexDebugger.Stop(); - if (profilerUI != null) profilerUI.Cleanup(); - this.SaveSettings(); + profilerUI?.Cleanup(); + SaveSettings(); } /// /// Handles the incoming events /// - public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority priority) + public void HandleEvent(object sender, NotifyEvent e, HandlingPriority priority) { if (priority == HandlingPriority.Low) { switch (e.Type) { case EventType.ProcessArgs: - TextEvent te = e as TextEvent; - if (te.Value.IndexOf("$(FlexSDK)") >= 0) + var te = (TextEvent) e; + if (te.Value.Contains("$(FlexSDK)")) { te.Value = te.Value.Replace("$(FlexSDK)", contextInstance.GetCompilerPath()); } break; case EventType.Command: - DataEvent de = e as DataEvent; - string action = de.Action; - if (action == "ProjectManager.OpenVirtualFile") - { - if (PluginBase.CurrentProject != null && PluginBase.CurrentProject.Language == "as3") - e.Handled = OpenVirtualFileModel(de.Data as String); - } - else if (!(settingObject as AS3Settings).DisableFDB && action == "AS3Context.StartDebugger") - { - string workDir = (PluginBase.CurrentProject != null) - ? Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath) - : Environment.CurrentDirectory; - - string flexSdk = (settingObject as AS3Settings).GetDefaultSDK().Path; - - // if the default sdk is not defined ask for project sdk - if (String.IsNullOrEmpty(flexSdk)) - { - flexSdk = PluginBase.MainForm.ProcessArgString("$(CompilerPath)"); - } - e.Handled = FlexDebugger.Start(workDir, flexSdk, null); - } - else if (action == "AS3Context.StartProfiler") + var de = (DataEvent) e; + var action = de.Action; + switch (action) { - if (profilerUI.AutoStart) profilerUI.StartProfiling(); + case "ProjectManager.Project": + FlexShells.Instance.Stop(); // clear + break; + case "ProjectManager.OpenVirtualFile": + if (PluginBase.CurrentProject?.Language == "as3") e.Handled = OpenVirtualFileModel((string) de.Data); + break; + case "AS3Context.StartDebugger" when !Settings.DisableFDB: + var workDir = PluginBase.CurrentProject != null + ? Path.GetDirectoryName(PluginBase.CurrentProject.ProjectPath) + : Environment.CurrentDirectory; + var flexSdk = Settings.GetDefaultSDK().Path; + // if the default sdk is not defined ask for project sdk + if (string.IsNullOrEmpty(flexSdk)) flexSdk = PluginBase.MainForm.ProcessArgString("$(CompilerPath)"); + e.Handled = FlexDebugger.Start(workDir, flexSdk, null); + break; + case "AS3Context.StartProfiler": + if (profilerUI.AutoStart) profilerUI.StartProfiling(); + break; } break; case EventType.Keys: if (inMXML) { - KeyEvent ke = e as KeyEvent; - if (ke.Value == PluginBase.MainForm.GetShortcutItemKeys("SearchMenu.GotoDeclaration")) + var ke = (KeyEvent) e; + if (ke.Value == PluginBase.MainForm.GetShortcutItemKeys("SearchMenu.GotoDeclaration") && MxmlComplete.GotoDeclaration()) { - if (MxmlComplete.GotoDeclaration()) - { - ke.Handled = true; - ke.ProcessKey = false; - } + ke.Handled = true; + ke.ProcessKey = false; } } break; } return; } - - else if (priority == HandlingPriority.Normal) + if (priority == HandlingPriority.Normal) { switch (e.Type) { case EventType.UIStarted: - contextInstance = new Context(settingObject); + contextInstance = new Context(Settings); ValidateSettings(); AddToolbarItems(); // Associate this context with AS3 language - ASCompletion.Context.ASContext.RegisterLanguage(contextInstance, "as3"); - ASCompletion.Context.ASContext.RegisterLanguage(contextInstance, "mxml"); + ASContext.RegisterLanguage(contextInstance, "as3"); + ASContext.RegisterLanguage(contextInstance, "mxml"); break; - case EventType.FileSave: case EventType.FileSwitch: - if (contextInstance != null) contextInstance.OnFileOperation(e); - - if (PluginBase.MainForm.CurrentDocument.IsEditable) + contextInstance?.OnFileOperation(e); + if (PluginBase.MainForm.CurrentDocument is {FileName: { } fileName}) { - string ext = Path.GetExtension(PluginBase.MainForm.CurrentDocument.FileName); - inMXML = (ext.ToLower() == ".mxml"); + inMXML = Path.GetExtension(fileName).ToLower() == ".mxml"; MxmlComplete.IsDirty = true; } else inMXML = false; @@ -216,103 +180,90 @@ public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority priority) } return; } - - else if (priority == HandlingPriority.High) + if (priority == HandlingPriority.High) { if (e.Type == EventType.Command) { - string action = (e as DataEvent).Action; + var action = ((DataEvent) e).Action; if (action == "ProjectManager.Project") { FlexDebugger.Stop(); - IProject project = PluginBase.CurrentProject; - viewButton.Enabled = project == null || project.Language == "as3" || project.Language == "haxe"; + var project = PluginBase.CurrentProject; + viewButton.Enabled = project is null || project.Language == "as3" || project.Language == "haxe"; } - else if (action.StartsWith("FlashViewer.")) + else if (action.StartsWithOrdinal("FlashViewer.")) { - if (action == "FlashViewer.Closed") - { - FlexDebugger.Stop(); - } - else if (action == "FlashViewer.External" || action == "FlashViewer.Default" - || action == "FlashViewer.Popup" || action == "FlashViewer.Document") + switch (action) { - if (PluginBase.CurrentProject != null - && PluginBase.CurrentProject.EnableInteractiveDebugger) - { - DataEvent de = new DataEvent(EventType.Command, "AS3Context.StartProfiler", null); - EventManager.DispatchEvent(this, de); - - if (PluginBase.CurrentProject.TraceEnabled) + case "FlashViewer.Closed": + FlexDebugger.Stop(); + break; + case "FlashViewer.External": + case "FlashViewer.Default": + case "FlashViewer.Popup": + case "FlashViewer.Document": + if (PluginBase.CurrentProject != null && PluginBase.CurrentProject.EnableInteractiveDebugger) { - de = new DataEvent(EventType.Command, "AS3Context.StartDebugger", (e as DataEvent).Data); + var de = new DataEvent(EventType.Command, "AS3Context.StartProfiler", null); EventManager.DispatchEvent(this, de); + if (PluginBase.CurrentProject.TraceEnabled) + { + de = new DataEvent(EventType.Command, "AS3Context.StartDebugger", ((DataEvent) e).Data); + EventManager.DispatchEvent(this, de); + } } - } + break; } } - else if (action == "FlashConnect") - { - ProfilerUI.HandleFlashConnect(sender, (e as DataEvent).Data); - } + else if (action == "FlashConnect") ProfilerUI.HandleFlashConnect(sender, ((DataEvent) e).Data); else if (inMXML) { - DataEvent de = e as DataEvent; - if (de.Action == "XMLCompletion.Element") + var de = (DataEvent) e; + de.Handled = de.Action switch { - de.Handled = MxmlComplete.HandleElement(de.Data); - } - if (de.Action == "XMLCompletion.Namespace") - { - de.Handled = MxmlComplete.HandleNamespace(de.Data); - } - else if (de.Action == "XMLCompletion.CloseElement") - { - de.Handled = MxmlComplete.HandleElementClose(de.Data); - } - else if (de.Action == "XMLCompletion.Attribute") - { - de.Handled = MxmlComplete.HandleAttribute(de.Data); - } + "XMLCompletion.Element" => MxmlComplete.HandleElement(de.Data), + "XMLCompletion.Namespace" => MxmlComplete.HandleNamespace(de.Data), + "XMLCompletion.CloseElement" => MxmlComplete.HandleElementClose(de.Data), + "XMLCompletion.Attribute" => MxmlComplete.HandleAttribute(de.Data), + "XMLCompletion.AttributeValue" => MxmlComplete.HandleAttributeValue(de.Data), + _ => de.Handled + }; } } } } - private bool OpenVirtualFileModel(string virtualPath) + bool OpenVirtualFileModel(string virtualPath) { - int p = virtualPath.IndexOf("::"); + var p = virtualPath.IndexOfOrdinal("::"); if (p < 0) return false; - string container = virtualPath.Substring(0, p); - string ext = Path.GetExtension(container).ToLower(); + var container = virtualPath.Substring(0, p); + var ext = Path.GetExtension(container).ToLower(); if (ext != ".swf" && ext != ".swc" && ext != ".ane") return false; if (!File.Exists(container)) return false; - string fileName = Path.Combine(container, virtualPath.Substring(p + 2).Replace('.', Path.DirectorySeparatorChar)); - PathModel path = new PathModel(container, contextInstance); - SwfOp.ContentParser parser = new SwfOp.ContentParser(path.Path); + var path = new PathModel(container, contextInstance); + var parser = new ContentParser(path.Path); parser.Run(); AbcConverter.Convert(parser, path, contextInstance); - if (path.HasFile(fileName)) + string fileName = Path.Combine(container, virtualPath.Substring(p + 2).Replace('.', Path.DirectorySeparatorChar)); + if (path.TryGetFile(fileName, out var model)) { - FileModel model = path.GetFile(fileName); ASComplete.OpenVirtualFile(model); return true; } int split = fileName.LastIndexOf(Path.DirectorySeparatorChar) + 1; fileName = fileName.Substring(0, split) + "package.as"; - if (path.HasFile(fileName)) + if (path.TryGetFile(fileName, out model)) { - FileModel model = path.GetFile(fileName); ASComplete.OpenVirtualFile(model); return true; } fileName = fileName.Substring(0, split) + "toplevel.as"; - if (path.HasFile(fileName)) + if (path.TryGetFile(fileName, out model)) { - FileModel model = path.GetFile(fileName); ASComplete.OpenVirtualFile(model); return true; } @@ -328,21 +279,20 @@ private bool OpenVirtualFileModel(string virtualPath) /// public void InitBasics() { - String dataPath = Path.Combine(PathHelper.DataDir, "AS3Context"); - if (!Directory.Exists(dataPath)) Directory.CreateDirectory(dataPath); - this.settingFilename = Path.Combine(dataPath, "Settings.fdb"); - this.pluginDesc = TextHelper.GetString("Info.Description"); - this.pluginIcon = PluginBase.MainForm.FindImage("123"); + var path = Path.Combine(PathHelper.DataDir, nameof(AS3Context)); + if (!Directory.Exists(path)) Directory.CreateDirectory(path); + settingFilename = Path.Combine(path, "Settings.fdb"); + Description = TextHelper.GetString("Info.Description"); + pluginIcon = PluginBase.MainForm.FindImage("123"); } /// /// Create dock panels /// - private void CreatePanels() + void CreatePanels() { - profilerUI = new ProfilerUI(); - profilerUI.Text = TextHelper.GetString("Title.Profiler"); - profilerPanel = PluginBase.MainForm.CreateDockablePanel(profilerUI, pluginGuid, pluginIcon, DockState.Hidden); + profilerUI = new ProfilerUI {Text = TextHelper.GetString("Title.Profiler")}; + profilerPanel = PluginBase.MainForm.CreateDockablePanel(profilerUI, Guid, pluginIcon, DockState.Hidden); profilerPanel.VisibleState = DockState.Float; profilerUI.PanelRef = profilerPanel; } @@ -350,27 +300,28 @@ private void CreatePanels() /// /// Create toolbar icons & menu items /// - private void CreateMenuItems() + void CreateMenuItems() { - ToolStripMenuItem menu = PluginBase.MainForm.FindMenuItem("ViewMenu") as ToolStripMenuItem; - if (menu == null) return; + if (!(PluginBase.MainForm.FindMenuItem("ViewMenu") is ToolStripMenuItem menu)) return; - ToolStripMenuItem viewItem = new ToolStripMenuItem(TextHelper.GetString("Label.ViewMenuItem"), pluginIcon, new EventHandler(OpenPanel)); + var viewItem = new ToolStripMenuItem(TextHelper.GetString("Label.ViewMenuItem"), pluginIcon, OpenPanel); PluginBase.MainForm.RegisterShortcutItem("ViewMenu.ShowProfiler", viewItem); menu.DropDownItems.Add(viewItem); viewButton = new ToolStripButton(pluginIcon); - viewButton.ToolTipText = TextHelper.GetString("Label.ViewMenuItem").Replace("&", ""); + viewButton.Name = "ShowProfiler"; + viewButton.ToolTipText = TextHelper.GetStringWithoutMnemonics("Label.ViewMenuItem"); + PluginBase.MainForm.RegisterSecondaryItem("ViewMenu.ShowProfiler", viewButton); viewButton.Click += OpenPanel; } /// /// Insert toolbar item at right position /// - private void AddToolbarItems() + void AddToolbarItems() { ToolStripItem checkSyntax = null; - ToolStrip toolbar = PluginBase.MainForm.ToolStrip; + var toolbar = PluginBase.MainForm.ToolStrip; foreach (ToolStripItem item in toolbar.Items) { if (item.Name == "CheckSyntax") @@ -391,9 +342,9 @@ private void AddToolbarItems() /// /// Opens the plugin panel again if closed /// - public void OpenPanel(object sender, System.EventArgs e) + public void OpenPanel(object sender, EventArgs e) { - if (sender is ToolStripButton && profilerPanel.Visible && profilerPanel.DockState.ToString().IndexOf("AutoHide") < 0) + if (sender is ToolStripButton && profilerPanel.Visible && !profilerPanel.DockState.ToString().Contains("AutoHide")) { profilerPanel.Hide(); } @@ -415,54 +366,42 @@ public void AddEventHandlers() /// public void LoadSettings() { - settingObject = new AS3Settings(); - if (!File.Exists(this.settingFilename)) this.SaveSettings(); - else - { - Object obj = ObjectSerializer.Deserialize(this.settingFilename, settingObject); - settingObject = (AS3Settings)obj; - } - if (settingObject.AS3ClassPath == null) settingObject.AS3ClassPath = @"Library\AS3\intrinsic"; + Settings = new AS3Settings(); + if (!File.Exists(settingFilename)) SaveSettings(); + else Settings = ObjectSerializer.Deserialize(settingFilename, Settings); + Settings.AS3ClassPath ??= @"Library\AS3\intrinsic"; } /// /// Fix some settings values when the context has been created /// - private void ValidateSettings() + void ValidateSettings() { - if (settingObject.InstalledSDKs == null || settingObject.InstalledSDKs.Length == 0 || PluginBase.MainForm.RefreshConfig) + if (Settings.InstalledSDKs.IsNullOrEmpty() || PluginBase.MainForm.RefreshConfig) { - InstalledSDK sdk; - List sdks = new List(); - string includedSDK; - includedSDK = "Tools\\flexsdk"; + var sdks = new List(); + var includedSDK = "Tools\\flexsdk"; if (Directory.Exists(PathHelper.ResolvePath(includedSDK))) { InstalledSDKContext.Current = this; - sdk = new InstalledSDK(this); - sdk.Path = includedSDK; - sdks.Add(sdk); + sdks.Add(new InstalledSDK(this) {Path = includedSDK}); } includedSDK = "Tools\\ascsdk"; if (Directory.Exists(PathHelper.ResolvePath(includedSDK))) { InstalledSDKContext.Current = this; - sdk = new InstalledSDK(this); - sdk.Path = includedSDK; - sdks.Add(sdk); + sdks.Add(new InstalledSDK(this) {Path = includedSDK}); } /* Resolve AppMan Flex SDKs */ - string appManDir = Path.Combine(PathHelper.BaseDir, @"Apps\flexsdk"); + var appManDir = Path.Combine(PathHelper.BaseDir, @"Apps\flexsdk"); if (Directory.Exists(appManDir)) { - string[] versionDirs = Directory.GetDirectories(appManDir); - foreach (string versionDir in versionDirs) + var versionDirs = Directory.GetDirectories(appManDir); + foreach (var versionDir in versionDirs) { if (Directory.Exists(versionDir)) { - sdk = new InstalledSDK(this); - sdk.Path = versionDir; - sdks.Add(sdk); + sdks.Add(new InstalledSDK(this) {Path = versionDir}); } } } @@ -470,14 +409,12 @@ private void ValidateSettings() appManDir = Path.Combine(PathHelper.BaseDir, @"Apps\flexairsdk"); if (Directory.Exists(appManDir)) { - string[] versionDirs = Directory.GetDirectories(appManDir); - foreach (string versionDir in versionDirs) + var versionDirs = Directory.GetDirectories(appManDir); + foreach (var versionDir in versionDirs) { if (Directory.Exists(versionDir)) { - sdk = new InstalledSDK(this); - sdk.Path = versionDir; - sdks.Add(sdk); + sdks.Add(new InstalledSDK(this) {Path = versionDir}); } } } @@ -485,29 +422,27 @@ private void ValidateSettings() appManDir = Path.Combine(PathHelper.BaseDir, @"Apps\ascsdk"); if (Directory.Exists(appManDir)) { - string[] versionDirs = Directory.GetDirectories(appManDir); - foreach (string versionDir in versionDirs) + var versionDirs = Directory.GetDirectories(appManDir); + foreach (var versionDir in versionDirs) { if (Directory.Exists(versionDir)) { - sdk = new InstalledSDK(this); - sdk.Path = versionDir; - sdks.Add(sdk); + sdks.Add(new InstalledSDK(this) {Path = versionDir}); } } } // // TODO: Resolve Apache Flex SDK // - if (settingObject.InstalledSDKs != null) + if (Settings.InstalledSDKs != null) { - char[] slashes = new char[] { '/', '\\' }; - foreach (InstalledSDK oldSdk in settingObject.InstalledSDKs) + char[] slashes = { '/', '\\' }; + foreach (var oldSdk in Settings.InstalledSDKs) { - string oldPath = oldSdk.Path.TrimEnd(slashes); - foreach (InstalledSDK newSdk in sdks) + var oldPath = oldSdk.Path.TrimEnd(slashes); + foreach (var newSdk in sdks) { - string newPath = newSdk.Path.TrimEnd(slashes); + var newPath = newSdk.Path.TrimEnd(slashes); if (newPath.Equals(oldPath, StringComparison.OrdinalIgnoreCase)) { sdks.Remove(newSdk); @@ -515,61 +450,59 @@ private void ValidateSettings() } } } - sdks.InsertRange(0, settingObject.InstalledSDKs); + sdks.InsertRange(0, Settings.InstalledSDKs); + } + Settings.InstalledSDKs = sdks.ToArray(); + } + else + { + foreach (var sdk in Settings.InstalledSDKs) + { + sdk.Validate(); } - settingObject.InstalledSDKs = sdks.ToArray(); } - else foreach (InstalledSDK sdk in settingObject.InstalledSDKs) ValidateSDK(sdk); - settingObject.OnClasspathChanged += SettingObjectOnClasspathChanged; - settingObject.OnInstalledSDKsChanged += settingObjectOnInstalledSDKsChanged; + Settings.OnClasspathChanged += SettingObjectOnClasspathChanged; + Settings.OnInstalledSDKsChanged += SettingObjectOnInstalledSDKsChanged; } /// /// Notify of SDK collection changes /// - void settingObjectOnInstalledSDKsChanged() + void SettingObjectOnInstalledSDKsChanged() { - if (contextInstance != null) - { - DataEvent de = new DataEvent(EventType.Command, "ProjectManager.InstalledSDKsChanged", "as3"); - EventManager.DispatchEvent(contextInstance, de); - if (!de.Handled) contextInstance.BuildClassPath(); - } + if (contextInstance is null) return; + var de = new DataEvent(EventType.Command, "ProjectManager.InstalledSDKsChanged", "as3"); + EventManager.DispatchEvent(contextInstance, de); + if (!de.Handled) contextInstance.BuildClassPath(); } /// /// Update the classpath if an important setting has changed /// - private void SettingObjectOnClasspathChanged() - { - if (contextInstance != null) contextInstance.BuildClassPath(); - } + void SettingObjectOnClasspathChanged() => contextInstance?.BuildClassPath(); /// /// Saves the plugin settings /// - public void SaveSettings() - { - ObjectSerializer.Serialize(this.settingFilename, settingObject); - } + public void SaveSettings() => ObjectSerializer.Serialize(settingFilename, Settings); /// /// Explore the possible locations for the Macromedia Flash IDE classpath /// - static public string FindAuthoringConfigurationPath(string flashPath) + public static string FindAuthoringConfigurationPath(string flashPath) { - if (flashPath == null) + if (flashPath is null) { flashPath = CallFlashIDE.FindFlashIDE(true); - if (flashPath == null) return null; + if (flashPath is null) return null; } - string ext = Path.GetExtension(flashPath).ToLower(); + var ext = Path.GetExtension(flashPath).ToLower(); if (ext == ".exe" || ext == ".bat" || ext == ".cmd") { flashPath = Path.GetDirectoryName(flashPath); } - string basePath = flashPath; - string deflang = System.Globalization.CultureInfo.CurrentUICulture.Name; + var basePath = flashPath; + var deflang = CultureInfo.CurrentUICulture.Name; deflang = deflang.Substring(0, 2); // CS4+ default configuration if (Directory.Exists(basePath + "\\Common\\Configuration\\ActionScript 3.0")) @@ -582,10 +515,10 @@ static public string FindAuthoringConfigurationPath(string flashPath) return basePath + deflang + "\\Configuration\\"; } // look for other languages - else if (Directory.Exists(basePath)) + if (Directory.Exists(basePath)) { - string[] dirs = Directory.GetDirectories(basePath); - foreach (string dir in dirs) + var dirs = Directory.GetDirectories(basePath); + foreach (var dir in dirs) { if (Directory.Exists(dir + "\\Configuration\\ActionScript 3.0")) { @@ -603,20 +536,19 @@ static public string FindAuthoringConfigurationPath(string flashPath) public bool ValidateSDK(InstalledSDK sdk) { sdk.Owner = this; - string path = sdk.Path; - Match mBin = Regex.Match(path, "[/\\\\]bin$", RegexOptions.IgnoreCase); - if (mBin.Success) - sdk.Path = path = path.Substring(0, mBin.Index); - - IProject project = PluginBase.CurrentProject; - if (project != null) - path = PathHelper.ResolvePath(path, Path.GetDirectoryName(project.ProjectPath)); - else - path = PathHelper.ResolvePath(path); + var path = sdk.Path; + if (path is null) return false; + var mBin = Regex.Match(path, "[/\\\\]bin$", RegexOptions.IgnoreCase); + if (mBin.Success) sdk.Path = path = path.Substring(0, mBin.Index); + + var project = PluginBase.CurrentProject; + path = project != null + ? PathHelper.ResolvePath(path, Path.GetDirectoryName(project.ProjectPath)) + : PathHelper.ResolvePath(path); try { - if (path == null || !Directory.Exists(path)) + if (!Directory.Exists(path)) { ErrorManager.ShowInfo("Path not found:\n" + sdk.Path); return false; @@ -628,25 +560,23 @@ public bool ValidateSDK(InstalledSDK sdk) return false; } - string descriptor = Path.Combine(path, "flex-sdk-description.xml"); - if (!File.Exists(descriptor)) - descriptor = Path.Combine(path, "air-sdk-description.xml"); - + var descriptor = Path.Combine(path, "flex-sdk-description.xml"); + if (!File.Exists(descriptor)) descriptor = Path.Combine(path, "air-sdk-description.xml"); if (File.Exists(descriptor)) { - string raw = File.ReadAllText(descriptor); - Match mName = Regex.Match(raw, "([^<]+)"); - Match mVer = Regex.Match(raw, "([^<]+)"); + var raw = File.ReadAllText(descriptor); + var mName = Regex.Match(raw, "([^<]+)"); + var mVer = Regex.Match(raw, "([^<]+)"); if (mName.Success && mVer.Success) { sdk.Name = mName.Groups[1].Value; sdk.Version = mVer.Groups[1].Value; descriptor = Path.Combine(path, "AIR SDK Readme.txt"); - if (sdk.Name.StartsWith("Flex") && File.Exists(descriptor)) + if (sdk.Name.StartsWithOrdinal("Flex") && File.Exists(descriptor)) { raw = File.ReadAllText(descriptor); - Match mAIR = Regex.Match(raw, "Adobe AIR ([0-9.]+) SDK"); + var mAIR = Regex.Match(raw, "Adobe AIR ([0-9.]+) SDK"); if (mAIR.Success) { sdk.Name += ", AIR " + mAIR.Groups[1].Value; @@ -655,14 +585,12 @@ public bool ValidateSDK(InstalledSDK sdk) } return true; } - else ErrorManager.ShowInfo("Invalid SDK descriptor:\n" + descriptor); + ErrorManager.ShowInfo("Invalid SDK descriptor:\n" + descriptor); } else ErrorManager.ShowInfo("No SDK descriptor found:\n" + descriptor); return false; } #endregion - } - -} +} \ No newline at end of file diff --git a/External/Plugins/AS3Context/Properties/AssemblyInfo.cs b/External/Plugins/AS3Context/Properties/AssemblyInfo.cs index 13e02da249..e33473e0bb 100644 --- a/External/Plugins/AS3Context/Properties/AssemblyInfo.cs +++ b/External/Plugins/AS3Context/Properties/AssemblyInfo.cs @@ -1,15 +1,17 @@ using System.Reflection; using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using PluginCore; // Information about this assembly is defined by the following attributes. // Change them to the information which is associated with the assembly you compile. [assembly: AssemblyTitle("AS3Context")] -[assembly: AssemblyDescription("AS3Context Plugin For ASCompletion In FlashDevelop.")] +[assembly: AssemblyDescription("AS3 Context Plugin For ASCompletion In " + DistroConfig.DISTRIBUTION_NAME)] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("FlashDevelop.org")] +[assembly: AssemblyCompany(DistroConfig.DISTRIBUTION_COMPANY)] [assembly: AssemblyProduct("AS3Context")] -[assembly: AssemblyCopyright("FlashDevelop.org 2005-2014")] +[assembly: AssemblyCopyright(DistroConfig.DISTRIBUTION_COPYRIGHT)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.0.0.0")] + +[assembly: InternalsVisibleTo("AS3Context.Tests")] diff --git a/External/Plugins/ASClassWizard/ASClassWizard.csproj b/External/Plugins/ASClassWizard/ASClassWizard.csproj index fbbd350ad0..94878b73cc 100644 --- a/External/Plugins/ASClassWizard/ASClassWizard.csproj +++ b/External/Plugins/ASClassWizard/ASClassWizard.csproj @@ -1,164 +1,90 @@  - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3} - Library - Properties - ASClassWizard - ASClassWizard - - - - - 3.5 - v2.0 - - - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - true - full - false - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - TRACE - prompt - 4 - - - x86 - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - TRACE - true - - - x86 - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - TRACE - true - - - - - - - - - - - - - - - - - - - Form - - - AS3ClassWizard.cs - - - Form - - - ClassBrowser.cs - - - Component - - - Form - - - PackageBrowser.cs - - - - - {61885F70-B4DC-4B44-852D-5D6D03F2A734} - PluginCore - False - - - {74AD0487-CEF9-43FE-9283-BC6F79539ADE} - AS2Context - False - - - {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF} - AS3Context - False - - - {4EBF2653-9654-4E40-880E-0046B3D6210E} - ASCompletion - False - - - {78101C01-E186-4954-B1DD-DEBB7905FAD8} - ProjectManager - False - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - - - - - + + + + Debug + AnyCPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3} + Library + Properties + ASClassWizard + ASClassWizard + net48 + true + false + false + false + + + true + full + false + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + prompt + 4 + 9 + + + none + true + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + prompt + 4 + 9 + + + x86 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + true + 9 + + + x86 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + true + 9 + + + true + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + full + x64 + 9 + prompt + + + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + true + x64 + 9 + prompt + + + + + + + + + {61885F70-B4DC-4B44-852D-5D6D03F2A734} + PluginCore + False + + + {4EBF2653-9654-4E40-880E-0046B3D6210E} + ASCompletion + False + + + {78101C01-E186-4954-B1DD-DEBB7905FAD8} + ProjectManager + False + + \ No newline at end of file diff --git a/External/Plugins/ASClassWizard/Controls/TreeView/SimpleDirectoryNode.cs b/External/Plugins/ASClassWizard/Controls/TreeView/SimpleDirectoryNode.cs index 4c386fbb33..4505508cb9 100644 --- a/External/Plugins/ASClassWizard/Controls/TreeView/SimpleDirectoryNode.cs +++ b/External/Plugins/ASClassWizard/Controls/TreeView/SimpleDirectoryNode.cs @@ -1,9 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; +using System.IO; using System.Windows.Forms; -using System.Diagnostics; namespace ASClassWizard.Controls.TreeView { @@ -15,11 +11,11 @@ class SimpleDirectoryNode : TreeNode public SimpleDirectoryNode(string directory, string path) : base(Path.GetFileName(directory)) { - this.dirty = true; - this.directoryPath = path; + dirty = true; + directoryPath = path; if (Directory.GetDirectories(path).Length > 0) - this.Nodes.Add(new TreeNode("")); + Nodes.Add(new TreeNode("")); } } } diff --git a/External/Plugins/ASClassWizard/PluginMain.cs b/External/Plugins/ASClassWizard/PluginMain.cs index 23cd9a331d..85e684204a 100644 --- a/External/Plugins/ASClassWizard/PluginMain.cs +++ b/External/Plugins/ASClassWizard/PluginMain.cs @@ -1,458 +1,158 @@ -#region imports - using System; using System.IO; -using System.Drawing; -using System.Windows.Forms; using System.ComponentModel; -using System.Diagnostics; using System.Collections; - using PluginCore.Localization; -using PluginCore.Utilities; using PluginCore.Managers; -using PluginCore.Helpers; using PluginCore; - using ProjectManager.Projects; -using ProjectManager.Projects.AS3; -using ProjectManager.Projects.AS2; - -using ASCompletion.Model; using ASCompletion.Context; - -using ASClassWizard.Resources; -using ASClassWizard.Wizards; - -using System.Text.RegularExpressions; using ASCompletion.Completion; using System.Collections.Generic; - -#endregion +using ASClassWizard.Wizards; namespace ASClassWizard { - public class PluginMain : IPlugin - { - private String pluginName = "ASClassWizard"; - private String pluginGuid = "a2c159c1-7d21-4483-aeb1-38d9fdc4c7f3"; - private String pluginHelp = "www.flashdevelop.org/community/"; - private String pluginDesc = "Provides an ActionScript class wizard for FlashDevelop."; - private String pluginAuth = "FlashDevelop Team"; - - private AS3ClassOptions lastFileOptions; - private String lastFileFromTemplate; - private IASContext processContext; - private String processOnSwitch; - private String constructorArgs; - private List constructorArgTypes; - - #region Required Properties + public class PluginMain : IPlugin + { + #region Required Properties /// /// Api level of the plugin /// - public Int32 Api - { - get { return 1; } - } + public int Api => 1; /// /// Name of the plugin /// - public String Name - { - get { return this.pluginName; } - } + public string Name => nameof(ASClassWizard); /// /// GUID of the plugin /// - public String Guid - { - get { return this.pluginGuid; } - } + public string Guid => "a2c159c1-7d21-4483-aeb1-38d9fdc4c7f3"; /// /// Author of the plugin /// - public String Author - { - get { return this.pluginAuth; } - } + public string Author => "FlashDevelop Team"; /// /// Description of the plugin /// - public String Description - { - get { return this.pluginDesc; } - } + public string Description { get; private set; } = "Provides an ActionScript class wizard for FlashDevelop."; /// /// Web address for help /// - public String Help - { - get { return this.pluginHelp; } - } + public string Help => "https://www.flashdevelop.org/community/"; /// /// Object that contains the settings /// [Browsable(false)] - public Object Settings - { - get { return null; } - } - - #endregion - - #region Required Methods + public object Settings => null; + + #endregion + + #region Required Methods - public void Initialize() - { - this.AddEventHandlers(); - this.InitLocalization(); + public void Initialize() + { + AddEventHandlers(); + InitLocalization(); } - - public void Dispose() - { + + public void Dispose() + { // Nothing here... - } - - public void HandleEvent(Object sender, NotifyEvent e, HandlingPriority prority) - { + } + + public void HandleEvent(object sender, NotifyEvent e, HandlingPriority priority) + { Project project; switch (e.Type) { case EventType.Command: - DataEvent evt = (DataEvent)e; - if (evt.Action == "ProjectManager.CreateNewFile") + var de = (DataEvent)e; + if (de.Action == "ProjectManager.CreateNewFile") { - Hashtable table = evt.Data as Hashtable; - project = PluginBase.CurrentProject as Project; - if ((project.Language.StartsWith("as") || project.Language == "haxe") && IsWizardTemplate(table["templatePath"] as String)) + project = (Project) PluginBase.CurrentProject; + if (project.Language.StartsWithOrdinal("as") || project.Language == "haxe") { - evt.Handled = true; - String className = table.ContainsKey("className") ? table["className"] as String : TextHelper.GetString("Wizard.Label.NewClass"); - DisplayClassWizard(table["inDirectory"] as String, table["templatePath"] as String, className, table["constructorArgs"] as String, table["constructorArgTypes"] as List); + var table = (Hashtable) de.Data; + var templateFile = table["templatePath"] as string; + if (WizardContext.IsWizardTemplate(templateFile)) + { + var fileName = Path.GetFileName(templateFile); + var templateType = !string.IsNullOrEmpty(fileName) && fileName.Contains('.', out var p) + ? fileName.Substring(0, p) + : "class"; + if (templateType.Equals("class", StringComparison.OrdinalIgnoreCase)) + { + de.Handled = true; + var inDirectory = (string)table["inDirectory"]; + var typeTemplate = table["GenericTemplate"] as string; + var name = table["className"] as string ?? TextHelper.GetString("Wizard.Label.NewClass"); + var constructorArgs = table["constructorArgs"] as string; + var constructorArgsTypes = table["constructorArgTypes"] as List; + using var dialog = new AS3ClassWizard(); + WizardContext.DisplayWizard(dialog, inDirectory, templateFile, typeTemplate, name, constructorArgs, constructorArgsTypes); + } + else if (templateType.Equals("interface", StringComparison.OrdinalIgnoreCase)) + { + de.Handled = true; + var inDirectory = (string) table["inDirectory"]; + var typeTemplate = table["GenericTemplate"] as string; + var name = table["interfaceName"] as string ?? TextHelper.GetString("Wizard.Label.NewInterface"); + using var dialog = new AS3InterfaceWizard(); + WizardContext.DisplayWizard(dialog, inDirectory, templateFile, typeTemplate, name, null, null); + } + } } } break; case EventType.FileSwitch: - if (PluginBase.MainForm.CurrentDocument.FileName == processOnSwitch) + if (PluginBase.MainForm.CurrentDocument?.FileName == WizardContext.processOnSwitch) { - processOnSwitch = null; - if (lastFileOptions == null || lastFileOptions.interfaces == null) return; - foreach (String cname in lastFileOptions.interfaces) + WizardContext.processOnSwitch = null; + if (WizardContext.lastFileOptions?.interfaces is null) return; + foreach (var it in WizardContext.lastFileOptions.interfaces) { ASContext.Context.CurrentModel.Check(); - ClassModel inClass = ASContext.Context.CurrentModel.GetPublicClass(); - ASGenerator.SetJobContext(null, cname, null, null); + var inClass = ASContext.Context.CurrentModel.GetPublicClass(); + ASGenerator.SetJobContext(null, it, null, null); ASGenerator.GenerateJob(GeneratorJobType.ImplementInterface, null, inClass, null, null); + ASContext.Context.UpdateCurrentFile(false); } - lastFileOptions = null; + WizardContext.lastFileOptions = null; } break; case EventType.ProcessArgs: - TextEvent te = e as TextEvent; project = PluginBase.CurrentProject as Project; - if (lastFileFromTemplate != null && project != null && (project.Language.StartsWith("as") || project.Language == "haxe")) + if (WizardContext.lastFileFromTemplate != null && project != null && (project.Language.StartsWithOrdinal("as") || project.Language == "haxe")) { - te.Value = ProcessArgs(project, te.Value); + var te = (TextEvent) e; + te.Value = WizardContext.ProcessArgs(te.Value); } break; } - } - - private bool IsWizardTemplate(string templateFile) - { - return templateFile != null && File.Exists(templateFile + ".wizard"); } - - #endregion - #region Custom Methods + #endregion - public static IMainForm MainForm { get { return PluginBase.MainForm; } } + #region Custom Methods - public void AddEventHandlers() + void AddEventHandlers() { EventManager.AddEventHandler(this, EventType.Command | EventType.ProcessArgs); EventManager.AddEventHandler(this, EventType.FileSwitch, HandlingPriority.Low); } - public void InitLocalization() - { - this.pluginDesc = TextHelper.GetString("Info.Description"); - } - - private void DisplayClassWizard(String inDirectory, String templateFile, String className, String constructorArgs, List constructorArgTypes) - { - Project project = PluginBase.CurrentProject as Project; - String classpath = project.AbsoluteClasspaths.GetClosestParent(inDirectory) ?? inDirectory; - String package; - try - { - package = GetPackage(classpath, inDirectory); - if (package == "") - { - // search in Global classpath - Hashtable info = new Hashtable(); - info["language"] = project.Language; - DataEvent de = new DataEvent(EventType.Command, "ASCompletion.GetUserClasspath", info); - EventManager.DispatchEvent(this, de); - if (de.Handled && info.ContainsKey("cp")) - { - List cps = info["cp"] as List; - if (cps != null) - { - foreach (string cp in cps) - { - package = GetPackage(cp, inDirectory); - if (package != "") - { - classpath = cp; - break; - } - } - } - } - } - } - catch (System.NullReferenceException) - { - package = ""; - } - AS3ClassWizard dialog = new AS3ClassWizard(); - bool isHaxe = project.Language == "haxe"; - dialog.Project = project; - dialog.Directory = inDirectory; - dialog.StartupClassName = className; - if (package != null) - { - package = package.Replace(Path.DirectorySeparatorChar, '.'); - dialog.StartupPackage = package; - } - if (dialog.ShowDialog() == DialogResult.OK) - { - string cPackage = dialog.getPackage(); - string path = Path.Combine(classpath, dialog.getPackage().Replace('.', Path.DirectorySeparatorChar)); - string newFilePath = Path.ChangeExtension(Path.Combine(path, dialog.getClassName()), isHaxe ? ".hx" : ".as"); - if (File.Exists(newFilePath)) - { - string title = " " + TextHelper.GetString("FlashDevelop.Title.ConfirmDialog"); - string message = TextHelper.GetString("ProjectManager.Info.FolderAlreadyContainsFile"); - DialogResult result = MessageBox.Show(PluginBase.MainForm, string.Format(message, newFilePath, "\n"), title, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); - if (result == DialogResult.Cancel) return; - } - string templatePath = templateFile + ".wizard"; - this.lastFileFromTemplate = newFilePath; - this.constructorArgs = constructorArgs; - this.constructorArgTypes = constructorArgTypes; - lastFileOptions = new AS3ClassOptions( - project.Language, - dialog.getPackage(), - dialog.getSuperClass(), - dialog.hasInterfaces() ? dialog.getInterfaces() : null, - dialog.isPublic(), - dialog.isDynamic(), - dialog.isFinal(), - dialog.getGenerateInheritedMethods(), - dialog.getGenerateConstructor() - ); - - try - { - if (!Directory.Exists(path)) Directory.CreateDirectory(path); - MainForm.FileFromTemplate(templatePath, newFilePath); - } - catch (Exception ex) - { - ErrorManager.ShowError(ex); - } - } - } - - private string GetPackage(string classpath, string path) - { - if (!path.StartsWith(classpath, StringComparison.OrdinalIgnoreCase)) - return ""; - string subPath = path.Substring(classpath.Length).Trim(new char[] { '/', '\\', ' ', '.' }); - return subPath.Replace(Path.DirectorySeparatorChar, '.'); - } - - public string ProcessArgs(Project project, string args) - { - if (lastFileFromTemplate != null) - { - string package = lastFileOptions != null ? lastFileOptions.Package : ""; - string fileName = Path.GetFileNameWithoutExtension(lastFileFromTemplate); - args = args.Replace("$(FileName)", fileName); - if (args.Contains("$(FileNameWithPackage)") || args.Contains("$(Package)")) - { - args = args.Replace("$(Package)", package); - if (package != "") args = args.Replace("$(FileNameWithPackage)", package + "." + fileName); - else args = args.Replace("$(FileNameWithPackage)", fileName); - if (lastFileOptions != null) - { - args = ProcessFileTemplate(args); - if (processOnSwitch == null) lastFileOptions = null; - } - } - lastFileFromTemplate = null; - } - return args; - } - - private string ProcessFileTemplate(string args) - { - Int32 eolMode = (Int32)MainForm.Settings.EOLMode; - String lineBreak = LineEndDetector.GetNewLineMarker(eolMode); - ClassModel cmodel; - List imports = new List(); - string extends = ""; - string implements = ""; - string access = ""; - string inheritedMethods = ""; - string paramString = ""; - string superConstructor = ""; - int index; - // resolve imports - if (lastFileOptions.interfaces != null && lastFileOptions.interfaces.Count > 0) - { - bool isHaxe2 = PluginBase.CurrentSDK != null && PluginBase.CurrentSDK.Name.ToLower().Contains("haxe 2"); - implements = " implements "; - string[] _implements; - index = 0; - foreach (string item in lastFileOptions.interfaces) - { - if (item.Split('.').Length > 1) imports.Add(item); - _implements = item.Split('.'); - implements += (index > 0 ? (isHaxe2 ? ", implements " : ", ") : "") + _implements[_implements.Length - 1]; - if (lastFileOptions.createInheritedMethods) - { - processOnSwitch = lastFileFromTemplate; - // let ASCompletion generate the implementations when file is opened - } - index++; - } - } - if (lastFileOptions.superClass != "") - { - String super = lastFileOptions.superClass; - if (lastFileOptions.superClass.Split('.').Length > 1) imports.Add(super); - string[] _extends = super.Split('.'); - extends = " extends " + _extends[_extends.Length - 1]; - processContext = ASContext.GetLanguageContext(lastFileOptions.Language); - if (lastFileOptions.createConstructor && processContext != null && constructorArgs == null) - { - cmodel = processContext.GetModel(super.LastIndexOf('.') < 0 ? "" : super.Substring(0, super.LastIndexOf('.')), _extends[_extends.Length - 1], ""); - if (!cmodel.IsVoid()) - { - foreach (MemberModel member in cmodel.Members) - { - if (member.Name == cmodel.Constructor) - { - paramString = member.ParametersString(); - AddImports(imports, member, cmodel); - superConstructor = "super("; - index = 0; - if (member.Parameters != null) - foreach (MemberModel param in member.Parameters) - { - if (param.Name.StartsWith(".")) break; - superConstructor += (index > 0 ? ", " : "") + param.Name; - index++; - } - superConstructor += ");\n" + (lastFileOptions.Language == "as3" ? "\t\t\t" : "\t\t"); - break; - } - } - } - } - processContext = null; - } - if (constructorArgs != null) - { - paramString = constructorArgs; - foreach (String type in constructorArgTypes) - { - if (!imports.Contains(type)) - { - imports.Add(type); - } - } - } - if (lastFileOptions.Language == "as3") - { - access = lastFileOptions.isPublic ? "public " : "internal "; - access += lastFileOptions.isDynamic ? "dynamic " : ""; - access += lastFileOptions.isFinal ? "final " : ""; - } - else if (lastFileOptions.Language == "haxe") - { - access = lastFileOptions.isPublic ? "public " : "private "; - access += lastFileOptions.isDynamic ? "dynamic " : ""; - } - else - { - access = lastFileOptions.isDynamic ? "dynamic " : ""; - } - string importsSrc = ""; - string prevImport = null; - imports.Sort(); - foreach (string import in imports) - { - if (prevImport != import) - { - prevImport = import; - if (import.LastIndexOf('.') == -1) continue; - if (import.Substring(0, import.LastIndexOf('.')) == lastFileOptions.Package) continue; - importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + "import " + import + ";" + lineBreak; - } - } - if (importsSrc.Length > 0) - { - importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + lineBreak; - } - args = args.Replace("$(Import)", importsSrc); - args = args.Replace("$(Extends)", extends); - args = args.Replace("$(Implements)", implements); - args = args.Replace("$(Access)", access); - args = args.Replace("$(InheritedMethods)", inheritedMethods); - args = args.Replace("$(ConstructorArguments)", paramString); - args = args.Replace("$(Super)", superConstructor); - return args; - } - - private void AddImports(List imports, MemberModel member, ClassModel inClass) - { - AddImport(imports, member.Type, inClass); - if (member.Parameters != null) - { - foreach (MemberModel item in member.Parameters) - { - AddImport(imports, item.Type, inClass); - } - } - } - - private String AddImport(List imports, String cname, ClassModel inClass) - { - ClassModel aClass = processContext.ResolveType(cname, inClass.InFile); - if (aClass != null && !aClass.IsVoid() && aClass.InFile.Package != "") - { - imports.Add(aClass.QualifiedName); - } - return ""; - } - - #endregion + void InitLocalization() => Description = TextHelper.GetString("Info.Description"); - } - -} + #endregion + } +} \ No newline at end of file diff --git a/External/Plugins/ASClassWizard/Properties/AssemblyInfo.cs b/External/Plugins/ASClassWizard/Properties/AssemblyInfo.cs index 198bf589b3..008e8dbb09 100644 --- a/External/Plugins/ASClassWizard/Properties/AssemblyInfo.cs +++ b/External/Plugins/ASClassWizard/Properties/AssemblyInfo.cs @@ -1,15 +1,14 @@ using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; +using PluginCore; // Information about this assembly is defined by the following attributes. // Change them to the information which is associated with the assembly you compile. [assembly: AssemblyTitle("ASClassWizard")] -[assembly: AssemblyDescription("ActionScript Class Wizard Plugin For FlashDevelop.")] +[assembly: AssemblyDescription("ActionScript Class Wizard Plugin For " + DistroConfig.DISTRIBUTION_NAME)] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("FlashDevelop.org")] +[assembly: AssemblyCompany(DistroConfig.DISTRIBUTION_COMPANY)] [assembly: AssemblyProduct("ASClassWizard")] -[assembly: AssemblyCopyright("FlashDevelop.org 2005-2014")] +[assembly: AssemblyCopyright(DistroConfig.DISTRIBUTION_COPYRIGHT)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("1.0.0.0")] \ No newline at end of file +[assembly: AssemblyVersion("1.0.0.0")] diff --git a/External/Plugins/ASClassWizard/Resources/ASClassOptions.cs b/External/Plugins/ASClassWizard/Resources/ASClassOptions.cs index 421f02269b..cb82bbe9ee 100644 --- a/External/Plugins/ASClassWizard/Resources/ASClassOptions.cs +++ b/External/Plugins/ASClassWizard/Resources/ASClassOptions.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.IO; -using System.Diagnostics; +using System.Collections.Generic; namespace ASClassWizard.Resources { @@ -17,6 +13,8 @@ public class AS3ClassOptions public bool isDynamic; public bool isFinal; public string Language; + // TODO slavara: move to HaxeClassOptions + public string Template; public AS3ClassOptions( string language, @@ -38,7 +36,6 @@ public AS3ClassOptions( isPublic = is_public; isDynamic = is_dynamic; isFinal = is_final; - } } } diff --git a/External/Plugins/ASClassWizard/Settings.cs b/External/Plugins/ASClassWizard/Settings.cs index 33760a8774..5a8c4707c2 100644 --- a/External/Plugins/ASClassWizard/Settings.cs +++ b/External/Plugins/ASClassWizard/Settings.cs @@ -1,8 +1,4 @@ using System; -using System.ComponentModel; -using System.Collections.Generic; -using System.Windows.Forms; -using System.Text; namespace ASClassWizard { @@ -10,5 +6,4 @@ namespace ASClassWizard public class Settings { } - -} +} \ No newline at end of file diff --git a/External/Plugins/ASClassWizard/WizardContext.cs b/External/Plugins/ASClassWizard/WizardContext.cs new file mode 100644 index 0000000000..097efdc946 --- /dev/null +++ b/External/Plugins/ASClassWizard/WizardContext.cs @@ -0,0 +1,322 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Windows.Forms; +using ASClassWizard.Resources; +using ASClassWizard.Wizards; +using ASCompletion.Completion; +using ASCompletion.Context; +using ASCompletion.Model; +using PluginCore; +using PluginCore.Localization; +using PluginCore.Managers; +using PluginCore.Utilities; +using ProjectManager.Projects; + +namespace ASClassWizard +{ + public static class WizardContext + { + + internal static AS3ClassOptions lastFileOptions; + internal static string lastFileFromTemplate; + internal static string processOnSwitch; + internal static string constructorArgs; + internal static List constructorArgTypes; + + public static bool IsWizardTemplate(string templateFile) => templateFile != null && File.Exists(templateFile + ".wizard"); + + public static void DisplayWizard(IWizard dialog, string inDirectory, string templateFile, string typeTemplate, string name, string constructorArgs, List constructorArgTypes) + { + var project = (Project) PluginBase.CurrentProject; + if (ProcessWizard(dialog, inDirectory, name, project, out var path, out var newFilePath)) return; + lastFileFromTemplate = newFilePath; + WizardContext.constructorArgs = constructorArgs; + WizardContext.constructorArgTypes = constructorArgTypes; + lastFileOptions = GetWizardOptions(project, dialog, typeTemplate); + FileFromTemplate(path, templateFile, newFilePath); + } + + public static bool ProcessWizard(IWizard dialog, string inDirectory, string name, Project project, out string path, out string newFilePath) + { + var classpath = project.AbsoluteClasspaths.GetClosestParent(inDirectory); + if (classpath is null) + { + if (project.AdditionalPaths is { } paths) classpath = PathCollection.GetClosestParent(inDirectory, paths); + classpath ??= inDirectory; + } + + var package = GetPackage(project, ref classpath, inDirectory); + dialog.Project = project; + dialog.Directory = inDirectory; + dialog.StartupClassName = name; + package = package.Replace(Path.DirectorySeparatorChar, '.'); + dialog.StartupPackage = package; + + var conflictResult = DialogResult.OK; + var ext = project.DefaultSearchFilter.Split(';').FirstOrDefault() ?? string.Empty; + if (ext.Length > 0) ext = ext.TrimStart('*'); + do + { + if (dialog.ShowDialog() != DialogResult.OK) + { + path = null; + newFilePath = null; + return true; + } + var cPackage = dialog.GetPackage(); + path = Path.Combine(classpath, cPackage.Replace('.', Path.DirectorySeparatorChar)); + newFilePath = Path.ChangeExtension(Path.Combine(path, dialog.GetName()), ext); + if (!File.Exists(newFilePath)) continue; + var title = " " + TextHelper.GetString("FlashDevelop.Title.ConfirmDialog"); + var message = TextHelper.GetString("PluginCore.Info.FolderAlreadyContainsFile"); + conflictResult = MessageBox.Show(PluginBase.MainForm, + string.Format(message, newFilePath, "\n"), title, + MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); + if (conflictResult == DialogResult.No) return true; + } while (conflictResult == DialogResult.Cancel); + return false; + } + + static AS3ClassOptions GetWizardOptions(IProject project, IWizard dialog, string typeTemplate) + { + return new AS3ClassOptions( + language: project.Language, + package: dialog.GetPackage(), + super_class: dialog.GetExtends(), + Interfaces: dialog.GetInterfaces(), + is_public: dialog.IsPublic(), + is_dynamic: dialog.IsDynamic(), + is_final: dialog.IsFinal(), + create_inherited: dialog.GetGenerateInheritedMethods(), + create_constructor: dialog.GetGenerateConstructor() + ) {Template = typeTemplate}; + } + + static void FileFromTemplate(string directoryPath, string templateFile, string filePath) + { + try + { + if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); + PluginBase.MainForm.FileFromTemplate(templateFile + ".wizard", filePath); + } + catch (Exception ex) + { + ErrorManager.ShowError(ex); + } + } + + static string GetPackage(Project project, ref string classpath, string inDirectory) + { + try + { + var package = GetPackage(classpath, inDirectory); + if (string.IsNullOrEmpty(package) && !project.AdditionalPaths.IsNullOrEmpty()) + { + var closest = ""; + foreach (var it in project.AdditionalPaths) + if ((classpath.StartsWithOrdinal(it) || it == ".") && it.Length > closest.Length) + closest = it; + if (closest.Length > 0) package = GetPackage(closest, inDirectory); + } + if (package != "") return package; + // search in Global classpath + var info = new Hashtable {["language"] = project.Language}; + var de = new DataEvent(EventType.Command, "ASCompletion.GetUserClasspath", info); + EventManager.DispatchEvent(null, de); + if (de.Handled && info.ContainsKey("cp") && info["cp"] is List cps) + { + foreach (var cp in cps) + { + package = GetPackage(cp, inDirectory); + if (package.Length == 0) continue; + classpath = cp; + break; + } + } + return package; + } + catch (NullReferenceException) + { + return string.Empty; + } + } + + static string GetPackage(string classpath, string path) + { + if (!path.StartsWith(classpath, StringComparison.OrdinalIgnoreCase)) return string.Empty; + return path.Substring(classpath.Length) + .Trim('/', '\\', ' ', '.') + .Replace(Path.DirectorySeparatorChar, '.'); + } + + public static string ProcessArgs(string args) + { + if (lastFileFromTemplate is null) return args; + var package = lastFileOptions != null ? lastFileOptions.Package : ""; + var fileName = Path.GetFileNameWithoutExtension(lastFileFromTemplate); + args = args.Replace("$(FileName)", fileName); + if (args.Contains("$(FileNameWithPackage)") || args.Contains("$(Package)")) + { + args = args.Replace("$(Package)", package); + args = package.Length != 0 + ? args.Replace("$(FileNameWithPackage)", package + "." + fileName) + : args.Replace("$(FileNameWithPackage)", fileName); + if (lastFileOptions != null) + { + args = ProcessFileTemplate(args); + if (processOnSwitch is null) lastFileOptions = null; + } + } + lastFileFromTemplate = null; + return args; + } + + static string ProcessFileTemplate(string args) + { + var eolMode = (int)PluginBase.Settings.EOLMode; + var lineBreak = LineEndDetector.GetNewLineMarker(eolMode); + var imports = new List(); + var extends = ""; + var implements = ""; + var paramString = ""; + var superConstructor = ""; + int index; + // resolve imports + if (!lastFileOptions.interfaces.IsNullOrEmpty()) + { + string implementContinuation; + implements = " implements "; + index = 0; + + if (lastFileOptions.Language == "haxe") + { + var isHaxe2 = PluginBase.CurrentSDK != null && PluginBase.CurrentSDK.Name.ToLower().Contains("haxe 2"); + implementContinuation = isHaxe2 ? ", implements " : " implements "; + } + else + { + implementContinuation = ", "; + } + + foreach (var item in lastFileOptions.interfaces) + { + if (item.Contains('.')) imports.Add(item); + implements += (index > 0 ? implementContinuation : "") + item.Split('.').Last(); + if (lastFileOptions.createInheritedMethods) + { + processOnSwitch = lastFileFromTemplate; + // let ASCompletion generate the implementations when file is opened + } + index++; + } + } + if (!string.IsNullOrEmpty(lastFileOptions.superClass)) + { + var superClassFullName = lastFileOptions.superClass; + if (superClassFullName.Contains('.')) imports.Add(superClassFullName); + var superClassShortName = superClassFullName.Split('.').Last(); + var fileName = Path.GetFileNameWithoutExtension(lastFileFromTemplate); + extends = fileName == superClassShortName ? $" extends {superClassFullName}" : $" extends {superClassShortName}"; + if (lastFileOptions.createConstructor + && constructorArgs is null + && ASContext.GetLanguageContext(lastFileOptions.Language) is { } ctx) + { + var lastDotIndex = superClassFullName.LastIndexOf('.'); + var cmodel = ctx.GetModel(lastDotIndex == -1 ? "" : superClassFullName.Substring(0, lastDotIndex), superClassShortName, ""); + if (!cmodel.IsVoid()) + { + if ((cmodel.Flags & FlagType.TypeDef) != 0) + cmodel.SearchMember(FlagType.Constructor, true, out cmodel); + foreach (var member in cmodel.Members) + { + if (member.Name != cmodel.Constructor) continue; + paramString = member.ParametersString(); + AddImports(ctx, member, cmodel.InFile, imports); + superConstructor = "super("; + index = 0; + if (member.Parameters != null) + foreach (var param in member.Parameters) + { + if (param.Name.StartsWith('.')) break; + var pname = TemplateUtils.GetParamName(param); + superConstructor += (index > 0 ? ", " : "") + pname; + index++; + } + superConstructor += ");\n" + (lastFileOptions.Language == "as3" ? "\t\t\t" : "\t\t"); + break; + } + } + } + } + if (constructorArgs != null) + { + paramString = constructorArgs; + foreach (var type in constructorArgTypes) + { + if (!imports.Contains(type)) + { + imports.Add(type); + } + } + } + string access; + var classMetadata = ""; + if (lastFileOptions.Language == "as3") + { + access = lastFileOptions.isPublic ? "public " : "internal "; + access += lastFileOptions.isDynamic ? "dynamic " : ""; + access += lastFileOptions.isFinal ? "final " : ""; + } + else if (lastFileOptions.Language == "haxe") + { + access = lastFileOptions.isPublic ? "public " : "private "; + access += lastFileOptions.isDynamic ? "dynamic " : ""; + if (lastFileOptions.isFinal) classMetadata += "@:final\n"; + } + else access = lastFileOptions.isDynamic ? "dynamic " : ""; + var importsSrc = ""; + string prevImport = null; + imports.Sort(); + foreach (var import in imports) + { + if (prevImport == import) continue; + prevImport = import; + if (import.LastIndexOf('.') is { } p && (p == -1 || import.Substring(0, p) == lastFileOptions.Package)) continue; + importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + "import " + import + ";" + lineBreak; + } + if (importsSrc.Length > 0) importsSrc += (lastFileOptions.Language == "as3" ? "\t" : "") + lineBreak; + args = args.Replace("$(Template)", lastFileOptions.Template ?? string.Empty); + args = args.Replace("$(Import)", importsSrc); + args = args.Replace("$(Extends)", extends); + args = args.Replace("$(Implements)", implements); + args = args.Replace("$(Access)", access); + args = args.Replace("$(InheritedMethods)", string.Empty); + args = args.Replace("$(ConstructorArguments)", paramString); + args = args.Replace("$(Super)", superConstructor); + args = args.Replace("$(ClassMetadata)", classMetadata); + return args; + } + + static void AddImports(IASContext ctx, MemberModel member, FileModel inFile, ICollection result) + { + var types = new List {member.Type}; + if (member.Parameters != null) types.AddRange(member.Parameters.Select(static it => it.Type)); + foreach (var type in ASContext.Context.DecomposeTypes(types)) + { + AddImport(ctx, type, inFile, result); + } + } + + static void AddImport(IASContext ctx, string cname, FileModel inFile, ICollection result) + { + var aClass = ctx.ResolveType(cname, inFile); + if (!aClass.IsVoid() && aClass.InFile.Package != "") + { + result.Add(aClass.QualifiedName); + } + } + } +} \ No newline at end of file diff --git a/External/Plugins/ASClassWizard/Wizards/AS3ClassWizard.cs b/External/Plugins/ASClassWizard/Wizards/AS3ClassWizard.cs index 23ef2d2258..fd85b04245 100644 --- a/External/Plugins/ASClassWizard/Wizards/AS3ClassWizard.cs +++ b/External/Plugins/ASClassWizard/Wizards/AS3ClassWizard.cs @@ -1,48 +1,44 @@ - -#region Imports -using System; -using System.Collections; +using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; using System.Drawing; -using System.Text; using System.IO; using System.Windows.Forms; using System.Text.RegularExpressions; - using PluginCore; using PluginCore.Localization; using ProjectManager.Projects; - -using ASClassWizard.Wizards; -using ASClassWizard.Resources; - using ASCompletion.Context; using ASCompletion.Model; - -using AS3Context; -using AS2Context; -using System.Reflection; using System.Diagnostics; -#endregion - +using System.Linq; +using PluginCore.Controls; namespace ASClassWizard.Wizards { - public partial class AS3ClassWizard : Form + public partial class AS3ClassWizard : SmartForm, IThemeHandler, IWizard { - private string directoryPath; private Project project; - public const string REG_IDENTIFIER = "^[a-zA-Z_$][a-zA-Z0-9_$]*$"; + public const string REG_IDENTIFIER_AS = "^[a-zA-Z_$][a-zA-Z0-9_$]*$"; + // $ is not a valid char in haxe class names + public const string REG_IDENTIFIER_HAXE = "^[a-zA-Z_][a-zA-Z0-9_]*$"; public AS3ClassWizard() { InitializeComponent(); LocalizeText(); CenterToParent(); + this.FormGuid = "eb444130-58ea-47bd-9751-ad78a59c711f"; this.Font = PluginBase.Settings.DefaultFont; - this.errorIcon.Image = PluginMain.MainForm.FindImage("197"); + this.errorIcon.Image = PluginBase.MainForm.FindImage("197"); + } + + public void AfterTheming() + { + Color color = PluginBase.MainForm.GetThemeColor("ListBox.BackColor", SystemColors.Window); + Color color1 = PluginBase.MainForm.GetThemeColor("Control.BackColor", SystemColors.Control); + this.flowLayoutPanel1.BackColor = color1; + this.flowLayoutPanel9.BackColor = color; + this.titleLabel.BackColor = color; } private void LocalizeText() @@ -63,25 +59,21 @@ private void LocalizeText() this.cancelButton.Text = TextHelper.GetString("Wizard.Button.Cancel"); } - public String StartupPackage + public string StartupPackage { - set { packageBox.Text = value; } + set => packageBox.Text = value; } - public String StartupClassName - { - set { classBox.Text = value; } - } - - public string Directory + public string StartupClassName { - get { return this.directoryPath; } - set { this.directoryPath = value; } + set => classBox.Text = value; } + public string Directory { get; set; } + public Project Project { - get { return project; } + get => project; set { this.project = value; @@ -91,32 +83,38 @@ public Project Project this.publicRadio.Enabled = false; this.internalRadio.Enabled = false; this.finalCheck.Enabled = false; - this.titleLabel.Text = TextHelper.GetString("Wizard.Label.NewAs2Class"); - this.Text = TextHelper.GetString("Wizard.Label.NewAs2Class"); + var label = TextHelper.GetString("Wizard.Label.NewAs2Class"); + this.titleLabel.Text = label; + this.Text = label; } if (project.Language == "haxe") { this.internalRadio.Text = "private"; - this.finalCheck.Enabled = false; - this.titleLabel.Text = TextHelper.GetString("Wizard.Label.NewHaxeClass"); - this.Text = TextHelper.GetString("Wizard.Label.NewHaxeClass"); + var label = TextHelper.GetString("Wizard.Label.NewHaxeClass"); + this.titleLabel.Text = label; + this.Text = label; } else { - this.titleLabel.Text = TextHelper.GetString("Wizard.Label.NewAs3Class"); - this.Text = TextHelper.GetString("Wizard.Label.NewAs3Class"); + var label = TextHelper.GetString("Wizard.Label.NewAs3Class"); + this.titleLabel.Text = label; + this.Text = label; } } } private void ValidateClass() { - string errorMessage = ""; - if (getClassName() == "" || !Regex.Match(getClassName(), REG_IDENTIFIER, RegexOptions.Singleline).Success) - { + var errorMessage = ""; + var regex = (project.Language == "haxe") ? REG_IDENTIFIER_HAXE : REG_IDENTIFIER_AS; + if (GetName().Length == 0) + errorMessage = TextHelper.GetString("Wizard.Error.EmptyClassName"); + else if (!Regex.Match(GetName(), regex, RegexOptions.Singleline).Success) errorMessage = TextHelper.GetString("Wizard.Error.InvalidClassName"); - } - if (errorMessage != "") + else if (project.Language == "haxe" && char.IsLower(GetName()[0])) + errorMessage = TextHelper.GetString("Wizard.Error.LowercaseClassName"); + + if (errorMessage.Length != 0) { okButton.Enabled = false; errorIcon.Visible = true; @@ -134,12 +132,9 @@ private void ValidateClass() /// /// Browse project packages /// - /// - /// private void packageBrowse_Click(object sender, EventArgs e) { - - PackageBrowser browser = new PackageBrowser(); + using PackageBrowser browser = new PackageBrowser(); browser.Project = this.Project; foreach (string item in Project.AbsoluteClasspaths) @@ -153,14 +148,14 @@ private void packageBrowse_Click(object sender, EventArgs e) string package = Path.GetDirectoryName(ProjectPaths.GetRelativePath(classpath, Path.Combine(browser.Package, "foo"))); if (package != null) { - directoryPath = browser.Package; + Directory = browser.Package; package = package.Replace(Path.DirectorySeparatorChar, '.'); this.packageBox.Text = package; } } else { - this.directoryPath = browser.Project.Directory; + this.Directory = browser.Project.Directory; this.packageBox.Text = ""; } } @@ -172,29 +167,17 @@ private void AS3ClassWizard_Load(object sender, EventArgs e) this.ValidateClass(); } - private void cancelButton_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.Cancel; - this.Close(); - } - - private void okButton_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.OK; - this.Close(); - } - private void baseBrowse_Click(object sender, EventArgs e) { - ClassBrowser browser = new ClassBrowser(); - IASContext context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language); + using ClassBrowser browser = new ClassBrowser(); + IASContext context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language); try { browser.ClassList = context.GetAllProjectClasses(); } catch { } - browser.ExcludeFlag = FlagType.Interface; - browser.IncludeFlag = FlagType.Class; + browser.ExcludeFlag = FlagType.Interface; + browser.IncludeFlag = FlagType.Class; if (browser.ShowDialog(this) == DialogResult.OK) { this.baseBox.Text = browser.SelectedClass; @@ -205,14 +188,12 @@ private void baseBrowse_Click(object sender, EventArgs e) /// /// Added interface /// - /// - /// private void implementBrowse_Click(object sender, EventArgs e) { - ClassBrowser browser = new ClassBrowser(); + using var browser = new ClassBrowser(); MemberList known = null; browser.IncludeFlag = FlagType.Interface; - IASContext context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language); + var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language); try { known = context.GetAllProjectClasses(); @@ -243,8 +224,6 @@ private void implementBrowse_Click(object sender, EventArgs e) /// /// Remove interface /// - /// - /// private void interfaceRemove_Click(object sender, EventArgs e) { if (this.implementList.SelectedItem != null) @@ -278,73 +257,32 @@ private void baseBox_TextChanged(object sender, EventArgs e) #endregion - public static Image GetResource( string resourceID ) - { - resourceID = "ASClassWizard." + resourceID; - Assembly assembly = Assembly.GetExecutingAssembly(); - Image image = new Bitmap(assembly.GetManifestResourceStream(resourceID)); - return image; - } - #region user_options - public string getPackage() - { - return this.packageBox.Text; - } + public string GetPackage() => packageBox.Text; - public string getClassName() - { - return this.classBox.Text; - } + public string GetName() => classBox.Text; - public bool isDynamic() - { - return this.dynamicCheck.Checked; - } + public bool IsDynamic() => dynamicCheck.Checked; - public bool isFinal() - { - return this.finalCheck.Checked; - } + public bool IsFinal() => finalCheck.Checked; - public bool isPublic() - { - return this.publicRadio.Checked; - } + public bool IsPublic() => publicRadio.Checked; - public string getSuperClass() - { - return this.baseBox.Text; - } + public string GetExtends() => baseBox.Text; - public List getInterfaces() + public List GetInterfaces() { - List _interfaces = new List(this.implementList.Items.Count); - foreach (string item in this.implementList.Items) - { - _interfaces.Add(item); - } - return _interfaces; + return implementList.Items.Cast().ToList(); } - public bool hasInterfaces() - { - return this.implementList.Items.Count > 0; - } + public bool HasInterfaces() => implementList.Items.Count > 0; - public bool getGenerateConstructor() - { - return this.constructorCheck.Checked; - } + public bool GetGenerateConstructor() => constructorCheck.Checked; - public bool getGenerateInheritedMethods() - { - return this.superCheck.Checked; - } + public bool GetGenerateInheritedMethods() => superCheck.Checked; #endregion - } } diff --git a/External/Plugins/ASClassWizard/Wizards/AS3ClassWizard.designer.cs b/External/Plugins/ASClassWizard/Wizards/AS3ClassWizard.designer.cs index 0f4775bbb5..5426397627 100644 --- a/External/Plugins/ASClassWizard/Wizards/AS3ClassWizard.designer.cs +++ b/External/Plugins/ASClassWizard/Wizards/AS3ClassWizard.designer.cs @@ -1,7 +1,4 @@ - -using ASClassWizard.Resources; - -namespace ASClassWizard.Wizards +namespace ASClassWizard.Wizards { partial class AS3ClassWizard { @@ -32,39 +29,39 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.flowLayoutPanel5 = new System.Windows.Forms.FlowLayoutPanel(); - this.constructorCheck = new System.Windows.Forms.CheckBox(); - this.superCheck = new System.Windows.Forms.CheckBox(); + this.constructorCheck = new System.Windows.Forms.CheckBoxEx(); + this.superCheck = new System.Windows.Forms.CheckBoxEx(); this.flowLayoutPanel4 = new System.Windows.Forms.FlowLayoutPanel(); - this.implementBrowse = new System.Windows.Forms.Button(); - this.implementRemove = new System.Windows.Forms.Button(); - this.baseBox = new System.Windows.Forms.TextBox(); - this.classBox = new System.Windows.Forms.TextBox(); - this.packageBox = new System.Windows.Forms.TextBox(); + this.implementBrowse = new System.Windows.Forms.ButtonEx(); + this.implementRemove = new System.Windows.Forms.ButtonEx(); + this.baseBox = new System.Windows.Forms.TextBoxEx(); + this.classBox = new System.Windows.Forms.TextBoxEx(); + this.packageBox = new System.Windows.Forms.TextBoxEx(); this.classLabel = new System.Windows.Forms.Label(); this.accessLabel = new System.Windows.Forms.Label(); this.flowLayoutPanel2 = new System.Windows.Forms.FlowLayoutPanel(); this.publicRadio = new System.Windows.Forms.RadioButton(); this.internalRadio = new System.Windows.Forms.RadioButton(); this.flowLayoutPanel3 = new System.Windows.Forms.FlowLayoutPanel(); - this.dynamicCheck = new System.Windows.Forms.CheckBox(); - this.finalCheck = new System.Windows.Forms.CheckBox(); + this.dynamicCheck = new System.Windows.Forms.CheckBoxEx(); + this.finalCheck = new System.Windows.Forms.CheckBoxEx(); this.baseLabel = new System.Windows.Forms.Label(); this.generationLabel = new System.Windows.Forms.Label(); this.packageLabel = new System.Windows.Forms.Label(); - this.packageBrowse = new System.Windows.Forms.Button(); - this.baseBrowse = new System.Windows.Forms.Button(); + this.packageBrowse = new System.Windows.Forms.ButtonEx(); + this.baseBrowse = new System.Windows.Forms.ButtonEx(); this.errorLabel = new System.Windows.Forms.Label(); this.errorIcon = new System.Windows.Forms.PictureBox(); this.flowLayoutPanel6 = new System.Windows.Forms.FlowLayoutPanel(); this.flowLayoutPanel9 = new System.Windows.Forms.FlowLayoutPanel(); this.titleLabel = new System.Windows.Forms.Label(); - this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.groupBox2 = new System.Windows.Forms.GroupBoxEx(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.implementLabel = new System.Windows.Forms.Label(); - this.implementList = new System.Windows.Forms.ListBox(); + this.implementList = new System.Windows.Forms.ListBoxEx(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); - this.cancelButton = new System.Windows.Forms.Button(); - this.okButton = new System.Windows.Forms.Button(); + this.cancelButton = new System.Windows.Forms.ButtonEx(); + this.okButton = new System.Windows.Forms.ButtonEx(); this.flowLayoutPanel5.SuspendLayout(); this.flowLayoutPanel4.SuspendLayout(); this.flowLayoutPanel2.SuspendLayout(); @@ -86,7 +83,7 @@ private void InitializeComponent() this.flowLayoutPanel5.Location = new System.Drawing.Point(106, 206); this.flowLayoutPanel5.Name = "flowLayoutPanel5"; this.flowLayoutPanel5.Size = new System.Drawing.Size(268, 54); - this.flowLayoutPanel5.TabIndex = 12; + this.flowLayoutPanel5.TabIndex = 15; // // constructorCheck // @@ -96,7 +93,7 @@ private void InitializeComponent() this.constructorCheck.Location = new System.Drawing.Point(3, 3); this.constructorCheck.Name = "constructorCheck"; this.constructorCheck.Size = new System.Drawing.Size(127, 17); - this.constructorCheck.TabIndex = 9; + this.constructorCheck.TabIndex = 0; this.constructorCheck.Text = "Generate Constructor"; this.constructorCheck.UseVisualStyleBackColor = true; // @@ -108,7 +105,7 @@ private void InitializeComponent() this.superCheck.Location = new System.Drawing.Point(3, 26); this.superCheck.Name = "superCheck"; this.superCheck.Size = new System.Drawing.Size(120, 17); - this.superCheck.TabIndex = 10; + this.superCheck.TabIndex = 1; this.superCheck.Text = "Generate Super call"; this.superCheck.UseVisualStyleBackColor = true; // @@ -122,14 +119,14 @@ private void InitializeComponent() this.flowLayoutPanel4.Margin = new System.Windows.Forms.Padding(3,0,0,0); this.flowLayoutPanel4.Name = "flowLayoutPanel4"; this.flowLayoutPanel4.Size = new System.Drawing.Size(80, 62); - this.flowLayoutPanel4.TabIndex = 10; + this.flowLayoutPanel4.TabIndex = 13; // // implementBrowse // this.implementBrowse.Location = new System.Drawing.Point(3, 3); this.implementBrowse.Name = "implementBrowse"; this.implementBrowse.Size = new System.Drawing.Size(74, 23); - this.implementBrowse.TabIndex = 8; + this.implementBrowse.TabIndex = 0; this.implementBrowse.Text = "Browse..."; this.implementBrowse.UseVisualStyleBackColor = true; this.implementBrowse.Anchor = System.Windows.Forms.AnchorStyles.None; @@ -141,7 +138,7 @@ private void InitializeComponent() this.implementRemove.Location = new System.Drawing.Point(3, 32); this.implementRemove.Name = "implementRemove"; this.implementRemove.Size = new System.Drawing.Size(74, 23); - this.implementRemove.TabIndex = 8; + this.implementRemove.TabIndex = 1; this.implementRemove.Text = "Remove"; this.implementRemove.UseVisualStyleBackColor = true; this.implementRemove.Anchor = System.Windows.Forms.AnchorStyles.None; @@ -154,7 +151,7 @@ private void InitializeComponent() this.baseBox.Location = new System.Drawing.Point(106, 116); this.baseBox.Name = "baseBox"; this.baseBox.Size = new System.Drawing.Size(268, 20); - this.baseBox.TabIndex = 7; + this.baseBox.TabIndex = 9; this.baseBox.TextChanged += new System.EventHandler(this.baseBox_TextChanged); // // classBox @@ -163,7 +160,7 @@ private void InitializeComponent() this.classBox.Location = new System.Drawing.Point(106, 88); this.classBox.Name = "classBox"; this.classBox.Size = new System.Drawing.Size(268, 20); - this.classBox.TabIndex = 5; + this.classBox.TabIndex = 7; this.classBox.Text = "NewClass"; this.classBox.TextChanged += new System.EventHandler(this.classBox_TextChanged); // @@ -173,7 +170,7 @@ private void InitializeComponent() this.packageBox.Location = new System.Drawing.Point(106, 4); this.packageBox.Name = "packageBox"; this.packageBox.Size = new System.Drawing.Size(268, 20); - this.packageBox.TabIndex = 0; + this.packageBox.TabIndex = 1; this.packageBox.TextChanged += new System.EventHandler(this.packageBox_TextChanged); // // classLabel @@ -183,7 +180,7 @@ private void InitializeComponent() this.classLabel.Location = new System.Drawing.Point(3, 91); this.classLabel.Name = "classLabel"; this.classLabel.Size = new System.Drawing.Size(32, 13); - this.classLabel.TabIndex = 1; + this.classLabel.TabIndex = 6; this.classLabel.Text = "Class"; // // accessLabel @@ -213,7 +210,7 @@ private void InitializeComponent() this.publicRadio.Location = new System.Drawing.Point(3, 3); this.publicRadio.Name = "publicRadio"; this.publicRadio.Size = new System.Drawing.Size(53, 17); - this.publicRadio.TabIndex = 1; + this.publicRadio.TabIndex = 0; this.publicRadio.TabStop = true; this.publicRadio.Text = "public"; this.publicRadio.UseVisualStyleBackColor = true; @@ -224,7 +221,7 @@ private void InitializeComponent() this.internalRadio.Location = new System.Drawing.Point(62, 3); this.internalRadio.Name = "internalRadio"; this.internalRadio.Size = new System.Drawing.Size(59, 17); - this.internalRadio.TabIndex = 2; + this.internalRadio.TabIndex = 1; this.internalRadio.Text = "internal"; this.internalRadio.UseVisualStyleBackColor = true; // @@ -244,7 +241,7 @@ private void InitializeComponent() this.dynamicCheck.Location = new System.Drawing.Point(3, 3); this.dynamicCheck.Name = "dynamicCheck"; this.dynamicCheck.Size = new System.Drawing.Size(65, 17); - this.dynamicCheck.TabIndex = 3; + this.dynamicCheck.TabIndex = 0; this.dynamicCheck.Text = "dynamic"; this.dynamicCheck.UseVisualStyleBackColor = true; // @@ -254,7 +251,7 @@ private void InitializeComponent() this.finalCheck.Location = new System.Drawing.Point(74, 3); this.finalCheck.Name = "finalCheck"; this.finalCheck.Size = new System.Drawing.Size(45, 17); - this.finalCheck.TabIndex = 4; + this.finalCheck.TabIndex = 1; this.finalCheck.Text = "final"; this.finalCheck.UseVisualStyleBackColor = true; // @@ -265,7 +262,7 @@ private void InitializeComponent() this.baseLabel.Location = new System.Drawing.Point(3, 119); this.baseLabel.Name = "baseLabel"; this.baseLabel.Size = new System.Drawing.Size(58, 13); - this.baseLabel.TabIndex = 6; + this.baseLabel.TabIndex = 8; this.baseLabel.Text = "Base class"; // // generationLabel @@ -275,7 +272,7 @@ private void InitializeComponent() this.generationLabel.Name = "generationLabel"; this.generationLabel.Padding = new System.Windows.Forms.Padding(0, 6, 0, 0); this.generationLabel.Size = new System.Drawing.Size(85, 19); - this.generationLabel.TabIndex = 11; + this.generationLabel.TabIndex = 14; this.generationLabel.Text = "Code generation"; // // packageLabel @@ -285,7 +282,7 @@ private void InitializeComponent() this.packageLabel.Location = new System.Drawing.Point(3, 7); this.packageLabel.Name = "packageLabel"; this.packageLabel.Size = new System.Drawing.Size(50, 13); - this.packageLabel.TabIndex = 13; + this.packageLabel.TabIndex = 0; this.packageLabel.Text = "Package"; // // packageBrowse @@ -294,7 +291,7 @@ private void InitializeComponent() this.packageBrowse.Location = new System.Drawing.Point(381, 3); this.packageBrowse.Name = "packageBrowse"; this.packageBrowse.Size = new System.Drawing.Size(74, 23); - this.packageBrowse.TabIndex = 0; + this.packageBrowse.TabIndex = 2; this.packageBrowse.Text = "Browse..."; this.packageBrowse.UseVisualStyleBackColor = true; this.packageBrowse.Click += new System.EventHandler(this.packageBrowse_Click); @@ -305,7 +302,7 @@ private void InitializeComponent() this.baseBrowse.Location = new System.Drawing.Point(381, 115); this.baseBrowse.Name = "baseBrowse"; this.baseBrowse.Size = new System.Drawing.Size(74, 23); - this.baseBrowse.TabIndex = 6; + this.baseBrowse.TabIndex = 10; this.baseBrowse.Text = "Browse..."; this.baseBrowse.UseVisualStyleBackColor = true; this.baseBrowse.Click += new System.EventHandler(this.baseBrowse_Click); @@ -318,11 +315,12 @@ private void InitializeComponent() this.errorLabel.Location = new System.Drawing.Point(25, 4); this.errorLabel.Name = "errorLabel"; this.errorLabel.Size = new System.Drawing.Size(34, 13); - this.errorLabel.TabIndex = 1; + this.errorLabel.TabIndex = 0; this.errorLabel.Text = "Error"; // // errorIcon - // + // + this.errorIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.errorIcon.Anchor = System.Windows.Forms.AnchorStyles.Left; this.errorIcon.Location = new System.Drawing.Point(3, 3); this.errorIcon.Name = "errorIcon"; @@ -337,8 +335,8 @@ private void InitializeComponent() this.flowLayoutPanel6.Controls.Add(this.errorLabel); this.flowLayoutPanel6.Location = new System.Drawing.Point(3, 3); this.flowLayoutPanel6.Name = "flowLayoutPanel6"; - this.flowLayoutPanel6.Size = new System.Drawing.Size(301, 23); - this.flowLayoutPanel6.TabIndex = 1; + this.flowLayoutPanel6.Size = new System.Drawing.Size(296, 23); + this.flowLayoutPanel6.TabIndex = 0; // // flowLayoutPanel9 // @@ -364,11 +362,14 @@ private void InitializeComponent() // // groupBox2 // + this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.groupBox2.Controls.Add(this.tableLayoutPanel2); this.groupBox2.Location = new System.Drawing.Point(10, 53); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(468, 279); - this.groupBox2.TabIndex = 4; + this.groupBox2.TabIndex = 1; this.groupBox2.TabStop = false; // // tableLayoutPanel2 @@ -414,7 +415,7 @@ private void InitializeComponent() this.implementLabel.Name = "implementLabel"; this.implementLabel.Padding = new System.Windows.Forms.Padding(0, 6, 0, 0); this.implementLabel.Size = new System.Drawing.Size(55, 19); - this.implementLabel.TabIndex = 8; + this.implementLabel.TabIndex = 11; this.implementLabel.Text = "Implement"; // // implementList @@ -424,11 +425,13 @@ private void InitializeComponent() this.implementList.Location = new System.Drawing.Point(106, 143); this.implementList.Name = "implementList"; this.implementList.Size = new System.Drawing.Size(268, 56); - this.implementList.TabIndex = 7; + this.implementList.TabIndex = 12; // // flowLayoutPanel1 // - this.flowLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.flowLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); this.flowLayoutPanel1.AutoSize = true; this.flowLayoutPanel1.Controls.Add(this.cancelButton); this.flowLayoutPanel1.Controls.Add(this.okButton); @@ -437,7 +440,7 @@ private void InitializeComponent() this.flowLayoutPanel1.Location = new System.Drawing.Point(12, 338); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(466, 29); - this.flowLayoutPanel1.TabIndex = 5; + this.flowLayoutPanel1.TabIndex = 2; // // cancelButton // @@ -445,21 +448,20 @@ private void InitializeComponent() this.cancelButton.Location = new System.Drawing.Point(388, 3); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); - this.cancelButton.TabIndex = 12; + this.cancelButton.TabIndex = 2; this.cancelButton.Text = "Cancel"; this.cancelButton.UseVisualStyleBackColor = true; - this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click); // // okButton // + this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; this.okButton.Enabled = false; this.okButton.Location = new System.Drawing.Point(307, 3); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); - this.okButton.TabIndex = 11; + this.okButton.TabIndex = 1; this.okButton.Text = "Ok"; this.okButton.UseVisualStyleBackColor = true; - this.okButton.Click += new System.EventHandler(this.okButton_Click); // // AS3ClassWizard // @@ -472,6 +474,8 @@ private void InitializeComponent() this.Controls.Add(this.groupBox2); this.Controls.Add(this.flowLayoutPanel9); this.ShowIcon = false; + this.MinimizeBox = false; + this.MaximizeBox = false; this.ShowInTaskbar = false; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; diff --git a/External/Plugins/ASClassWizard/Wizards/AS3InterfaceWizard.cs b/External/Plugins/ASClassWizard/Wizards/AS3InterfaceWizard.cs new file mode 100644 index 0000000000..e02caf3d2a --- /dev/null +++ b/External/Plugins/ASClassWizard/Wizards/AS3InterfaceWizard.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Text.RegularExpressions; +using System.Windows.Forms; +using ASCompletion.Context; +using ASCompletion.Model; +using PluginCore; +using PluginCore.Controls; +using PluginCore.Localization; +using ProjectManager.Projects; + +namespace ASClassWizard.Wizards +{ + public partial class AS3InterfaceWizard : SmartForm, IThemeHandler, IWizard + { + Project project; + public const string REG_IDENTIFIER_AS = "^[a-zA-Z_$][a-zA-Z0-9_$]*$"; + // $ is not a valid char in haxe class names + public const string REG_IDENTIFIER_HAXE = "^[a-zA-Z_][a-zA-Z0-9_]*$"; + + public AS3InterfaceWizard() + { + InitializeComponent(); + LocalizeText(); + CenterToParent(); + FormGuid = "E1D36E71-BD39-4C58-A436-F46D01EC0590"; + Font = PluginBase.Settings.DefaultFont; + errorIcon.Image = PluginBase.MainForm.FindImage("197"); + } + + public void AfterTheming() + { + var color = PluginBase.MainForm.GetThemeColor("ListBox.BackColor", SystemColors.Window); + var color1 = PluginBase.MainForm.GetThemeColor("Control.BackColor", SystemColors.Control); + flowLayoutPanel1.BackColor = color1; + flowLayoutPanel9.BackColor = color; + titleLabel.BackColor = color; + } + + void LocalizeText() + { + typeLabel.Text = TextHelper.GetString("Wizard.Label.Name"); + baseLabel.Text = TextHelper.GetString("Wizard.Label.ExtendsInterface"); + packageLabel.Text = TextHelper.GetString("Wizard.Label.Package"); + packageBrowse.Text = TextHelper.GetString("Wizard.Button.Browse"); + baseBrowse.Text = TextHelper.GetString("Wizard.Button.Browse"); + okButton.Text = TextHelper.GetString("Wizard.Button.Ok"); + cancelButton.Text = TextHelper.GetString("Wizard.Button.Cancel"); + } + + public string StartupPackage + { + set => packageBox.Text = value; + } + + public string StartupClassName + { + set => classBox.Text = value; + } + + public string Directory { get; set; } + + public Project Project + { + get => project; + set + { + project = value; + if (project.Language == "as2") + { + var label = TextHelper.GetString("Wizard.Label.NewAs2Interface"); + titleLabel.Text = label; + Text = label; + } + else if (project.Language == "haxe") + { + var label = TextHelper.GetString("Wizard.Label.NewHaxeInterface"); + titleLabel.Text = label; + Text = label; + } + else + { + var label = TextHelper.GetString("Wizard.Label.NewAs3Interface"); + titleLabel.Text = label; + Text = label; + } + } + } + + void ValidateClass() + { + var errorMessage = ""; + var regex = (project.Language == "haxe") ? REG_IDENTIFIER_HAXE : REG_IDENTIFIER_AS; + if (GetName().Length == 0) + errorMessage = TextHelper.GetString("Wizard.Error.EmptyInterfaceName"); + else if (!Regex.Match(GetName(), regex, RegexOptions.Singleline).Success) + errorMessage = TextHelper.GetString("Wizard.Error.InvalidInterfaceName"); + else if (project.Language == "haxe" && char.IsLower(GetName()[0])) + errorMessage = TextHelper.GetString("Wizard.Error.LowercaseInterfaceName"); + + if (errorMessage.Length != 0) + { + okButton.Enabled = false; + errorIcon.Visible = true; + } + else + { + okButton.Enabled = true; + errorIcon.Visible = false; + } + errorLabel.Text = errorMessage; + } + + #region EventHandlers + + /// + /// Browse project packages + /// + void packageBrowse_Click(object sender, EventArgs e) + { + using PackageBrowser browser = new PackageBrowser(); + browser.Project = Project; + + foreach (string item in Project.AbsoluteClasspaths) + browser.AddClassPath(item); + + if (browser.ShowDialog(this) == DialogResult.OK) + { + if (browser.Package != null) + { + string classpath = Project.AbsoluteClasspaths.GetClosestParent(browser.Package); + string package = Path.GetDirectoryName(ProjectPaths.GetRelativePath(classpath, Path.Combine(browser.Package, "foo"))); + if (package != null) + { + Directory = browser.Package; + package = package.Replace(Path.DirectorySeparatorChar, '.'); + packageBox.Text = package; + } + } + else + { + Directory = browser.Project.Directory; + packageBox.Text = ""; + } + } + } + + void AS3ClassWizard_Load(object sender, EventArgs e) + { + classBox.Select(); + ValidateClass(); + } + + void baseBrowse_Click(object sender, EventArgs e) + { + using var browser = new ClassBrowser(); + var context = ASContext.GetLanguageContext(PluginBase.CurrentProject.Language); + try + { + browser.ClassList = context.GetAllProjectClasses(); + } + catch { } + browser.IncludeFlag = FlagType.Interface; + if (browser.ShowDialog(this) == DialogResult.OK) + { + baseBox.Text = browser.SelectedClass; + } + okButton.Focus(); + } + + void packageBox_TextChanged(object sender, EventArgs e) + { + ValidateClass(); + } + + void classBox_TextChanged(object sender, EventArgs e) + { + ValidateClass(); + } + + void baseBox_TextChanged(object sender, EventArgs e) + { + ValidateClass(); + } + + #endregion + + #region user_options + + public string GetPackage() => packageBox.Text; + + public string GetName() => classBox.Text; + + public string GetExtends() => baseBox.Text; + + #endregion + + public List GetInterfaces() => null; + + public bool IsPublic() => true; + + public bool IsDynamic() => false; + + public bool IsFinal() => false; + + public bool GetGenerateInheritedMethods() => false; + + public bool GetGenerateConstructor() => false; + } +} diff --git a/External/Plugins/ASClassWizard/Wizards/AS3InterfaceWizard.designer.cs b/External/Plugins/ASClassWizard/Wizards/AS3InterfaceWizard.designer.cs new file mode 100644 index 0000000000..f448287d61 --- /dev/null +++ b/External/Plugins/ASClassWizard/Wizards/AS3InterfaceWizard.designer.cs @@ -0,0 +1,345 @@ + +namespace ASClassWizard.Wizards +{ + partial class AS3InterfaceWizard + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.baseBox = new System.Windows.Forms.TextBoxEx(); + this.classBox = new System.Windows.Forms.TextBoxEx(); + this.packageBox = new System.Windows.Forms.TextBoxEx(); + this.typeLabel = new System.Windows.Forms.Label(); + this.baseLabel = new System.Windows.Forms.Label(); + this.packageLabel = new System.Windows.Forms.Label(); + this.packageBrowse = new System.Windows.Forms.ButtonEx(); + this.baseBrowse = new System.Windows.Forms.ButtonEx(); + this.errorLabel = new System.Windows.Forms.Label(); + this.errorIcon = new System.Windows.Forms.PictureBox(); + this.flowLayoutPanel6 = new System.Windows.Forms.FlowLayoutPanel(); + this.flowLayoutPanel9 = new System.Windows.Forms.FlowLayoutPanel(); + this.titleLabel = new System.Windows.Forms.Label(); + this.groupBox2 = new System.Windows.Forms.GroupBoxEx(); + this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); + this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); + this.cancelButton = new System.Windows.Forms.ButtonEx(); + this.okButton = new System.Windows.Forms.ButtonEx(); + ((System.ComponentModel.ISupportInitialize)(this.errorIcon)).BeginInit(); + this.flowLayoutPanel6.SuspendLayout(); + this.flowLayoutPanel9.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.tableLayoutPanel2.SuspendLayout(); + this.flowLayoutPanel1.SuspendLayout(); + this.SuspendLayout(); + // + // baseBox + // + this.baseBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.baseBox.BorderColor = System.Drawing.SystemColors.ControlDark; + this.baseBox.Enabled = false; + this.baseBox.Location = new System.Drawing.Point(106, 63); + this.baseBox.Name = "baseBox"; + this.baseBox.Size = new System.Drawing.Size(267, 20); + this.baseBox.TabIndex = 9; + this.baseBox.UseTheme = true; + this.baseBox.TextChanged += new System.EventHandler(this.baseBox_TextChanged); + // + // classBox + // + this.classBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.classBox.BorderColor = System.Drawing.SystemColors.ControlDark; + this.classBox.Location = new System.Drawing.Point(106, 34); + this.classBox.Name = "classBox"; + this.classBox.Size = new System.Drawing.Size(267, 20); + this.classBox.TabIndex = 7; + this.classBox.Text = "INewInterface"; + this.classBox.UseTheme = true; + this.classBox.TextChanged += new System.EventHandler(this.classBox_TextChanged); + // + // packageBox + // + this.packageBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.packageBox.BorderColor = System.Drawing.SystemColors.ControlDark; + this.packageBox.Location = new System.Drawing.Point(106, 5); + this.packageBox.Name = "packageBox"; + this.packageBox.Size = new System.Drawing.Size(267, 20); + this.packageBox.TabIndex = 1; + this.packageBox.UseTheme = true; + this.packageBox.TextChanged += new System.EventHandler(this.packageBox_TextChanged); + // + // typeLabel + // + this.typeLabel.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.typeLabel.AutoSize = true; + this.typeLabel.Location = new System.Drawing.Point(3, 37); + this.typeLabel.Name = "typeLabel"; + this.typeLabel.Size = new System.Drawing.Size(49, 13); + this.typeLabel.TabIndex = 6; + this.typeLabel.Text = "Interface"; + // + // baseLabel + // + this.baseLabel.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.baseLabel.AutoSize = true; + this.baseLabel.Location = new System.Drawing.Point(3, 66); + this.baseLabel.Name = "baseLabel"; + this.baseLabel.Size = new System.Drawing.Size(75, 13); + this.baseLabel.TabIndex = 8; + this.baseLabel.Text = "Base interface"; + // + // packageLabel + // + this.packageLabel.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.packageLabel.AutoSize = true; + this.packageLabel.Location = new System.Drawing.Point(3, 8); + this.packageLabel.Name = "packageLabel"; + this.packageLabel.Size = new System.Drawing.Size(50, 13); + this.packageLabel.TabIndex = 0; + this.packageLabel.Text = "Package"; + // + // packageBrowse + // + this.packageBrowse.Anchor = System.Windows.Forms.AnchorStyles.None; + this.packageBrowse.DisabledBackColor = System.Drawing.SystemColors.Control; + this.packageBrowse.DisabledTextColor = System.Drawing.SystemColors.ControlDark; + this.packageBrowse.Location = new System.Drawing.Point(381, 3); + this.packageBrowse.Name = "packageBrowse"; + this.packageBrowse.Size = new System.Drawing.Size(74, 23); + this.packageBrowse.TabIndex = 2; + this.packageBrowse.Text = "Browse..."; + this.packageBrowse.UseTheme = true; + this.packageBrowse.UseVisualStyleBackColor = true; + this.packageBrowse.Click += new System.EventHandler(this.packageBrowse_Click); + // + // baseBrowse + // + this.baseBrowse.Anchor = System.Windows.Forms.AnchorStyles.None; + this.baseBrowse.DisabledBackColor = System.Drawing.SystemColors.Control; + this.baseBrowse.DisabledTextColor = System.Drawing.SystemColors.ControlDark; + this.baseBrowse.Location = new System.Drawing.Point(381, 61); + this.baseBrowse.Name = "baseBrowse"; + this.baseBrowse.Size = new System.Drawing.Size(74, 23); + this.baseBrowse.TabIndex = 10; + this.baseBrowse.Text = "Browse..."; + this.baseBrowse.UseTheme = true; + this.baseBrowse.UseVisualStyleBackColor = true; + this.baseBrowse.Click += new System.EventHandler(this.baseBrowse_Click); + // + // errorLabel + // + this.errorLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right))); + this.errorLabel.AutoSize = true; + this.errorLabel.ForeColor = System.Drawing.Color.Black; + this.errorLabel.Location = new System.Drawing.Point(25, 4); + this.errorLabel.Name = "errorLabel"; + this.errorLabel.Size = new System.Drawing.Size(29, 13); + this.errorLabel.TabIndex = 0; + this.errorLabel.Text = "Error"; + // + // errorIcon + // + this.errorIcon.Anchor = System.Windows.Forms.AnchorStyles.Left; + this.errorIcon.Location = new System.Drawing.Point(3, 3); + this.errorIcon.Name = "errorIcon"; + this.errorIcon.Size = new System.Drawing.Size(16, 16); + this.errorIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; + this.errorIcon.TabIndex = 0; + this.errorIcon.TabStop = false; + // + // flowLayoutPanel6 + // + this.flowLayoutPanel6.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.flowLayoutPanel6.Controls.Add(this.errorIcon); + this.flowLayoutPanel6.Controls.Add(this.errorLabel); + this.flowLayoutPanel6.Location = new System.Drawing.Point(5, 3); + this.flowLayoutPanel6.Name = "flowLayoutPanel6"; + this.flowLayoutPanel6.Size = new System.Drawing.Size(296, 23); + this.flowLayoutPanel6.TabIndex = 0; + // + // flowLayoutPanel9 + // + this.flowLayoutPanel9.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.flowLayoutPanel9.BackColor = System.Drawing.SystemColors.Window; + this.flowLayoutPanel9.Controls.Add(this.titleLabel); + this.flowLayoutPanel9.Location = new System.Drawing.Point(12, 12); + this.flowLayoutPanel9.Name = "flowLayoutPanel9"; + this.flowLayoutPanel9.Padding = new System.Windows.Forms.Padding(5); + this.flowLayoutPanel9.Size = new System.Drawing.Size(466, 35); + this.flowLayoutPanel9.TabIndex = 0; + // + // titleLabel + // + this.titleLabel.Anchor = System.Windows.Forms.AnchorStyles.None; + this.titleLabel.AutoSize = true; + this.titleLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.titleLabel.Location = new System.Drawing.Point(8, 5); + this.titleLabel.Name = "titleLabel"; + this.titleLabel.Size = new System.Drawing.Size(169, 13); + this.titleLabel.TabIndex = 0; + this.titleLabel.Text = "New Actionscript 2 Interface"; + // + // groupBox2 + // + this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.groupBox2.BorderColor = System.Drawing.SystemColors.ControlDark; + this.groupBox2.Controls.Add(this.tableLayoutPanel2); + this.groupBox2.Location = new System.Drawing.Point(10, 53); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(468, 104); + this.groupBox2.TabIndex = 1; + this.groupBox2.TabStop = false; + this.groupBox2.UseTheme = true; + // + // tableLayoutPanel2 + // + this.tableLayoutPanel2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.tableLayoutPanel2.ColumnCount = 3; + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 27.42382F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 72.57618F)); + this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 83F)); + this.tableLayoutPanel2.Controls.Add(this.baseBrowse, 2, 2); + this.tableLayoutPanel2.Controls.Add(this.packageBrowse, 2, 0); + this.tableLayoutPanel2.Controls.Add(this.packageLabel, 0, 0); + this.tableLayoutPanel2.Controls.Add(this.packageBox, 1, 0); + this.tableLayoutPanel2.Controls.Add(this.baseBox, 1, 2); + this.tableLayoutPanel2.Controls.Add(this.baseLabel, 0, 2); + this.tableLayoutPanel2.Controls.Add(this.typeLabel, 0, 1); + this.tableLayoutPanel2.Controls.Add(this.classBox, 1, 1); + this.tableLayoutPanel2.Location = new System.Drawing.Point(3, 12); + this.tableLayoutPanel2.Name = "tableLayoutPanel2"; + this.tableLayoutPanel2.RowCount = 3; + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 28F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); + this.tableLayoutPanel2.Size = new System.Drawing.Size(460, 88); + this.tableLayoutPanel2.TabIndex = 0; + // + // flowLayoutPanel1 + // + this.flowLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.flowLayoutPanel1.AutoSize = true; + this.flowLayoutPanel1.Controls.Add(this.cancelButton); + this.flowLayoutPanel1.Controls.Add(this.okButton); + this.flowLayoutPanel1.Controls.Add(this.flowLayoutPanel6); + this.flowLayoutPanel1.FlowDirection = System.Windows.Forms.FlowDirection.RightToLeft; + this.flowLayoutPanel1.Location = new System.Drawing.Point(12, 163); + this.flowLayoutPanel1.Name = "flowLayoutPanel1"; + this.flowLayoutPanel1.Size = new System.Drawing.Size(466, 29); + this.flowLayoutPanel1.TabIndex = 2; + // + // cancelButton + // + this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.cancelButton.DisabledBackColor = System.Drawing.SystemColors.Control; + this.cancelButton.DisabledTextColor = System.Drawing.SystemColors.ControlDark; + this.cancelButton.Location = new System.Drawing.Point(388, 3); + this.cancelButton.Name = "cancelButton"; + this.cancelButton.Size = new System.Drawing.Size(75, 23); + this.cancelButton.TabIndex = 2; + this.cancelButton.Text = "Cancel"; + this.cancelButton.UseTheme = true; + this.cancelButton.UseVisualStyleBackColor = true; + // + // okButton + // + this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + this.okButton.DisabledBackColor = System.Drawing.SystemColors.Control; + this.okButton.DisabledTextColor = System.Drawing.SystemColors.ControlDark; + this.okButton.Enabled = false; + this.okButton.Location = new System.Drawing.Point(307, 3); + this.okButton.Name = "okButton"; + this.okButton.Size = new System.Drawing.Size(75, 23); + this.okButton.TabIndex = 1; + this.okButton.Text = "Ok"; + this.okButton.UseTheme = true; + this.okButton.UseVisualStyleBackColor = true; + // + // AS3InterfaceWizard + // + this.AcceptButton = this.okButton; + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.CancelButton = this.cancelButton; + this.ClientSize = new System.Drawing.Size(490, 204); + this.Controls.Add(this.flowLayoutPanel1); + this.Controls.Add(this.groupBox2); + this.Controls.Add(this.flowLayoutPanel9); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "AS3InterfaceWizard"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "New ActionScript Interface"; + this.Load += new System.EventHandler(this.AS3ClassWizard_Load); + ((System.ComponentModel.ISupportInitialize)(this.errorIcon)).EndInit(); + this.flowLayoutPanel6.ResumeLayout(false); + this.flowLayoutPanel6.PerformLayout(); + this.flowLayoutPanel9.ResumeLayout(false); + this.flowLayoutPanel9.PerformLayout(); + this.groupBox2.ResumeLayout(false); + this.tableLayoutPanel2.ResumeLayout(false); + this.tableLayoutPanel2.PerformLayout(); + this.flowLayoutPanel1.ResumeLayout(false); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label packageLabel; + private System.Windows.Forms.Label typeLabel; + private System.Windows.Forms.Label baseLabel; + private System.Windows.Forms.Label errorLabel; + private System.Windows.Forms.PictureBox errorIcon; + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel6; + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel9; + private System.Windows.Forms.Label titleLabel; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; + private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; + private System.Windows.Forms.TextBoxEx packageBox; + private System.Windows.Forms.ButtonEx packageBrowse; + private System.Windows.Forms.TextBoxEx classBox; + private System.Windows.Forms.TextBoxEx baseBox; + private System.Windows.Forms.ButtonEx baseBrowse; + private System.Windows.Forms.GroupBoxEx groupBox2; + private System.Windows.Forms.ButtonEx cancelButton; + private System.Windows.Forms.ButtonEx okButton; + } +} + diff --git a/External/Plugins/ASClassWizard/Wizards/ClassBrowser.cs b/External/Plugins/ASClassWizard/Wizards/ClassBrowser.cs index b38b45fb05..863abb3233 100644 --- a/External/Plugins/ASClassWizard/Wizards/ClassBrowser.cs +++ b/External/Plugins/ASClassWizard/Wizards/ClassBrowser.cs @@ -1,66 +1,35 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; using System.Windows.Forms; -using System.Reflection; using PluginCore; using PluginCore.Localization; using ASCompletion.Model; -using ASClassWizard.Wizards; -using ASClassWizard.Resources; using PluginCore.Controls; namespace ASClassWizard.Wizards { public partial class ClassBrowser : SmartForm { - - private MemberList all; - private List dataProvider; - private FlagType invalidFlag; - private FlagType validFlag; private int resultCount; private int topIndex; private int lastScore; private string matchToken; private int matchLen; - public MemberList ClassList - { - get { return this.all; } - set { this.all = value; } - } + public MemberList ClassList { get; set; } - public List DataProvider - { - get { return this.dataProvider; } - set { this.dataProvider = value; } - } + public List DataProvider { get; set; } - public FlagType ExcludeFlag - { - get { return this.invalidFlag; } - set { this.invalidFlag = value; } - } + public FlagType ExcludeFlag { get; set; } - public FlagType IncludeFlag - { - get { return this.validFlag; } - set { this.validFlag = value; } - } + public FlagType IncludeFlag { get; set; } - public string SelectedClass - { - get { return this.itemList.SelectedItem != null ? this.itemList.SelectedItem.ToString() : null; } - } + public string SelectedClass => itemList.SelectedItem?.ToString(); public ClassBrowser() { this.FormGuid = "a076f763-e85e-49a2-8688-a6d35b39e7c6"; - this.DataProvider = new List(); + this.DataProvider = new List(); InitializeComponent(); InitializeLocalization(); this.Font = PluginBase.Settings.DefaultFont; @@ -78,20 +47,21 @@ private void InitializeLocalization() private void ClassBrowser_Load(object sender, EventArgs e) { - ASClassWizard.Wizards.GListBox.GListBoxItem node; this.itemList.BeginUpdate(); this.itemList.Items.Clear(); if (this.ClassList != null) { foreach (MemberModel item in this.ClassList) { + // exclude types imported in the current file + if (item.Name != item.Type) continue; if (ExcludeFlag > 0) if ((item.Flags & ExcludeFlag) > 0) continue; if (IncludeFlag > 0) { if (!((item.Flags & IncludeFlag) > 0)) continue; } if (this.itemList.Items.Count > 0 && item.Name == this.itemList.Items[this.itemList.Items.Count - 1].ToString()) continue; - node = new ASClassWizard.Wizards.GListBox.GListBoxItem(item.Name, (item.Flags & FlagType.Interface) > 0 ? 6 : 8); + var node = new ListBox.ListBoxItem(item.Name, (item.Flags & FlagType.Interface) > 0 ? 6 : 8); this.itemList.Items.Add(node); this.DataProvider.Add(node); } @@ -106,16 +76,15 @@ private void ClassBrowser_Load(object sender, EventArgs e) } /// - /// Filder the list + /// Filter the list /// - private void filterBox_TextChanged( Object sender, EventArgs e) + private void filterBox_TextChanged(object sender, EventArgs e) { - string text = this.filterBox.Text; this.itemList.BeginUpdate(); this.itemList.Items.Clear(); topIndex = 0; - List result = this.FilterSmart(); + List result = this.FilterSmart(); this.itemList.Items.AddRange(result.ToArray()); this.itemList.EndUpdate(); @@ -128,7 +97,7 @@ private void filterBox_TextChanged( Object sender, EventArgs e) /// /// Filter using CompletionList smart comparison /// - private List FilterSmart() + private List FilterSmart() { lastScore = 99; resultCount = 0; @@ -138,11 +107,9 @@ private void filterBox_TextChanged( Object sender, EventArgs e) } /// - /// Filder the results + /// Filter the results /// - /// - /// - private bool FindAllItems( GListBox.GListBoxItem item ) + private bool FindAllItems(ListBox.ListBoxItem item) { if (matchLen == 0) return true; int score = PluginCore.Controls.CompletionList.SmartMatch(item.Text, matchToken, matchLen); @@ -156,34 +123,19 @@ private bool FindAllItems( GListBox.GListBoxItem item ) resultCount++; return true; } - else return false; + + return false; } /// /// Select None button click /// - /// - /// private void cancelButton_Click(object sender, EventArgs e) { this.itemList.SelectedItem = null; - this.DialogResult = DialogResult.OK; - this.Close(); - } - - - /// - /// Ok button click - /// - /// - /// - private void okButton_Click(object sender, EventArgs e) - { - this.DialogResult = DialogResult.OK; - this.Close(); } - private void itemList_DoubleClick( object sender, EventArgs e ) + private void itemList_DoubleClick(object sender, EventArgs e) { this.DialogResult = DialogResult.OK; this.Close(); diff --git a/External/Plugins/ASClassWizard/Wizards/ClassBrowser.designer.cs b/External/Plugins/ASClassWizard/Wizards/ClassBrowser.designer.cs index 44d5815191..59819236bb 100644 --- a/External/Plugins/ASClassWizard/Wizards/ClassBrowser.designer.cs +++ b/External/Plugins/ASClassWizard/Wizards/ClassBrowser.designer.cs @@ -33,11 +33,11 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.components = new System.ComponentModel.Container(); - this.cancelButton = new System.Windows.Forms.Button(); - this.okButton = new System.Windows.Forms.Button(); - this.itemList = new ASClassWizard.Wizards.GListBox(); + this.cancelButton = new System.Windows.Forms.ButtonEx(); + this.okButton = new System.Windows.Forms.ButtonEx(); + this.itemList = new ASClassWizard.Wizards.ListBox(); this.classBrowserBindingSource = new System.Windows.Forms.BindingSource(this.components); - this.filterBox = new System.Windows.Forms.TextBox(); + this.filterBox = new System.Windows.Forms.TextBoxEx(); ((System.ComponentModel.ISupportInitialize)(this.classBrowserBindingSource)).BeginInit(); this.SuspendLayout(); // @@ -45,7 +45,7 @@ private void InitializeComponent() // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Location = new System.Drawing.Point(219, 270); + this.cancelButton.Location = new System.Drawing.Point(219, 267); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 3; @@ -57,13 +57,12 @@ private void InitializeComponent() // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - this.okButton.Location = new System.Drawing.Point(137, 270); + this.okButton.Location = new System.Drawing.Point(137, 267); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 2; this.okButton.Text = "&Ok"; this.okButton.UseVisualStyleBackColor = true; - this.okButton.Click += new System.EventHandler(this.okButton_Click); // // itemList // @@ -71,9 +70,9 @@ private void InitializeComponent() this.itemList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.itemList.FormattingEnabled = true; this.itemList.ImageList = null; - this.itemList.Location = new System.Drawing.Point(12, 40); + this.itemList.Location = new System.Drawing.Point(12, 42); this.itemList.Name = "itemList"; - this.itemList.Size = new System.Drawing.Size(282, 225); + this.itemList.Size = new System.Drawing.Size(282, 235); this.itemList.TabIndex = 1; this.itemList.DoubleClick += new System.EventHandler(this.itemList_DoubleClick); // @@ -116,7 +115,7 @@ private void InitializeComponent() private System.Windows.Forms.Button cancelButton; private System.Windows.Forms.Button okButton; private System.Windows.Forms.BindingSource classBrowserBindingSource; - private GListBox itemList; + private ListBox itemList; private System.Windows.Forms.TextBox filterBox; } } \ No newline at end of file diff --git a/External/Plugins/ASClassWizard/Wizards/GListBox.cs b/External/Plugins/ASClassWizard/Wizards/GListBox.cs deleted file mode 100644 index 146e662d6e..0000000000 --- a/External/Plugins/ASClassWizard/Wizards/GListBox.cs +++ /dev/null @@ -1,101 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections; -using System.Text; -using System.Drawing; -using System.Windows.Forms; - -namespace ASClassWizard.Wizards -{ - - // GListBox class - public class GListBox : ListBox - { - private ImageList _myImageList; - public ImageList ImageList - { - get { return _myImageList; } - set { _myImageList = value; } - } - public GListBox() - { - // Set owner draw mode - this.ItemHeight = this.Font.Height + 2; - this.DrawMode = DrawMode.OwnerDrawFixed; - } - - protected override void OnDrawItem( System.Windows.Forms.DrawItemEventArgs e ) - { - e.DrawBackground(); - e.DrawFocusRectangle(); - GListBoxItem item; - Rectangle bounds = e.Bounds; - Size imageSize = _myImageList.ImageSize; - try - { - item = (GListBoxItem)Items[e.Index]; - if (item.ImageIndex != -1) - { - ImageList.Draw(e.Graphics, bounds.Left, bounds.Top, item.ImageIndex); - e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor), - bounds.Left + imageSize.Width, bounds.Top); - } - else - { - e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor), - bounds.Left, bounds.Top); - } - } - catch - { - if (e.Index != -1) - { - e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, - new SolidBrush(e.ForeColor), bounds.Left, bounds.Top); - } - else - { - e.Graphics.DrawString(Text, e.Font, new SolidBrush(e.ForeColor), - bounds.Left, bounds.Top); - } - } - base.OnDrawItem(e); - } - - - public class GListBoxItem - { - public int matchScore; - - private string _myText; - private int _myImageIndex; - - // properties - public string Text - { - get { return _myText; } - set { _myText = value; } - } - public int ImageIndex - { - get { return _myImageIndex; } - set { _myImageIndex = value; } - } - - //constructor - public GListBoxItem(string text, int index) - { - _myText = text; - _myImageIndex = index; - } - public GListBoxItem(string text) : this(text, -1) { } - public GListBoxItem() : this("") { } - public override string ToString() - { - return _myText; - } - - - }//End of GListBoxItem class - }//End of GListBox class -} diff --git a/External/Plugins/ASClassWizard/Wizards/IWizard.cs b/External/Plugins/ASClassWizard/Wizards/IWizard.cs new file mode 100644 index 0000000000..c5087e6f4d --- /dev/null +++ b/External/Plugins/ASClassWizard/Wizards/IWizard.cs @@ -0,0 +1,24 @@ +using System.Collections.Generic; +using System.Windows.Forms; +using ProjectManager.Projects; + +namespace ASClassWizard.Wizards +{ + public interface IWizard + { + Project Project { set; } + string Directory { set; } + string StartupClassName { set; } + string StartupPackage { set; } + string GetPackage(); + string GetName(); + string GetExtends(); + List GetInterfaces(); + bool IsPublic(); + bool IsDynamic(); + bool IsFinal(); + bool GetGenerateInheritedMethods(); + bool GetGenerateConstructor(); + DialogResult ShowDialog(); + } +} \ No newline at end of file diff --git a/External/Plugins/ASClassWizard/Wizards/ListBox.cs b/External/Plugins/ASClassWizard/Wizards/ListBox.cs new file mode 100644 index 0000000000..a70c496d03 --- /dev/null +++ b/External/Plugins/ASClassWizard/Wizards/ListBox.cs @@ -0,0 +1,84 @@ +using PluginCore; +using System.Drawing; +using System.Windows.Forms; + +namespace ASClassWizard.Wizards +{ + public class ListBox : ListBoxEx, IThemeHandler + { + public ListBox() + { + // Set owner draw mode + this.ItemHeight = this.Font.Height + 2; + this.DrawMode = DrawMode.OwnerDrawFixed; + } + + public ImageList ImageList { get; set; } + + public void AfterTheming() + { + this.BorderStyle = BorderStyle.FixedSingle; + this.BorderColor = PluginBase.MainForm.GetThemeColor("ListBox.BorderColor", SystemColors.ControlText); + this.ForeColor = PluginBase.MainForm.GetThemeColor("ListBox.ForeColor", SystemColors.ControlText); + this.BackColor = PluginBase.MainForm.GetThemeColor("ListBox.BackColor", SystemColors.Window); + this.Refresh(); + } + + protected override void OnDrawItem( System.Windows.Forms.DrawItemEventArgs e ) + { + e.DrawBackground(); + e.DrawFocusRectangle(); + Rectangle bounds = e.Bounds; + Size imageSize = ImageList.ImageSize; + try + { + var item = (ListBoxItem)Items[e.Index]; + if (item.ImageIndex != -1) + { + ImageList.Draw(e.Graphics, bounds.Left, bounds.Top, item.ImageIndex); + e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor), + bounds.Left + imageSize.Width, bounds.Top); + } + else + { + e.Graphics.DrawString(item.Text, e.Font, new SolidBrush(e.ForeColor), + bounds.Left, bounds.Top); + } + } + catch + { + if (e.Index != -1) + { + e.Graphics.DrawString(Items[e.Index].ToString(), e.Font, + new SolidBrush(e.ForeColor), bounds.Left, bounds.Top); + } + else + { + e.Graphics.DrawString(Text, e.Font, new SolidBrush(e.ForeColor), + bounds.Left, bounds.Top); + } + } + base.OnDrawItem(e); + } + + public class ListBoxItem + { + // properties + public string Text { get; set; } + + public int ImageIndex { get; set; } + + public ListBoxItem() : this("") { } + + public ListBoxItem(string text) : this(text, -1) { } + + public ListBoxItem(string text, int index) + { + Text = text; + ImageIndex = index; + } + + public override string ToString() => Text; + } + } +} diff --git a/External/Plugins/ASClassWizard/Wizards/PackageBrowser.cs b/External/Plugins/ASClassWizard/Wizards/PackageBrowser.cs index 12a414d476..04923e8693 100644 --- a/External/Plugins/ASClassWizard/Wizards/PackageBrowser.cs +++ b/External/Plugins/ASClassWizard/Wizards/PackageBrowser.cs @@ -1,9 +1,5 @@ using System; using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; using System.IO; using System.Windows.Forms; using ProjectManager.Controls; @@ -12,15 +8,12 @@ using PluginCore.Localization; using PluginCore.Controls; using ASClassWizard.Controls.TreeView; -using ASClassWizard.Resources; namespace ASClassWizard.Wizards { public partial class PackageBrowser : SmartForm { - List classpathList; - Project project; public PackageBrowser() { @@ -28,51 +21,32 @@ public PackageBrowser() InitializeComponent(); LocalizeTexts(); CenterToParent(); - this.FormGuid = "b5a7f1b4-959b-485b-a7d7-9b683191c0cf"; - this.Font = PluginBase.Settings.DefaultFont; - this.browserView.ImageList = Icons.ImageList; - this.browserView.BeforeExpand += onBeforeExpandNode; + FormGuid = "b5a7f1b4-959b-485b-a7d7-9b683191c0cf"; + Font = PluginBase.Settings.DefaultFont; + browserView.ImageList = Icons.ImageList; + browserView.BeforeExpand += OnBeforeExpandNode; } - private void LocalizeTexts() + void LocalizeTexts() { - this.inviteLabel.Text = TextHelper.GetString("Wizard.Label.ChosePackage"); - this.okButton.Text = TextHelper.GetString("Wizard.Button.Ok"); - this.cancelButton.Text = TextHelper.GetString("Wizard.Button.Cancel"); - this.Text = TextHelper.GetString("Wizard.Label.PackageSelection"); + inviteLabel.Text = TextHelper.GetString("Wizard.Label.ChosePackage"); + okButton.Text = TextHelper.GetString("Wizard.Button.Ok"); + cancelButton.Text = TextHelper.GetString("Wizard.Button.Cancel"); + Text = TextHelper.GetString("Wizard.Label.PackageSelection"); } - public Project Project - { - get { return project; } - set { this.project = value; } - } + public Project Project { get; set; } - public String Package - { - get { - return this.browserView.SelectedNode != null ? - ((SimpleDirectoryNode)this.browserView.SelectedNode).directoryPath : null; - } - } - - private void Initialize() - { - classpathList = new List(); - } + public string Package => ((SimpleDirectoryNode) browserView.SelectedNode)?.directoryPath; + void Initialize() => classpathList = new List(); - public void AddClassPath(string value) - { - classpathList.Add(value); - } + public void AddClassPath(string value) => classpathList.Add(value); - private void RefreshTree() + void RefreshTree() { - SimpleDirectoryNode node; - - this.browserView.BeginUpdate(); - this.browserView.Nodes.Clear(); + browserView.BeginUpdate(); + browserView.Nodes.Clear(); if (classpathList.Count > 0) { @@ -83,48 +57,39 @@ private void RefreshTree() { foreach (string item in Directory.GetDirectories(cp)) { - if (IsDirectoryExcluded(item) == false) + if (!IsDirectoryExcluded(item)) { - node = new SimpleDirectoryNode(item, Path.Combine(cp, item)); - node.ImageIndex = Icons.Folder.Index; - node.SelectedImageIndex = Icons.Folder.Index; - this.browserView.Nodes.Add(node); + var node = new SimpleDirectoryNode(item, Path.Combine(cp, item)) + { + ImageIndex = Icons.Folder.Index, + SelectedImageIndex = Icons.Folder.Index + }; + browserView.Nodes.Add(node); } } } catch { } } } - this.browserView.EndUpdate(); - + browserView.EndUpdate(); } - private void PackageBrowser_Load(object sender, EventArgs e) - { - RefreshTree(); - } + void PackageBrowser_Load(object sender, EventArgs e) => RefreshTree(); - private void onBeforeExpandNode(Object sender, TreeViewCancelEventArgs e) + void OnBeforeExpandNode(object sender, TreeViewCancelEventArgs e) { - SimpleDirectoryNode newNode; - - if (e.Node is SimpleDirectoryNode) + if (e.Node is SimpleDirectoryNode {dirty: true} node) { - SimpleDirectoryNode node = e.Node as SimpleDirectoryNode; - if (node.dirty) + node.dirty = false; + node.Nodes.Clear(); + foreach (string item in Directory.GetDirectories(node.directoryPath)) { - node.dirty = false; - e.Node.Nodes.Clear(); - - foreach (string item in Directory.GetDirectories(node.directoryPath)) + if (!IsDirectoryExcluded(item)) { - if (IsDirectoryExcluded(item) == false) - { - newNode = new SimpleDirectoryNode(item, Path.Combine(node.directoryPath, item)); - newNode.ImageIndex = Icons.Folder.Index; - newNode.SelectedImageIndex = Icons.Folder.Index; - node.Nodes.Add(newNode); - } + var newNode = new SimpleDirectoryNode(item, Path.Combine(node.directoryPath, item)); + newNode.ImageIndex = Icons.Folder.Index; + newNode.SelectedImageIndex = Icons.Folder.Index; + node.Nodes.Add(newNode); } } } @@ -133,8 +98,6 @@ private void onBeforeExpandNode(Object sender, TreeViewCancelEventArgs e) /// /// Verify if a given directory is hidden /// - /// - /// protected bool IsDirectoryExcluded(string path) { string dirName = Path.GetFileName(path); @@ -148,20 +111,17 @@ protected bool IsDirectoryExcluded(string path) return Project.IsPathHidden(path) && !Project.ShowHiddenPaths; } - - - private void okButton_Click(object sender, EventArgs e) + void okButton_Click(object sender, EventArgs e) { - this.DialogResult = DialogResult.OK; - this.Close(); + DialogResult = DialogResult.OK; + Close(); } - private void cancelButton_Click(object sender, EventArgs e) + void cancelButton_Click(object sender, EventArgs e) { - this.browserView.SelectedNode = null; - this.DialogResult = DialogResult.Cancel; - this.Close(); + browserView.SelectedNode = null; + DialogResult = DialogResult.Cancel; + Close(); } - } } diff --git a/External/Plugins/ASClassWizard/Wizards/PackageBrowser.designer.cs b/External/Plugins/ASClassWizard/Wizards/PackageBrowser.designer.cs index 5c36bff3aa..974a36fab2 100644 --- a/External/Plugins/ASClassWizard/Wizards/PackageBrowser.designer.cs +++ b/External/Plugins/ASClassWizard/Wizards/PackageBrowser.designer.cs @@ -1,6 +1,4 @@ -using ASClassWizard.Resources; - -namespace ASClassWizard.Wizards +namespace ASClassWizard.Wizards { partial class PackageBrowser { @@ -31,15 +29,15 @@ protected override void Dispose(bool disposing) private void InitializeComponent() { this.inviteLabel = new System.Windows.Forms.Label(); - this.browserView = new System.Windows.Forms.TreeView(); - this.okButton = new System.Windows.Forms.Button(); - this.cancelButton = new System.Windows.Forms.Button(); + this.browserView = new System.Windows.Forms.TreeViewEx(); + this.okButton = new System.Windows.Forms.ButtonEx(); + this.cancelButton = new System.Windows.Forms.ButtonEx(); this.SuspendLayout(); // // inviteLabel // this.inviteLabel.AutoSize = true; - this.inviteLabel.Location = new System.Drawing.Point(12, 9); + this.inviteLabel.Location = new System.Drawing.Point(11, 9); this.inviteLabel.Name = "inviteLabel"; this.inviteLabel.Size = new System.Drawing.Size(82, 13); this.inviteLabel.TabIndex = 1; @@ -48,15 +46,15 @@ private void InitializeComponent() // browserView // this.browserView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); - this.browserView.Location = new System.Drawing.Point(12, 25); + this.browserView.Location = new System.Drawing.Point(12, 27); this.browserView.Name = "browserView"; - this.browserView.Size = new System.Drawing.Size(260, 194); + this.browserView.Size = new System.Drawing.Size(260, 188); this.browserView.TabIndex = 2; // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.okButton.Location = new System.Drawing.Point(116, 226); + this.okButton.Location = new System.Drawing.Point(116, 224); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 3; @@ -68,7 +66,7 @@ private void InitializeComponent() // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Location = new System.Drawing.Point(198, 226); + this.cancelButton.Location = new System.Drawing.Point(198, 224); this.cancelButton.Name = "cancelButton"; this.cancelButton.Size = new System.Drawing.Size(75, 23); this.cancelButton.TabIndex = 4; diff --git a/External/Plugins/ASCompletion/ASCompletion.csproj b/External/Plugins/ASCompletion/ASCompletion.csproj index fc25566037..ab09845c23 100644 --- a/External/Plugins/ASCompletion/ASCompletion.csproj +++ b/External/Plugins/ASCompletion/ASCompletion.csproj @@ -1,194 +1,126 @@  - - - Debug - AnyCPU - 9.0.30729 - 2.0 - {4EBF2653-9654-4E40-880E-0046B3D6210E} - Library - Properties - ASCompletion - ASCompletion - - - - - 3.5 - - - v2.0 - - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - - - true - full - false - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - DEBUG;TRACE - prompt - 4 - - - pdbonly - true - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - DEBUG;TRACE - prompt - 4 - true - - - x86 - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - - - x86 - ..\..\..\FlashDevelop\Bin\Debug\Plugins\ - TRACE - true - - - - - - - - - - - - - - - - - Component - - - UserControl - - - ModelsExplorer.cs - - - - - - - - - - - - UserControl - - - - - - Component - - - Code - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - {61885F70-B4DC-4B44-852D-5D6D03F2A734} - PluginCore - False - - - - - - False - Microsoft .NET Framework 4 %28x86 and x64%29 - true - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - false - - - False - Windows Installer 3.1 - true - - - - - - - - - - - - - - - - - - - - - + + + + Debug + AnyCPU + {4EBF2653-9654-4E40-880E-0046B3D6210E} + Library + Properties + ASCompletion + ASCompletion + net48 + true + false + false + false + false + x64;x86;AnyCPU + + + true + full + false + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + prompt + 4 + 9 + + + false + none + true + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + 9 + + + true + full + false + x86 + DEBUG;TRACE + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + 4 + 9 + prompt + + + false + none + true + x86 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + 9 + + + true + full + false + x64 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + DEBUG;TRACE + 4 + 9 + prompt + + + false + none + true + x64 + ..\..\..\FlashDevelop\Bin\Debug\Plugins\ + TRACE + 9 + + + + + + + + + + {61885F70-B4DC-4B44-852D-5D6D03F2A734} + PluginCore + False + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/External/Plugins/ASCompletion/Commands/CallFlashIDE.cs b/External/Plugins/ASCompletion/Commands/CallFlashIDE.cs index 5748e7b03a..ebfad8fc94 100644 --- a/External/Plugins/ASCompletion/Commands/CallFlashIDE.cs +++ b/External/Plugins/ASCompletion/Commands/CallFlashIDE.cs @@ -1,22 +1,24 @@ using System; -using System.Text; -using System.Windows.Forms; -using PluginCore; -using PluginCore.Managers; -using ASCompletion; -using PluginCore.Localization; using System.IO; +using System.Windows.Forms; using ASCompletion.Context; -using PluginCore.Helpers; +using PluginCore; using PluginCore.Bridge; +using PluginCore.Helpers; +using PluginCore.Localization; +using PluginCore.Managers; namespace ASCompletion.Commands { public class CallFlashIDE { - private delegate void RunBackgroundInvoker(string exe, string args); - - static readonly private string[] FLASHIDE_PATH = { + static readonly string[] FLASHIDE_PATH = { + @"C:\Program Files\Adobe\Adobe Animate CC 2017\Animate.exe", + @"C:\Program Files (x86)\Adobe\Adobe Animate CC 2017\Animate.exe", + @"C:\Program Files\Adobe\Adobe Animate CC 2016\Animate.exe", + @"C:\Program Files (x86)\Adobe\Adobe Animate CC 2016\Animate.exe", + @"C:\Program Files\Adobe\Adobe Animate CC 2015\Animate.exe", + @"C:\Program Files (x86)\Adobe\Adobe Animate CC 2015\Animate.exe", @"C:\Program Files\Adobe\Adobe Flash CS5.5\Flash.exe", @"C:\Program Files (x86)\Adobe\Adobe Flash CS5.5\Flash.exe", @"C:\Program Files\Adobe\Adobe Flash CS5\Flash.exe", @@ -30,13 +32,13 @@ public class CallFlashIDE @"C:\Program Files\Macromedia\Flash MX 2004\Flash.exe", @"C:\Program Files (x86)\Macromedia\Flash MX 2004\Flash.exe" }; - static private DateTime lastRun; + private static DateTime lastRun; /// /// Return the path to the most recent Flash.exe /// /// - static public string FindFlashIDE() + public static string FindFlashIDE() { return FindFlashIDE(false); } @@ -46,13 +48,13 @@ static public string FindFlashIDE() /// /// Only AS3-capable authoring /// - static public string FindFlashIDE(bool AS3CapableOnly) + public static string FindFlashIDE(bool AS3CapableOnly) { string found = null; foreach (string flashexe in FLASHIDE_PATH) { if (File.Exists(flashexe) - && (!AS3CapableOnly || found.IndexOf("Flash CS") > 0)) + && (!AS3CapableOnly || found.IndexOfOrdinal("Flash CS") > 0 || found.IndexOfOrdinal("Animate") > 0)) { found = flashexe; break; @@ -66,18 +68,22 @@ static public string FindFlashIDE(bool AS3CapableOnly) /// /// /// Operation successful - static public bool Run(string pathToIDE, string cmdData) + public static bool Run(string pathToIDE, string cmdData) { if (BridgeManager.Active) pathToIDE = "Flash"; else { - if (pathToIDE != null && Directory.Exists(pathToIDE)) - pathToIDE = Path.Combine(pathToIDE, "Flash.exe"); - if (pathToIDE == null || !System.IO.File.Exists(pathToIDE)) + if (Directory.Exists(pathToIDE)) + { + var exe = Path.Combine(pathToIDE, "Animate.exe"); + if (!File.Exists(exe)) exe = Path.Combine(pathToIDE, "Flash.exe"); + pathToIDE = exe; + } + if (!File.Exists(pathToIDE)) { - string msg = TextHelper.GetString("Info.ConfigureFlashPath"); - string title = TextHelper.GetString("Info.ConfigurationRequired"); - DialogResult result = MessageBox.Show(msg, title, MessageBoxButtons.OKCancel); + var msg = TextHelper.GetString("Info.ConfigureFlashPath"); + var title = TextHelper.GetString("Info.ConfigurationRequired"); + var result = MessageBox.Show(msg, title, MessageBoxButtons.OKCancel); if (result == DialogResult.OK) { PluginBase.MainForm.ShowSettingsDialog("ASCompletion", "Flash"); @@ -94,7 +100,7 @@ static public bool Run(string pathToIDE, string cmdData) if (cmdData != null) { args = PluginBase.MainForm.ProcessArgString(cmdData); - if (args.IndexOf('"') < 0) args = '"' + args + '"'; + if (!args.Contains('"')) args = '"' + args + '"'; } // execution @@ -104,7 +110,7 @@ static public bool Run(string pathToIDE, string cmdData) try { - string file = args.StartsWith("\"") ? args.Substring(1, args.Length-2) : args; + string file = args.StartsWith('\"') ? args.Substring(1, args.Length-2) : args; if (BridgeManager.Active && BridgeManager.Settings.TargetRemoteIDE && File.Exists(file) && Path.GetExtension(file) == ".jsfl" && file[0] <= 'H') { diff --git a/External/Plugins/ASCompletion/Commands/CreateTrustFile.cs b/External/Plugins/ASCompletion/Commands/CreateTrustFile.cs index 58ab9a33f8..39a654aa33 100644 --- a/External/Plugins/ASCompletion/Commands/CreateTrustFile.cs +++ b/External/Plugins/ASCompletion/Commands/CreateTrustFile.cs @@ -1,10 +1,8 @@ using System; using System.IO; using System.Text; -using System.Collections; -using PluginCore.Managers; using PluginCore.Helpers; -using PluginCore; +using PluginCore.Managers; namespace ASCompletion.Commands { @@ -20,19 +18,19 @@ public class CreateTrustFile /// Operation successful public static bool Run(string name, string path) { - if (name == null || path == null) return false; + if (name is null || path is null) return false; try { path += " "; string separator = Path.DirectorySeparatorChar.ToString(); string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); - string fixedPath = String.Format(FULLPATH, appDataDir, separator); + string fixedPath = string.Format(FULLPATH, appDataDir, separator); if (!Directory.Exists(fixedPath)) Directory.CreateDirectory(fixedPath); string file = Path.Combine(fixedPath, name); if (File.Exists(file)) { string src = FileHelper.ReadFile(file, Encoding.Default); - if (src.IndexOf(path) < 0) FileHelper.AddToFile(file, "\r\n" + path, Encoding.Default); + if (!src.Contains(path)) FileHelper.AddToFile(file, "\r\n" + path, Encoding.Default); } else FileHelper.WriteFile(file, path, Encoding.Default); return true; diff --git a/External/Plugins/ASCompletion/Completion/ASComplete.cs b/External/Plugins/ASCompletion/Completion/ASComplete.cs index d85217fac4..7cc0e1e44e 100644 --- a/External/Plugins/ASCompletion/Completion/ASComplete.cs +++ b/External/Plugins/ASCompletion/Completion/ASComplete.cs @@ -1,610 +1,705 @@ -/* - * Code completion - */ - -using System; -using System.Windows.Forms; +using System; using System.Collections; using System.Collections.Generic; +using System.Drawing; +using System.IO; +using System.Linq; using System.Text; using System.Text.RegularExpressions; -using System.Diagnostics; +using System.Windows.Forms; +using ASCompletion.Commands; +using ASCompletion.Context; +using ASCompletion.Model; using PluginCore; -using PluginCore.Managers; using PluginCore.Controls; -using ASCompletion.Model; -using ASCompletion.Context; -using System.IO; using PluginCore.Helpers; using PluginCore.Localization; +using PluginCore.Managers; using PluginCore.Utilities; using ScintillaNet; +using ScintillaNet.Lexers; namespace ASCompletion.Completion { public delegate void ResolvedContextChangeHandler(ResolvedContext resolved); - /// - /// Description of ASComplete. - /// - public class ASComplete - { - - #region regular_expressions_definitions - static private readonly RegexOptions ro_csr = ASFileParserRegexOptions.SinglelineComment | RegexOptions.RightToLeft; - // refine last expression - static private readonly Regex re_refineExpression = new Regex("[^\\[\\]{}(:,=+*/%!<>-]*$", ro_csr); - // code cleaning - static private readonly Regex re_whiteSpace = new Regex("[\\s]+", ASFileParserRegexOptions.SinglelineComment); - // balanced matching, see: http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx - static private readonly Regex re_balancedParenthesis = new Regex("\\([^()]*(((?\\()[^()]*)+((?\\))[^()]*)+)*(?(Open)(?!))\\)", - ASFileParserRegexOptions.SinglelineComment); - // expressions - static private readonly Regex re_sub = new Regex("^#(?[0-9]+)~$", ASFileParserRegexOptions.SinglelineComment); - #endregion - - #region completion_history - // stores last char entered - static private LastCharData LastChar; + /// + /// Description of ASComplete. + /// + public class ASComplete + { + + #region regular_expressions_definitions + + const RegexOptions ro_csr = ASFileParserRegexOptions.SinglelineComment | RegexOptions.RightToLeft; + + // refine last expression + static readonly Regex re_refineExpression = new Regex("[^\\[\\]'\"{}(:,=+*/%!<>-]*$", ro_csr); + // code cleaning + static readonly Regex re_whiteSpace = new Regex("[\\s]+", ASFileParserRegexOptions.SinglelineComment); + // balanced matching, see: http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx + static readonly Regex re_balancedParenthesis = new Regex("\\([^()]*(((?\\()[^()]*)+((?\\))[^()]*)+)*(?(Open)(?!))\\)", + ASFileParserRegexOptions.SinglelineComment); + // expressions + static readonly Regex re_sub = new Regex("^#(?[0-9]+)~$", ASFileParserRegexOptions.SinglelineComment); + #endregion + + #region fields + public static Keys HelpKeys = Keys.F1; + //stores the currently used class namespace and name - static private String currentClassHash = null; + static string currentClassHash; //stores the last completed member for each class - static private IDictionary completionHistory = new Dictionary(); + protected static readonly IDictionary completionHistory = new Dictionary(); + + public static ResolvedContext CurrentResolvedContext; + public static event ResolvedContextChangeHandler OnResolvedContextChanged; - static public ResolvedContext CurrentResolvedContext; - static public event ResolvedContextChangeHandler OnResolvedContextChanged; #endregion #region application_event_handlers /// - /// Character written in editor - /// - /// Character inserted - static public bool OnChar(ScintillaControl Sci, int Value, bool autoHide) - { - IASContext ctx = ASContext.Context; - if (ctx.Settings == null || !ctx.Settings.CompletionEnabled) - return false; - try - { - if (Sci.IsSelectionRectangle) + /// Character written in editor + /// + /// Scintilla Control + /// Character inserted + /// Auto-started completion (is false when pressing Ctrl+Space or Ctrl+Alt+Space) + /// Auto-completion has been handled + public static bool OnChar(ScintillaControl sci, int value, bool autoHide) + { + if (sci.IsSelectionRectangle) return false; + var ctx = ASContext.Context; + try + { + // code auto + int eolMode = sci.EOLMode; + if (((value == '\n') && (eolMode != 1)) || ((value == '\r') && (eolMode == 1))) + { + if (ASContext.HasContext && ctx.IsFileValid) HandleStructureCompletion(sci); return false; - // code auto - int eolMode = Sci.EOLMode; - if (((Value == 10) && (eolMode != 1)) || ((Value == 13) && (eolMode == 1))) - { - if (ASContext.HasContext && ASContext.Context.IsFileValid) HandleStructureCompletion(Sci); - return false; - } - - int position = Sci.CurrentPos; + } + var position = sci.CurrentPos; if (position < 2) return false; - - // ignore text in comments & quoted text - Sci.Colourise(0,-1); - int stylemask = (1 << Sci.StyleBits) -1; - int style = Sci.StyleAt(position-1) & stylemask; - if (!IsTextStyle(style) && !IsTextStyle(Sci.StyleAt(position) & stylemask)) - { - // documentation completion - if (ASContext.CommonSettings.SmartTipsEnabled && IsCommentStyle(style)) - return ASDocumentation.OnChar(Sci, Value, position, style); - else if (autoHide) + var prevValue = (char) sci.CharAt(position - 2); + var skipQuoteCheck = false; + sci.Colourise(0, -1); + var style = sci.BaseStyleAt(position - 1); + var features = ctx.Features; + if (features.hasStringInterpolation && (IsStringStyle(style) || IsCharStyle(style))) + { + var stringTypeChar = sci.GetStringType(position - 2); // start from -2 in case the inserted char is ' or " + // string interpolation + if (features.stringInterpolationQuotes.Contains(stringTypeChar) + && IsMatchingQuote(stringTypeChar, sci.BaseStyleAt(position - 2))) { - // close quotes - HandleClosingChar(Sci, Value, position); - return false; - } - } - - // close brace/parents - if (autoHide) HandleClosingChar(Sci, Value, position); - - // stop here if the class is not valid - if (!ASContext.HasContext || !ASContext.Context.IsFileValid) return false; - ContextFeatures features = ASContext.Context.Features; - - // handle - switch (Value) - { - case '.': - if (features.dot == "." || !autoHide) - return HandleDotCompletion(Sci, autoHide); - break; - - case '>': - if (features.dot == "->" && Sci.CharAt(position - 2) == '-') - return HandleDotCompletion(Sci, autoHide); - break; - - case ' ': - position--; - string word = GetWordLeft(Sci, ref position); - if (word.Length <= 0) + if (value == '$' && !ctx.CodeComplete.IsEscapedCharacter(sci, position - 1, '$')) + return HandleInterpolationCompletion(sci, autoHide, false); + if (value == '{' && prevValue == '$' && !ctx.CodeComplete.IsEscapedCharacter(sci, position - 2, '$')) { - char c = (char)Sci.CharAt(position); - if (c == ':' && features.hasEcmaTyping) - return HandleColonCompletion(Sci, "", autoHide); - else if (autoHide && (c == '(' || c == ',') && !ASContext.CommonSettings.DisableCallTip) - return HandleFunctionCompletion(Sci, autoHide); - break; + if (autoHide) HandleAddClosingBraces(sci, (char) value, true); + return HandleInterpolationCompletion(sci, autoHide, true); } - if (word == "class" || word == "package" || word == "interface") - return false; - // new/extends/instanceof/... - if (features.HasTypePreKey(word)) - return HandleNewCompletion(Sci, "", autoHide, word); - // import - if (features.hasImports && (word == features.importKey || word == features.importKeyAlt)) - return HandleImportCompletion(Sci, "", autoHide); - // public/internal/private/protected/static - if (word == features.publicKey || word == features.internalKey - || word == features.protectedKey || word == features.privateKey - || word == features.staticKey || word == features.inlineKey) - return HandleDeclarationCompletion(Sci, "", autoHide); - // override - if (word == features.overrideKey) - return ASGenerator.HandleGeneratorCompletion(Sci, autoHide, word); - break; - - case ':': - if (features.hasEcmaTyping) + if (ctx.CodeComplete.IsStringInterpolationStyle(sci, position - 2)) + skipQuoteCheck = true; // continue on with regular completion + } + } + + if (!skipQuoteCheck) + { + // ignore text in comments & quoted text + if (!IsTextStyle(style) && !IsTextStyle(sci.BaseStyleAt(position))) + { + // documentation completion + if (ASContext.CommonSettings.SmartTipsEnabled && IsCommentStyle(style)) { - return HandleColonCompletion(Sci, "", autoHide); + return ASDocumentation.OnChar(sci, value, position, style); } - else break; - - case '<': - if (features.hasGenerics && position > 2) + if (autoHide) { - char c0 = (char)Sci.CharAt(position - 2); - bool result = false; - if (c0 == '.' /*|| Char.IsLetterOrDigit(c0)*/) - return HandleColonCompletion(Sci, "", autoHide); - return result; + // close quotes + HandleAddClosingBraces(sci, (char) value, true); } - else break; + return false; + } + } + + // close brace/parens + if (autoHide) HandleAddClosingBraces(sci, (char) value, true); + + // stop here if the class is not valid + if (!ASContext.HasContext || !ctx.IsFileValid) return false; - case '(': + if (ctx.CodeComplete.IsAvailable(ctx, autoHide)) + { + // Custom completion + if (ctx.CodeComplete.OnChar(sci, value, prevValue, autoHide)) return true; + switch (value) + { + case '.': + if (features.dot == "." || !autoHide) return HandleDotCompletion(sci, autoHide); + break; + + case '>': + if (features.dot == "->" && prevValue == '-') return HandleDotCompletion(sci, autoHide); + break; + + case ' ': + if (ctx.CodeComplete.HandleWhiteSpaceCompletion(sci, position, autoHide)) return true; + break; + + case ':': + if (features.hasEcmaTyping) return HandleColonCompletion(sci, string.Empty, autoHide); + break; + + case '<': + if (features.hasGenerics && position > 2) + { + var c0 = (char) sci.CharAt(position - 2); + //TODO: We should check if we are actually on a generic type + if ((ctx.CurrentModel.Version == 3 && c0 == '.') || char.IsLetterOrDigit(c0)) + return HandleColonCompletion(sci, string.Empty, autoHide); + return false; + } + break; + + default: + AutoStartCompletion(sci, position); + break; + } + } + switch (value) + { + case '(': case ',': - if (!ASContext.CommonSettings.DisableCallTip) - return HandleFunctionCompletion(Sci, autoHide); - else return false; + return !ASContext.CommonSettings.DisableCallTip && HandleFunctionCompletion(sci, autoHide); - case ')': + case ')': if (UITools.CallTip.CallTipActive) UITools.CallTip.Hide(); - return false; + return false; - case '*': - if (features.hasImportsWildcard) return CodeAutoOnChar(Sci, Value); + case '*': + if (features.hasImportsWildcard) return CodeAutoOnChar(sci, value); break; case ';': - if (!ASContext.CommonSettings.DisableCodeReformat) - ReformatLine(Sci, position); + if (!ASContext.CommonSettings.DisableCodeReformat) ReformatLine(sci, position); break; + } + } + catch (Exception ex) + { + #if DEBUG + throw; + #else + ErrorManager.ShowError(/*"Completion error",*/ ex); + #endif + } - default: - AutoStartCompletion(Sci, position); - break; - } - } - catch (Exception ex) { - ErrorManager.ShowError(/*"Completion error",*/ ex); - } - - // CodeAuto context - if (!PluginCore.Controls.CompletionList.Active) LastExpression = null; - return false; + // CodeAuto context + if (!CompletionList.Active) LastExpression = null; + return false; } - internal static void OnTextChanged(ScintillaControl sci, int position, int length, int linesAdded) + /// + /// Character written in editor + /// + /// Scintilla Control + /// Character inserted + /// Character before inserted character + /// Auto-started completion (is false when pressing Ctrl+Space or Ctrl+Alt+Space) + /// Auto-completion has been handled + protected virtual bool OnChar(ScintillaControl sci, int value, char prevValue, bool autoHide) => false; + + /// + /// Returns true if completion is available + /// + /// + /// Auto-started completion (is false when pressing Ctrl+Space or Ctrl+Alt+Space) + /// true if completion is available + protected virtual bool IsAvailable(IASContext ctx, bool autoHide) => ctx.Settings != null && ctx.Settings.CompletionEnabled; + + /// + /// Returns true if position is available for tooltip + /// + /// Scintilla Control + /// Cursor position + /// true if position is available for tooltip + protected internal virtual bool IsAvailableForToolTip(ScintillaControl sci, int position) { - // TODO track text changes -> LastChar + var style = sci.StyleAt(position); + return IsTextStyle(style) || (ASContext.Context.Features.hasInterfaces && IsStringInterpolationStyle(sci, position)); } - private static void HandleClosingChar(ScintillaControl Sci, int Value, int position) + /// + /// Handle shortcuts + /// + /// Test keys + /// Scintilla Control + /// + public static bool OnShortcut(Keys keys, ScintillaControl sci) { - if (!ASContext.CommonSettings.AddClosingBraces) return; - - int stylemask = (1 << Sci.StyleBits) - 1; - int style = Sci.StyleAt(position - 1) & stylemask; - char c = (char)Sci.CharAt(position); - if (c > 32 && ")]}-+/>*,;".IndexOf(c) < 0) return; - - if (IsTextStyle(Sci.StyleAt(position - 2) & stylemask)) + if (sci.IsSelectionRectangle) return false; + // dot complete + if (keys == (Keys.Control | Keys.Space)) { - if (Value == '"') - { - ASComplete.InsertSymbol(Sci, "\""); - } - else if (Value == '\'') - { - ASComplete.InsertSymbol(Sci, "'"); - } - else if (Value == '[') - { - ASComplete.InsertSymbol(Sci, "]"); - } - else if (Value == '(') - { - ASComplete.InsertSymbol(Sci, ")"); - } - else if (Value == ')') - { - if (LastChar != null - && LastChar.Value == '(' - && LastChar.Position == position - 1) - { - LastChar = null; - Sci.DeleteBack(); - Sci.SetSel(position, position); - } - } - else if (Value == ']') - { - if (LastChar != null - && LastChar.Value == '[' - && LastChar.Position == position - 1) - { - LastChar = null; - Sci.DeleteBack(); - Sci.SetSel(position, position); - } - } - LastChar = new LastCharData(Value, position); + if (!ASContext.HasContext || !ASContext.Context.IsFileValid) return false; + // try to get completion as if we had just typed the previous char + if (OnChar(sci, sci.CharAt(sci.PositionBefore(sci.CurrentPos)), false)) return true; + // force dot completion + OnChar(sci, '.', false); + return true; } - else + if (keys == Keys.Back) { - if (Value == '"') - { - if (LastChar != null - && LastChar.Value == '"' - && LastChar.Position == position - 1) - { - LastChar = null; - Sci.DeleteBack(); - Sci.SetSel(position, position); - } - } - else if (Value == '\'') - { - if (LastChar != null - && LastChar.Value == '\'' - && LastChar.Position == position - 1) - { - LastChar = null; - Sci.DeleteBack(); - Sci.SetSel(position, position); - } - } - } - } - - /// - /// Handle shortcuts - /// - /// Test keys - /// - static public bool OnShortcut(Keys keys, ScintillaControl Sci) - { - if (Sci.IsSelectionRectangle) + HandleAddClosingBraces(sci, sci.CurrentChar, false); return false; - - // dot complete - if (keys == (Keys.Control | Keys.Space)) - { - if (ASContext.HasContext && ASContext.Context.IsFileValid) - { - // force dot completion - OnChar(Sci, '.', false); - return true; - } - else return false; - } - // show calltip - else if (keys == (Keys.Control | Keys.Shift | Keys.Space)) - { - if (ASContext.HasContext && ASContext.Context.IsFileValid) - { - //HandleFunctionCompletion(Sci); - // force function completion - OnChar(Sci, '(', false); - return true; - } - else return false; - } + } + // show calltip + if (keys == (Keys.Control | Keys.Shift | Keys.Space)) + { + if (!ASContext.HasContext || !ASContext.Context.IsFileValid) return false; + // force function completion + OnChar(sci, '(', false); + return true; + } // project types completion - else if (keys == (Keys.Control | Keys.Alt | Keys.Space)) + if (keys == (Keys.Control | Keys.Alt | Keys.Space)) { - if (ASContext.HasContext && ASContext.Context.IsFileValid && !ASContext.Context.Settings.LazyClasspathExploration) + if (!ASContext.HasContext + || !ASContext.Context.IsFileValid + || ASContext.Context.Settings.LazyClasspathExploration) return false; + var word = GetWordLeft(sci, sci.CurrentPos - 1); + if (word.Length > 0) { - int position = Sci.CurrentPos-1; - string tail = GetWordLeft(Sci, ref position); - ContextFeatures features = ASContext.Context.Features; - if (tail.IndexOf(features.dot) < 0 && features.HasTypePreKey(tail)) tail = ""; - // display the full project classes list - HandleAllClassesCompletion(Sci, tail, false, true); - return true; + var features = ASContext.Context.Features; + if (!word.Contains(features.dot) && features.HasTypePreKey(word)) word = string.Empty; } - else return false; + // display the full project classes list + HandleAllClassesCompletion(sci, word, false, true); + return true; } - // hot build - else if (keys == (Keys.Control | Keys.Enter)) - { - // project build - DataEvent de = new DataEvent(EventType.Command, "ProjectManager.HotBuild", null); - EventManager.DispatchEvent(ASContext.Context, de); - // - if (!de.Handled) - { - // quick build + // hot build + if (keys == (Keys.Control | Keys.Enter)) + { + // project build + var de = new DataEvent(EventType.Command, "ProjectManager.HotBuild", null); + EventManager.DispatchEvent(ASContext.Context, de); + if (!de.Handled) + { + // quick build if (!ASContext.Context.BuildCMD(true)) { // Flash IDE - if (PluginBase.CurrentProject == null) + if (PluginBase.CurrentProject is null) { - string idePath = ASContext.CommonSettings.PathToFlashIDE; - if (idePath != null && File.Exists(Path.Combine(idePath, "Flash.exe"))) + var idePath = ASContext.CommonSettings.PathToFlashIDE; + if (File.Exists(Path.Combine(idePath, "Flash.exe"))) { - string cmd = Path.Combine("Tools", Path.Combine("flashide", "testmovie.jsfl")); + var cmd = Path.Combine("Tools", "flashide", "testmovie.jsfl"); cmd = PathHelper.ResolvePath(cmd); - if (cmd != null && File.Exists(cmd)) - Commands.CallFlashIDE.Run(idePath, cmd); + if (File.Exists(cmd)) CallFlashIDE.Run(idePath, cmd); } } } - } - return true; - } - // help - else if (keys == Keys.F1 && ASContext.HasContext && ASContext.Context.IsFileValid) - { - ResolveElement(Sci, "ShowDocumentation"); - return true; - } + } + return true; + } + // help + if (keys == HelpKeys && ASContext.HasContext && ASContext.Context.IsFileValid) + { + ResolveElement(sci, "ShowDocumentation"); + return true; + } return false; } /// /// Fire the completion automatically + /// Scintilla Control + /// Cursor position /// - private static void AutoStartCompletion(ScintillaControl Sci, int position) + static void AutoStartCompletion(ScintillaControl sci, int position) + { + if (CompletionList.Active + || !ASContext.Context.Features.hasEcmaTyping + || ASContext.CommonSettings.AlwaysCompleteWordLength <= 0) return; + // fire completion if starting to write a word + var wordStart = sci.WordStartPosition(position, true); + if (position - wordStart < ASContext.CommonSettings.AlwaysCompleteWordLength) return; + var c = (char) sci.CharAt(wordStart); + if (char.IsDigit(c)) return; + var characterClass = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage).characterclass.Characters; + if (!characterClass.Contains(c)) return; + // give a guess to the context (do not complete where it should not) + var pos = wordStart - 1; + var hadWS = false; + var canComplete = false; + while (pos > 0) + { + c = (char) sci.CharAt(pos--); + if (hadWS && characterClass.Contains(c)) break; + if (c == '<' && ((char) sci.CharAt(pos + 2) == '/' || !hadWS)) break; + if (":;,+-*%!&|<>/{}()[=?".Contains(c)) + { + canComplete = true; + // TODO Add HTML lookup here + if (pos > 0 && c == '/' && (char) sci.CharAt(pos) == '<') canComplete = false; + break; + } + if (c <= ' ') + { + if (c == '\r' || c == '\n') + { + canComplete = true; + break; + } + if (pos > 1 && sci.BaseStyleAt(pos - 1) == (int) CPP.GLOBALCLASS) + { + canComplete = true; + break; + } + hadWS = true; + } + else if (c != '.' && !characterClass.Contains(c)) + { + // TODO support custom DOT + canComplete = false; + break; + } + } + canComplete |= hadWS + // for example: override ad + && sci.GetWordFromPosition(pos) is {Length: > 0} word + && ASContext.Context.Features.accessKeywords.Contains(word); + if (canComplete) HandleDotCompletion(sci, true); + } + #endregion + + #region add_closing_braces + + public static void HandleAddClosingBraces(ScintillaControl sci, char c, bool addedChar) { - if (!CompletionList.Active && ASContext.Context.Features.hasEcmaTyping - && ASContext.CommonSettings.AlwaysCompleteWordLength > 0) - { - // fire completion if starting to write a word - bool valid = true; - int n = ASContext.CommonSettings.AlwaysCompleteWordLength; - int wordStart = Sci.WordStartPosition(position, true); - if (position - wordStart != n) - return; - char c = (char)Sci.CharAt(wordStart); - string characterClass = ScintillaControl.Configuration.GetLanguage(Sci.ConfigurationLanguage).characterclass.Characters; - if (Char.IsDigit(c) || characterClass.IndexOf(c) < 0) + if (!ASContext.CommonSettings.AddClosingBraces) return; + var ctx = ASContext.Context; + if (addedChar) + { + if (IsMatchingQuote(c, sci.BaseStyleAt(sci.CurrentPos - 2)) && ctx.CodeComplete.IsEscapedCharacter(sci, sci.CurrentPos - 1)) + { return; - // give a guess to the context (do not complete where it should not) - if (valid) - { - int pos = wordStart - 1; - c = ' '; - char c2 = ' '; - bool hadWS = false; - bool canComplete = false; - while (pos > 0) + } + + bool undo = false; + byte styleBefore; + byte styleAfter; + + sci.BeginUndoAction(); + + if (c == '"' || c == '\'') + { + // Get the before & after style values unaffected by the entered char + sci.DeleteBack(); + sci.Colourise(0, -1); + styleBefore = (byte) sci.BaseStyleAt(sci.CurrentPos - 1); + styleAfter = (byte) sci.BaseStyleAt(sci.CurrentPos); + sci.AddText(1, c.ToString()); + undo = true; + } + else + { + styleBefore = (byte) sci.BaseStyleAt(sci.CurrentPos - 2); + styleAfter = (byte) sci.BaseStyleAt(sci.CurrentPos); + } + + // not inside a string literal + int position = sci.CurrentPos - 1; + if (!(IsStringStyle(styleBefore) && IsStringStyle(styleAfter)) && !(IsCharStyle(styleBefore) && IsCharStyle(styleAfter)) + || ctx.CodeComplete.IsStringInterpolationStyle(sci, position)) + { + char nextChar = sci.CurrentChar; + int nextPos = sci.CurrentPos; + + while (nextChar == ' ' || nextChar == '\t') // Don't skip new line characters { - c = (char)Sci.CharAt(pos--); - if (hadWS && characterClass.IndexOf(c) >= 0) break; - else if (c == '<' && ((char)Sci.CharAt(pos + 2) == '/' || !hadWS)) break; - else if (":;,+-*%!&|<>/{}()[=?".IndexOf(c) >= 0) - { - canComplete = true; - // TODO Add HTML lookup here - if (pos > 0) - { - char c0 = (char)Sci.CharAt(pos); - if (c == '/' && c0 == '<') canComplete = false; - } - break; - } - else if (c <= 32) - { - if (c == '\r' || c == '\n') - { - canComplete = true; - break; - } - else if (pos > 1) - { - int style = Sci.BaseStyleAt(pos - 1); - if (style == 19) - { - canComplete = true; - break; - } - } - hadWS = true; - } - else if (c != '.' && characterClass.IndexOf(c) < 0) + nextPos++; + nextChar = (char) sci.CharAt(nextPos); + } + + foreach (var brace in ASContext.CommonSettings.AddClosingBracesRules) + { + // Handle opening first for braces that have equal opening & closing chars + if (HandleBraceOpen(sci, brace, c, styleAfter, styleBefore) + || HandleBraceClose(sci, brace, c, nextChar, nextPos)) { - // TODO support custom DOT - canComplete = false; + undo = false; break; } - c2 = c; } - if (canComplete) HandleDotCompletion(Sci, true); } - } - } - #endregion - - #region plugin commands - /// - /// Using the text under at cursor position, search and open the object/class/member declaration - /// - /// Control - /// Declaration was found - static public bool DeclarationLookup(ScintillaControl Sci) - { - if (!ASContext.Context.IsFileValid || (Sci == null)) return false; - - // get type at cursor position - int position = Sci.WordEndPosition(Sci.CurrentPos, true); - ASResult result = GetExpressionType(Sci, position); - - // browse to package folder - if (result.IsPackage && result.InFile != null) - { - return ASContext.Context.BrowseTo(result.InFile.Package); - } - - // open source and show declaration - if (!result.IsNull()) - { - if (result.Member != null && (result.Member.Flags & FlagType.AutomaticVar) > 0) - return false; + else if (IsMatchingQuote(c, styleAfter)) + { + char nextChar = sci.CurrentChar; + int nextPos = sci.CurrentPos; - // open the file - return OpenDocumentToDeclaration(Sci, result); - } - // show overriden method - else if (ASContext.Context.CurrentMember != null - && ASContext.Context.Features.overrideKey != null - && Sci.GetWordFromPosition(position) == ASContext.Context.Features.overrideKey) - { - MemberModel member = ASContext.Context.CurrentMember; - if ((member.Flags & FlagType.Override) > 0) - { - ClassModel tmpClass = ASContext.Context.CurrentClass; - if (tmpClass != null) + while (nextChar == ' ' || nextChar == '\t') // Don't skip new line characters { - tmpClass.ResolveExtends(); - tmpClass = tmpClass.Extends; - while (tmpClass != null && !tmpClass.IsVoid()) + nextPos++; + nextChar = (char) sci.CharAt(nextPos); + } + + foreach (var brace in ASContext.CommonSettings.AddClosingBracesRules) + { + if (HandleBraceClose(sci, brace, c, nextChar, nextPos)) { - MemberModel found = tmpClass.Members.Search(member.Name, 0, 0); - if (found != null) - { - result = new ASResult(); - result.Member = found; - result.InFile = tmpClass.InFile; - result.InClass = tmpClass; - OpenDocumentToDeclaration(Sci, result); - break; - } - tmpClass = tmpClass.Extends; + undo = false; + break; } } } - } - return false; - } - - /// - /// Show resolved element declaration - /// - static public bool OpenDocumentToDeclaration(ScintillaControl Sci, ASResult result) - { - FileModel model = result.InFile - ?? ((result.Member != null && result.Member.InFile != null) ? result.Member.InFile : null) - ?? ((result.Type != null) ? result.Type.InFile : null); - if (model == null || model.FileName == "") return false; - ClassModel inClass = result.InClass ?? result.Type; - // for Back command - if (Sci != null) - { - int lookupLine = Sci.LineFromPosition(Sci.CurrentPos); - int lookupCol = Sci.CurrentPos - Sci.PositionFromLine(lookupLine); - ASContext.Panel.SetLastLookupPosition(ASContext.Context.CurrentFile, lookupLine, lookupCol); + sci.EndUndoAction(); + if (undo) sci.Undo(); } - - if (model != ASContext.Context.CurrentModel) + else { - // cached files declarations have no line numbers - if (model.CachedModel && model.Context != null) + char open = (char) sci.CharAt(sci.CurrentPos - 1); + + if (IsMatchingQuote(open, sci.BaseStyleAt(sci.CurrentPos - 2)) && ctx.CodeComplete.IsEscapedCharacter(sci, sci.CurrentPos - 1)) { - ASFileParser.ParseFile(model); - if (inClass != null && !inClass.IsVoid()) - { - inClass = model.GetClassByName(inClass.Name); - if (result.Member != null) - result.Member = inClass.Members.Search(result.Member.Name, 0, 0); - } - else result.Member = model.Members.Search(result.Member.Name, 0, 0); + return; } - if (model.FileName.Length > 0 && File.Exists(model.FileName)) - ASContext.MainForm.OpenEditableDocument(model.FileName, false); - else + int styleBefore = sci.BaseStyleAt(sci.CurrentPos - 2); + int styleAfter = sci.BaseStyleAt(sci.CurrentPos); + + // not inside a string literal + int position = sci.CurrentPos - 1; + if (!(IsStringStyle(styleBefore) && IsStringStyle(styleAfter)) && !(IsCharStyle(styleBefore) && IsCharStyle(styleAfter)) + || ctx.CodeComplete.IsStringInterpolationStyle(sci, position) + || IsMatchingQuote(open, styleAfter)) { - OpenVirtualFile(model); - result.InFile = ASContext.Context.CurrentModel; - if (result.InFile == null) return false; - if (inClass != null) + foreach (var brace in ASContext.CommonSettings.AddClosingBracesRules) { - inClass = result.InFile.GetClassByName(inClass.Name); - if (result.Member != null) - result.Member = inClass.Members.Search(result.Member.Name, 0, 0); + if (HandleBraceRemove(sci, brace, open)) + { + break; + } } - else if (result.Member != null) - result.Member = result.InFile.Members.Search(result.Member.Name, 0, 0); } } - if ((inClass == null || inClass.IsVoid()) && result.Member == null) - return false; - - Sci = ASContext.CurSciControl; - if (Sci == null) - return false; + } - int line = 0; - string name = null; - bool isClass = false; - // member - if (result.Member != null && result.Member.LineFrom > 0) + static bool HandleBraceOpen(ScintillaControl sci, Brace brace, char open, byte styleAfter, byte styleBefore) + { + if (open != brace.Open) return false; + var charAfter = (char) sci.CharAt(sci.CurrentPos); + var charBefore = (char) sci.CharAt(sci.CurrentPos - 2); + if (!brace.ShouldOpen(charBefore, styleBefore, charAfter, styleAfter)) return false; + var selections = sci.GetSelections(); + var positions = new List(selections); + for (var i = selections - 1; i >= 0; i--) { - line = result.Member.LineFrom; - name = result.Member.Name; + positions.Add(sci.GetSelectionNStart(i)); } - // class declaration - else if (inClass.LineFrom > 0) + positions.Sort(); + var braceString = brace.Close.ToString(); + for (var i = 0; i < selections; i++) { - line = inClass.LineFrom; - name = inClass.Name; - isClass = true; - // constructor - foreach (MemberModel member in inClass.Members) - if ((member.Flags & FlagType.Constructor) > 0) - { - line = member.LineFrom; - name = member.Name; - isClass = false; - break; - } + var position = positions[i] + i * braceString.Length; + sci.InsertText(position, braceString); + positions[i] = position; + if (!brace.AddSpace) continue; + sci.InsertText(position, " "); + if (i + 1 < selections) positions[i + 1] += " ".Length * (i + 1); } - // select - if (line > 0) + sci.SetSelection(positions[0], positions[0]); + for (var i = 1; i < selections; i++) { - if (isClass) - LocateMember("(class|interface)", name, line); - else - LocateMember("(function|var|const|get|set|property|[,(])", name, line); + var position = positions[i]; + sci.AddSelection(position, position); } return true; } - static public void OpenVirtualFile(FileModel model) + static bool HandleBraceClose(ScintillaControl sci, Brace brace, char close, char next, int nextPosition) { - string ext = Path.GetExtension(model.FileName); - if (ext == "") ext = model.Context.GetExplorerMask()[0]; - string dummyFile = Path.Combine( - Path.GetDirectoryName(model.FileName), - "[model] " + Path.GetFileNameWithoutExtension(model.FileName) + ext); - foreach (ITabbedDocument doc in ASContext.MainForm.Documents) - { + if (close != brace.Close || next != brace.Close || !brace.ShouldClose(sci.CurrentPos, nextPosition)) + return false; + sci.DeleteBack(); + sci.AnchorPosition = nextPosition; + sci.CurrentPos = nextPosition; + return true; + } + + static bool HandleBraceRemove(ScintillaControl sci, Brace brace, char open) + { + var result = false; + var selections = sci.GetSelections(); + for (var i = 0; i < selections; i++) + { + if (open != brace.Open) continue; + var startPosition = sci.GetSelectionNStart(i); + var closePosition = startPosition; + if (GetCharRight(sci, true, ref closePosition) != brace.Close || !brace.ShouldRemove(startPosition, closePosition)) continue; + sci.SetSelectionNStart(i, startPosition - 1); + sci.SetSelectionNEnd(i, closePosition + 1); + result = true; + } + return result; + } + + #endregion + + #region plugin commands + /// + /// Using the text under at cursor position, search and open the object/class/member declaration + /// + /// Scintilla Control + /// Declaration was found + public static bool DeclarationLookup(ScintillaControl sci) + { + if (!ASContext.Context.IsFileValid || sci is null) return false; + // let the context handle goto declaration if we couldn't find anything + if (InternalDeclarationLookup(sci)) return true; + var expression = GetExpression(sci, sci.CurrentPos); + return ASContext.Context.HandleGotoDeclaration(sci, expression); + } + + public static bool TypeDeclarationLookup(ScintillaControl sci) + { + if (sci is null || !ASContext.Context.IsFileValid) return false; + var position = ExpressionEndPosition(sci, sci.CurrentPos); + var result = GetExpressionType(sci, position, false, true); + if (result.IsPackage) return false; + var member = result.Member; + var type = result.Type; + if (member is null || member.Flags.HasFlag(FlagType.AutomaticVar) || type is null) return false; + if (member.Flags.HasFlag(FlagType.Function)) + { + type = ResolveType(result.Member.Type, result.InFile); + if (type.IsVoid()) return false; + } + result.Member = null; + result.InClass = null; + result.InFile = null; + var path = type.Name; + result.Path = path.Contains('.', out var index) + ? path.Substring(0, index) + : path; + return OpenDocumentToDeclaration(sci, result); + } + + static bool InternalDeclarationLookup(ScintillaControl sci) + { + // get type at cursor position + var position = ExpressionEndPosition(sci, sci.CurrentPos); + var result = GetExpressionType(sci, position, false, true); + + var ctx = ASContext.Context; + // browse to package folder + if (result.IsPackage && result.InFile != null) return ctx.BrowseTo(result.InFile.Package); + + // open source and show declaration + if (!result.IsNull()) + { + if (result.Member != null && (result.Member.Flags & FlagType.AutomaticVar) > 0) + return false; + + // open the file + return OpenDocumentToDeclaration(sci, result); + } + // show overridden method + if (ctx.CurrentMember is null + || ctx.Features.overrideKey is null + || sci.GetWordFromPosition(position) != ctx.Features.overrideKey) return false; + var member = ctx.CurrentMember; + if ((member.Flags & FlagType.Override) == 0) return false; + var found = ctx.CurrentClass.Extends.SearchMember(member.Name, true, out var inClass); + if (found != null) OpenDocumentToDeclaration(sci, new ASResult {Member = found, InFile = inClass.InFile, InClass = inClass}); + return false; + } + + public static void SaveLastLookupPosition(ScintillaControl sci) + { + if (sci is null) return; + var lookupLine = sci.CurrentLine; + var lookupCol = sci.CurrentPos - sci.PositionFromLine(lookupLine); + ASContext.Panel.SetLastLookupPosition(ASContext.Context.CurrentFile, lookupLine, lookupCol); + } + + /// + /// Show resolved element declaration + /// + /// Scintilla control + /// Element declaration + public static bool OpenDocumentToDeclaration(ScintillaControl sci, ASResult result) + { + var model = result.InFile ?? result.Member?.InFile ?? result.Type?.InFile; + if (string.IsNullOrEmpty(model?.FileName)) return false; + var inClass = result.InClass ?? result.Type; + + SaveLastLookupPosition(sci); + + if (model != ASContext.Context.CurrentModel) + { + if (File.Exists(model.FileName)) PluginBase.MainForm.OpenEditableDocument(model.FileName, false); + else + { + OpenVirtualFile(model); + result.InFile = ASContext.Context.CurrentModel; + if (result.InFile is null) return false; + if (inClass != null) + { + inClass = result.InFile.GetClassByName(inClass.Name); + if (result.Member != null) result.Member = inClass.Members.Search(result.Member.Name); + } + else if (result.Member != null) result.Member = result.InFile.Members.Search(result.Member.Name); + } + } + if ((inClass is null || inClass.IsVoid()) && result.Member is null) return false; + if (PluginBase.MainForm.CurrentDocument?.SciControl is null) return false; + + var line = 0; + string name = null; + var isClass = false; + // member + if (result.Member != null && result.Member.LineFrom > 0) + { + line = result.Member.LineFrom; + name = result.Member.Name; + } + // class declaration + else if (inClass != null && inClass.LineFrom > 0) + { + line = inClass.LineFrom; + name = inClass.Name; + isClass = true; + // constructor + var member = inClass.SearchMember(FlagType.Constructor, false); + if (member != null) + { + line = member.LineFrom; + name = member.Name; + isClass = false; + } + } + // select + if (line > 0) + { + var keyword = isClass + ? "(class|interface|abstract)" + : "(function|var|const|get|set|property|namespace|[,(])"; + LocateMember(keyword, name, line); + } + return true; + } + + public static void OpenVirtualFile(FileModel model) + { + var ext = Path.GetExtension(model.FileName); + if (string.IsNullOrEmpty(ext)) ext = model.Context.GetExplorerMask()[0].Replace("*", string.Empty); + var dummyFile = Path.Combine(Path.GetDirectoryName(model.FileName), "[model] " + Path.GetFileNameWithoutExtension(model.FileName) + ext); + foreach (var doc in PluginBase.MainForm.Documents) + { if (doc.FileName == dummyFile) { doc.Activate(); @@ -613,95 +708,104 @@ static public void OpenVirtualFile(FileModel model) } // nice output model.Members.Sort(); - foreach (ClassModel aClass in model.Classes) aClass.Members.Sort(); - string src = "//\n// " + model.FileName + "\n//\n" + model.GenerateIntrinsic(false); - ASContext.MainForm.CreateEditableDocument(dummyFile, src, Encoding.UTF8.CodePage); + foreach (var aClass in model.Classes) aClass.Members.Sort(); + var src = "//\n// " + model.FileName + "\n//\n" + model.GenerateIntrinsic(false); + if (PluginBase.MainForm.CreateEditableDocument(dummyFile, src, Encoding.UTF8.CodePage) is ITabbedDocument {SciControl: { } sci}) + { + // The model document will be read only + sci.IsReadOnly = true; + } } - static public void LocateMember(string keyword, string name, int line) + public static void LocateMember(string keyword, string name, int line) + => LocateMember(PluginBase.MainForm.CurrentDocument?.SciControl, keyword, name, line); + + public static void LocateMember(ScintillaControl sci, string keyword, string name, int line) { - try - { - ScintillaControl sci = PluginBase.MainForm.CurrentDocument.SciControl; - if (sci == null || line <= 0) return; + if (sci is null || line <= 0 || string.IsNullOrEmpty(name)) return; + ASContext.Context.CodeComplete.LocateMember(sci, line, keyword, name); + } - bool found = false; - string pattern = String.Format("{0}\\s*(?{1})[^A-z0-9]", (keyword ?? ""), name.Replace(".", "\\s*.\\s*")); - Regex re = new Regex(pattern); - for (int i = line; i < line + 2; i++) - if (i < sci.LineCount) - { - string text = sci.GetLine(i); - Match m = re.Match(text); - if (m.Success) - { - int position = sci.PositionFromLine(i) + sci.MBSafeTextLength(text.Substring(0, m.Groups["name"].Index)); - sci.EnsureVisible(sci.LineFromPosition(position)); - sci.SetSel(position, position + m.Groups["name"].Length); - found = true; - break; - } - } + protected virtual void LocateMember(ScintillaControl sci, int line, string keyword, string name) + => LocateMember(sci, line, $"{keyword ?? string.Empty}\\s*(?{name.Replace(".", "\\s*.\\s*")})[^A-z0-9]"); - if (!found) - { - sci.EnsureVisible(line); - int linePos = sci.PositionFromLine(line); - sci.SetSel(linePos, linePos); - } - sci.Focus(); + protected void LocateMember(ScintillaControl sci, int line, string pattern) + { + var found = false; + var re = new Regex(pattern); + for (int i = line, lineCount = sci.LineCount; i < line + 2 && i < lineCount; i++) + { + var text = sci.GetLine(i); + var m = re.Match(text); + if (!m.Success) continue; + var position = sci.PositionFromLine(i) + sci.MBSafeTextLength(text.Substring(0, m.Groups["name"].Index)); + sci.EnsureVisibleEnforcePolicy(sci.LineFromPosition(position)); + sci.SetSel(position, position + m.Groups["name"].Length); + found = true; + break; + } + if (!found) + { + sci.EnsureVisible(line); + var linePos = sci.PositionFromLine(line); + sci.SetSel(linePos, linePos); } - catch { } + sci.Focus(); } /// /// Resolve word at cursor position and pre-fill arguments for args processor /// - internal static void ResolveContext(ScintillaControl Sci) + internal static void ResolveContext(ScintillaControl sci) { try { // check if a document - if (Sci == null) + if (sci is null) { ClearResolvedContext(); return; } - + var currentPos = sci.CurrentPos; // check if resolution is needed - int position = Sci.WordEndPosition(Sci.CurrentPos, true); + var position = sci.WordEndPosition(currentPos, true); if (CurrentResolvedContext != null && CurrentResolvedContext.Position == position && CurrentResolvedContext.Result != null && !CurrentResolvedContext.Result.IsNull()) return; // check context - IASContext context = ASContext.Context; - if (context == null || context.CurrentModel == null) + var context = ASContext.Context; + if (context?.CurrentModel is null) { ClearResolvedContext(); return; } - CurrentResolvedContext = new ResolvedContext(); - CurrentResolvedContext.Position = position; + CurrentResolvedContext = new ResolvedContext {Position = position}; + var features = context.Features; // get type at cursor position ASResult result; - if (ASContext.Context.IsFileValid) result = GetExpressionType(Sci, position); + if (context.IsFileValid + // comments + && sci.BaseStyleAt(currentPos) is { } style && !IsCommentStyle(style) + // keywords + && ((style != 19 && style != 24) || (!string.IsNullOrEmpty(features.ConstructorKey) && sci.GetWordFromPosition(currentPos) == features.ConstructorKey))) + { + result = GetExpressionType(sci, position); + } else result = new ASResult(); CurrentResolvedContext.Result = result; - ContextFeatures features = context.Features; - Hashtable args = CurrentResolvedContext.Arguments; - string package = context.CurrentModel.Package; + var args = CurrentResolvedContext.Arguments; + var package = context.CurrentModel.Package; args.Add("TypPkg", package); - ClassModel cClass = context.CurrentClass; - if (cClass == null) cClass = ClassModel.VoidClass; + var cClass = context.CurrentClass ?? ClassModel.VoidClass; args.Add("TypName", MemberModel.FormatType(cClass.Name)); - string fullname = MemberModel.FormatType(cClass.QualifiedName); - args.Add("TypPkgName", fullname); - FlagType flags = cClass.Flags; - string kind = GetKind(flags, features); + var fullName = MemberModel.FormatType(cClass.QualifiedName); + args.Add("TypPkgName", fullName); + var flags = cClass.Flags; + var kind = GetKind(flags, features); args.Add("TypKind", kind); if (context.CurrentMember != null) @@ -711,20 +815,19 @@ internal static void ResolveContext(ScintillaControl Sci) kind = GetKind(flags, features); args.Add("MbrKind", kind); - ClassModel aType = CurrentResolvedContext.TokenType - = ASContext.Context.ResolveType(context.CurrentMember.Type, context.CurrentModel); - package = aType.IsVoid() ? "" : aType.InFile.Package; + var aType = CurrentResolvedContext.TokenType = ResolveType(context.CurrentMember.Type, context.CurrentModel); + package = aType.IsVoid() ? string.Empty : aType.InFile.Package; args.Add("MbrTypPkg", package); args.Add("MbrTypName", MemberModel.FormatType(aType.Name)); - fullname = MemberModel.FormatType(aType.QualifiedName); - args.Add("MbrTypePkgName", fullname); + fullName = MemberModel.FormatType(aType.QualifiedName); + args.Add("MbrTypePkgName", fullName); flags = aType.Flags; kind = GetKind(flags, features); args.Add("MbrTypKind", kind); } else { - args.Add("MbrName", ""); + args.Add("MbrName", string.Empty); args.Add("MbrKind", ""); args.Add("MbrTypPkg", ""); args.Add("MbrTypName", ""); @@ -736,42 +839,49 @@ internal static void ResolveContext(ScintillaControl Sci) } // if element can be resolved - if (!result.IsNull()) + if (result.IsPackage) { - ClassModel oClass = result.InClass != null ? result.InClass : result.Type; - - if (result.IsPackage || (oClass.IsVoid() && (result.Member.Flags & FlagType.Function) == 0 && (result.Member.Flags & FlagType.Namespace) == 0)) + args.Add("ItmFile", result.InFile.FileName); + args.Add("ItmTypPkg", result.Path); + args.Add("ItmTypPkgName", result.Path); + } + else if (result.Type != null || result.Member != null) + { + var oClass = result.InClass ?? result.Type ?? ClassModel.VoidClass; + if (oClass.IsVoid() && (result.Member is null || (result.Member.Flags & FlagType.Function) == 0 && (result.Member.Flags & FlagType.Namespace) == 0)) + { + NotifyContextChanged(); return; + } // type details FileModel file; - MemberModel member = result.Member; - + var member = result.Member; if (member != null && member.IsPackageLevel) { args.Add("ItmTypName", member.Name); file = member.InFile; - fullname = "package"; + fullName = "package"; flags = member.Flags; } else { args.Add("ItmTypName", MemberModel.FormatType(oClass.Name)); file = oClass.InFile; - fullname = MemberModel.FormatType(oClass.Name); + fullName = MemberModel.FormatType(oClass.Name); flags = oClass.Flags; } package = file.Package; - fullname = (package.Length > 0 ? package + "." : "") + fullname; + fullName = (package.Length > 0 ? package + "." : "") + fullName; kind = GetKind(flags, features); args.Add("ItmFile", file.FileName); args.Add("ItmTypPkg", package); - args.Add("ItmTypPkgName", fullname); + args.Add("ItmTypPkgName", fullName); args.Add("ItmTypKind", kind); // type as path - args.Add("ItmTypPkgNamePath", fullname.Replace('.', '\\')); - args.Add("ItmTypPkgNameURL", fullname.Replace('.', '/')); + args.Add("ItmTypPkgNamePath", fullName.Replace('.', '\\')); + args.Add("ItmTypPkgNameURL", fullName.Replace('.', '/')); if (result.Type != null) { @@ -822,55 +932,51 @@ internal static void ResolveContext(ScintillaControl Sci) } NotifyContextChanged(); } - catch + catch { + // ignored } } - private static void ClearResolvedContext() + static void ClearResolvedContext() { - if (CurrentResolvedContext != null && CurrentResolvedContext.Position == -1) - return; + if (CurrentResolvedContext != null && CurrentResolvedContext.Position == -1) return; CurrentResolvedContext = new ResolvedContext(); NotifyContextChanged(); } - private static void NotifyContextChanged() - { - if (OnResolvedContextChanged != null) - ASComplete.OnResolvedContextChanged(CurrentResolvedContext); - } + static void NotifyContextChanged() => OnResolvedContextChanged?.Invoke(CurrentResolvedContext); /// - /// Using the text under at cursor position, resolve the member/type and call the specified command. - /// - /// Control - /// Resolved element details - static public Hashtable ResolveElement(ScintillaControl Sci, string eventAction) - { - if (CurrentResolvedContext == null) ResolveContext(Sci); - + /// Using the text under at cursor position, resolve the member/type and call the specified command. + /// + /// Control + /// + /// Resolved element details + public static Hashtable? ResolveElement(ScintillaControl sci, string eventAction) + { + if (CurrentResolvedContext is null) ResolveContext(sci); if (eventAction != null && !CurrentResolvedContext.Result.IsNull()) { // other plugins may handle the request - DataEvent de = new DataEvent(EventType.Command, eventAction, CurrentResolvedContext.Arguments); + var de = new DataEvent(EventType.Command, eventAction, CurrentResolvedContext.Arguments); EventManager.DispatchEvent(ASContext.Context, de); if (de.Handled) return CurrentResolvedContext.Arguments; // help if (eventAction == "ShowDocumentation") { - string cmd = ASContext.Context.Settings.DocumentationCommandLine; - if (cmd == null || cmd.Length == 0) return null; + var cmd = ASContext.Context.Settings.DocumentationCommandLine; + if (string.IsNullOrEmpty(cmd)) return null; // top-level vars should be searched only if the command includes member information - if (CurrentResolvedContext.Result.InClass == ClassModel.VoidClass && cmd.IndexOf("$(Itm") < 0) + if (CurrentResolvedContext.Result.InClass == ClassModel.VoidClass && !cmd.Contains("$(Itm")) return null; // complete command cmd = ArgumentsProcessor.Process(cmd, CurrentResolvedContext.Arguments); // call the command try { - ASContext.MainForm.CallCommand("RunProcess", cmd); + PluginBase.MainForm.CallCommand("RunProcess", cmd); } catch (Exception ex) { @@ -879,23 +985,18 @@ static public Hashtable ResolveElement(ScintillaControl Sci, string eventAction) } } return CurrentResolvedContext.Arguments; - } + } public static void FindClosestList(IASContext context, ASExpr expr, int lineNum, ref string closestListName, ref string closestListItemType) { + if (expr?.LocalVars is null) return; MemberModel closestList = null; - if (expr == null || expr.LocalVars == null) - return; - - foreach (MemberModel m in expr.LocalVars) + foreach (var m in expr.LocalVars) { - if (m.LineFrom > lineNum) - continue; - if (closestList != null && (lineNum - m.LineFrom) >= (lineNum - closestList.LineFrom)) - continue; - - ClassModel aType2 = ASContext.Context.ResolveType(m.Type, context.CurrentModel); - string objType = ASContext.Context.Features.objectKey; + if (m.LineFrom > lineNum) continue; + if (closestList != null && m.LineFrom <= closestList.LineFrom) continue; + var aType2 = ResolveType(m.Type, context.CurrentModel); + var objType = ASContext.Context.Features.objectKey; while (!aType2.IsVoid() && aType2.QualifiedName != objType) { if (aType2.IndexType != null) @@ -912,15 +1013,14 @@ public static void FindClosestList(IASContext context, ASExpr expr, int lineNum, public static string FindFreeIterator(IASContext context, ClassModel cClass, ASExpr expr) { - int iteratorCount = 105; - string iterator = ((char)iteratorCount).ToString(); - bool restartCycle = false; - MemberList members = cClass.Members; - List parameters = context.CurrentMember.Parameters; + var iteratorCount = 105; + var iterator = ((char)iteratorCount).ToString(); + var members = cClass.Members; + var parameters = context.CurrentMember.Parameters; while (true) { - restartCycle = false; - if (expr != null && expr.LocalVars != null) + var restartCycle = false; + if (expr?.LocalVars != null) foreach (MemberModel m in expr.LocalVars) { if (m.Name == iterator) @@ -963,88 +1063,107 @@ public static string FindFreeIterator(IASContext context, ClassModel cClass, ASE return iterator; } - private static string GetKind(FlagType flags, ContextFeatures features) + static string GetKind(FlagType flags, ContextFeatures features) { - if (flags == FlagType.Function) return features.functionKey; + if (flags == FlagType.Function) return features.functionKey; if ((flags & FlagType.Constant) > 0) return features.constKey; if ((flags & (FlagType.Getter | FlagType.Setter)) > 0) return features.varKey; - if ((flags & FlagType.Interface) > 0) return "interface"; - if ((flags & FlagType.Class) > 0) return "class"; - return ""; + if ((flags & FlagType.Interface) > 0) return features.InterfaceKey; + if ((flags & FlagType.Class) > 0) return features.ClassKey; + return string.Empty; } - #endregion - - #region structure_completion - static private void HandleStructureCompletion(ScintillaControl Sci) - { - try - { - int position = Sci.CurrentPos; - int line = Sci.LineFromPosition(position); - if (line == 0) - return; - string txt = Sci.GetLine(line-1).TrimEnd(); - int style = Sci.BaseStyleAt(position); - - // in comments - if (PluginBase.Settings.CommentBlockStyle == CommentBlockStyle.Indented && txt.EndsWith("*/")) - FixIndentationAfterComments(Sci, line); - else if (IsCommentStyle(style) && (Sci.BaseStyleAt(position + 1) == style)) - FormatComments(Sci, txt, line); + #endregion + + #region structure_completion + + static void HandleStructureCompletion(ScintillaControl sci) + { + try + { + int position = sci.CurrentPos; + int line = sci.LineFromPosition(position); + if (line == 0) return; + string txt = sci.GetLine(line - 1).TrimEnd(); + int style = sci.BaseStyleAt(position); + + // move closing brace to its own line and fix indentation + if (sci.CurrentChar == '}') + { + var openingBrace = sci.SafeBraceMatch(position); + var openLine = openingBrace >= 0 ? sci.LineFromPosition(openingBrace) : line - 1; + sci.InsertText(sci.CurrentPos, LineEndDetector.GetNewLineMarker(sci.EOLMode)); + sci.SetLineIndentation(line + 1, sci.GetLineIndentation(openLine)); + } + // in comments + else if (PluginBase.Settings.CommentBlockStyle == CommentBlockStyle.Indented && txt.EndsWithOrdinal("*/")) + FixIndentationAfterComments(sci, line); + else if (IsCommentStyle(style) && (sci.BaseStyleAt(position + 1) == style)) + FormatComments(sci, txt, line); // in code else { // braces if (!ASContext.CommonSettings.DisableAutoCloseBraces) { - if (txt.IndexOf("//") > 0) // remove comment at end of line + if (txt.Contains("//", out var p1) && p1 > 0) // remove comment at end of line { - int slashes = Sci.MBSafeTextLength(txt.Substring(0, txt.IndexOf("//") + 1)); - if (Sci.PositionIsOnComment(Sci.PositionFromLine(line-1) + slashes)) - txt = txt.Substring(0, txt.IndexOf("//")).Trim(); + var slashes = sci.MBSafeTextLength(txt.Substring(0, p1 + 1)); + if (sci.PositionIsOnComment(sci.PositionFromLine(line-1) + slashes)) + txt = txt.Substring(0, p1).Trim(); } - if (txt.EndsWith("{") && (line > 1)) AutoCloseBrace(Sci, line); + if (txt.EndsWith('{') && line > 1) AutoCloseBrace(sci, line); } - // code reformating - if (!ASContext.CommonSettings.DisableCodeReformat && !txt.EndsWith("*/")) - ReformatLine(Sci, Sci.PositionFromLine(line) - 1); - } - } - catch (Exception ex) - { - ErrorManager.ShowError(ex); - } - } - - private static void ReformatLine(ScintillaControl Sci, int position) + // code reformatting + if (!ASContext.CommonSettings.DisableCodeReformat && !txt.EndsWithOrdinal("*/")) + ReformatLine(sci, sci.PositionFromLine(line) - 1); + } + } + catch (Exception ex) + { + ErrorManager.ShowError(ex); + } + } + + static void ReformatLine(ScintillaControl sci, int position) { - int line = Sci.LineFromPosition(position); - string txt = Sci.GetLine(line); - int curPos = Sci.CurrentPos; - int startPos = Sci.PositionFromLine(line); - int offset = Sci.MBSafeLengthFromBytes(txt, position - startPos); - - ReformatOptions options = new ReformatOptions(); - options.Newline = LineEndDetector.GetNewLineMarker(Sci.EOLMode); - options.CondenseWhitespace = ASContext.CommonSettings.CondenseWhitespace; - options.BraceAfterLine = ASContext.CommonSettings.ReformatBraces - && PluginBase.MainForm.Settings.CodingStyle == CodingStyle.BracesAfterLine; - options.CompactChars = ASContext.CommonSettings.CompactChars; - options.SpacedChars = ASContext.CommonSettings.SpacedChars; - options.SpaceBeforeFunctionCall = ASContext.CommonSettings.SpaceBeforeFunctionCall; - options.AddSpaceAfter = ASContext.CommonSettings.AddSpaceAfter.Split(' '); - options.IsPhp = ASContext.Context.Settings.LanguageId == "PHP"; - options.IsHaXe = ASContext.Context.Settings.LanguageId == "HAXE"; + int line = sci.LineFromPosition(position); + string txt = sci.GetLine(line).TrimEnd('\r', '\n'); + int curPos = sci.CurrentPos; + int startPos = sci.PositionFromLine(line); + int offset = sci.MBSafeLengthFromBytes(txt, position - startPos); + var options = new ReformatOptions + { + Newline = LineEndDetector.GetNewLineMarker(sci.EOLMode), + CondenseWhitespace = ASContext.CommonSettings.CondenseWhitespace, + BraceAfterLine = ASContext.CommonSettings.ReformatBraces && PluginBase.Settings.CodingStyle == CodingStyle.BracesAfterLine, + CompactChars = ASContext.CommonSettings.CompactChars, + SpacedChars = ASContext.CommonSettings.SpacedChars, + SpaceBeforeFunctionCall = ASContext.CommonSettings.SpaceBeforeFunctionCall, + AddSpaceAfter = !string.IsNullOrEmpty(ASContext.Context.Settings.AddSpaceAfter) + ? ASContext.Context.Settings.AddSpaceAfter.Split(' ') + : ASContext.CommonSettings.AddSpaceAfter.Split(' '), + IsPhp = ASContext.Context.Settings.LanguageId == "PHP", + IsHaXe = ASContext.Context.Settings.LanguageId == "HAXE" + }; + if (options.IsHaXe) + { + var initialStyle = sci.BaseStyleAt(startPos); + options.InString = initialStyle switch + { + (int) CPP.STRING => 1, + (int) CPP.CHARACTER => 2, + _ => options.InString + }; + } int newOffset = offset; - string replace = Reformater.ReformatLine(txt, options, ref newOffset); - + var replace = Reformater.ReformatLine(txt, options, ref newOffset); if (replace != txt) { position = curPos + newOffset - offset; - Sci.SetSel(startPos, startPos + Sci.MBSafeTextLength(txt)); - Sci.ReplaceSel(replace); - Sci.SetSel(position, position); + sci.SetSel(startPos, startPos + sci.MBSafeTextLength(txt)); + sci.ReplaceSel(replace); + sci.SetSel(position, position); } } @@ -1052,79 +1171,74 @@ private static void ReformatLine(ScintillaControl Sci, int position) /// Add closing brace to a code block. /// If enabled, move the starting brace to a new line. /// - /// - /// + /// /// - private static void AutoCloseBrace(ScintillaControl Sci, int line) + static void AutoCloseBrace(ScintillaControl sci, int line) { // find matching brace - int bracePos = Sci.LineEndPosition(line - 1) - 1; - while ((bracePos > 0) && (Sci.CharAt(bracePos) != '{')) bracePos--; - if (bracePos == 0 || Sci.BaseStyleAt(bracePos) != 10) return; - int match = Sci.SafeBraceMatch(bracePos); + int bracePos = sci.LineEndPosition(line - 1) - 1; + while ((bracePos > 0) && (sci.CharAt(bracePos) != '{')) bracePos--; + if (bracePos == 0 || sci.BaseStyleAt(bracePos) != 10) return; + int match = sci.SafeBraceMatch(bracePos); int start = line; - int indent = Sci.GetLineIndentation(start - 1); + int indent = sci.GetLineIndentation(start - 1); if (match > 0) { - int endIndent = Sci.GetLineIndentation(Sci.LineFromPosition(match)); - if (endIndent + Sci.TabWidth > indent) + int endIndent = sci.GetLineIndentation(sci.LineFromPosition(match)); + if (endIndent + sci.TabWidth > indent) return; } // find where to include the closing brace int startIndent = indent; - int newIndent = indent + Sci.TabWidth; - int count = Sci.LineCount; + int count = sci.LineCount; int lastLine = line; int position; - string txt = Sci.GetLine(line).Trim(); + string txt = sci.GetLine(line).Trim(); line++; - int eolMode = Sci.EOLMode; + int eolMode = sci.EOLMode; string NL = LineEndDetector.GetNewLineMarker(eolMode); - if (txt.Length > 0 && ")]};,".IndexOf(txt[0]) >= 0) + if (txt.Length > 0 && ")]};,".Contains(txt[0])) { - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - position = Sci.CurrentPos; - Sci.InsertText(position, NL + "}"); - Sci.SetLineIndentation(line, startIndent); + position = sci.CurrentPos; + sci.InsertText(position, NL + "}"); + sci.SetLineIndentation(line, startIndent); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } return; } - else + while (line < count - 1) { - while (line < count - 1) + txt = sci.GetLine(line).TrimEnd(); + if (txt.Length != 0) { - txt = Sci.GetLine(line).TrimEnd(); - if (txt.Length != 0) - { - indent = Sci.GetLineIndentation(line); - if (indent <= startIndent) break; - lastLine = line; - } - else break; - line++; + indent = sci.GetLineIndentation(line); + if (indent <= startIndent) break; + lastLine = line; } + else break; + line++; } if (line >= count - 1) lastLine = start; // insert closing brace - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - position = Sci.LineEndPosition(lastLine); - Sci.InsertText(position, NL + "}"); - Sci.SetLineIndentation(lastLine + 1, startIndent); + position = sci.LineEndPosition(lastLine); + sci.InsertText(position, NL + "}"); + sci.SetLineIndentation(lastLine + 1, startIndent); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } } @@ -1132,377 +1246,367 @@ private static void AutoCloseBrace(ScintillaControl Sci, int line) /// When javadoc comment blocks have and additional space, /// fix indentation of new line following this block /// - /// + /// /// - private static void FixIndentationAfterComments(ScintillaControl Sci, int line) + static void FixIndentationAfterComments(ScintillaControl sci, int line) { int startLine = line - 1; while (startLine > 0) { - string txt = Sci.GetLine(startLine).TrimStart(); - if (txt.StartsWith("/*")) break; - else if (!txt.StartsWith("*")) break; + string txt = sci.GetLine(startLine).TrimStart(); + if (txt.StartsWithOrdinal("/*")) break; + if (!txt.StartsWith('*')) break; startLine--; } - Sci.SetLineIndentation(line, Sci.GetLineIndentation(startLine)); - int position = Sci.LineIndentPosition(line); - Sci.SetSel(position, position); + sci.SetLineIndentation(line, sci.GetLineIndentation(startLine)); + int position = sci.LineIndentPosition(line); + sci.SetSel(position, position); } /// /// Add a '*' at the beginning of new lines inside a comment block /// - /// + /// /// /// - private static void FormatComments(ScintillaControl Sci, string txt, int line) + static void FormatComments(ScintillaControl sci, string txt, int line) { txt = txt.TrimStart(); - if (txt.StartsWith("/*")) + if (txt.StartsWithOrdinal("/*")) { - Sci.ReplaceSel("* "); + sci.ReplaceSel("* "); if (PluginBase.Settings.CommentBlockStyle == CommentBlockStyle.Indented) - Sci.SetLineIndentation(line, Sci.GetLineIndentation(line) + 1); - int position = Sci.LineIndentPosition(line) + 2; - Sci.SetSel(position, position); + sci.SetLineIndentation(line, sci.GetLineIndentation(line) + 1); + int position = sci.LineIndentPosition(line) + 2; + sci.SetSel(position, position); } - else if (txt.StartsWith("*")) + else if (txt.StartsWith('*')) { - Sci.ReplaceSel("* "); - int position = Sci.LineIndentPosition(line) + 2; - Sci.SetSel(position, position); + sci.ReplaceSel("* "); + int position = sci.LineIndentPosition(line) + 2; + sci.SetSel(position, position); } } - #endregion + #endregion + + #region template_completion - #region template_completion - static private bool HandleDeclarationCompletion(ScintillaControl Sci, string tail, bool autoHide) - { - int position = Sci.CurrentPos; - int line = Sci.LineFromPosition(position); - if (Sci.CharAt(position - 1) <= 32) tail = ""; + static bool HandleDeclarationCompletion(ScintillaControl sci, string tail, bool autoHide) + { + int position = sci.CurrentPos; + int line = sci.LineFromPosition(position); + if (sci.CharAt(position - 1) <= ' ') tail = ""; // completion support - ContextFeatures features = ASContext.Context.Features; - List support = features.GetDeclarationKeywords(Sci.GetLine(line)); + var ctx = ASContext.Context; + var features = ctx.Features; + var insideClass = !ctx.CurrentClass.IsVoid() && ctx.CurrentClass.LineFrom < line; + var support = features.GetDeclarationKeywords(sci.GetLine(line), insideClass); if (support.Count == 0) return true; - // current model - FileModel cFile = ASContext.Context.CurrentModel; - ClassModel cClass = ASContext.Context.CurrentClass; - // does it need indentation? int tab = 0; int tempLine = line-1; - int tempIndent; - string tempText; - while(tempLine > 0) + while (tempLine > 0) { - tempText = Sci.GetLine(tempLine).Trim(); - if (tempText.IndexOf("class") >= 0 || tempText.IndexOf("interface") >=0 || tempText.IndexOf("enum") >= 0) + var tempText = sci.GetLine(tempLine).Trim(); + if (insideClass && CodeUtils.IsTypeDecl(tempText, features.typesKeywords)) + { + tab = sci.GetLineIndentation(tempLine) + sci.TabWidth; break; - if (tempText.Length > 0 && (tempText.EndsWith("}") || IsDeclaration(tempText))) + } + if (tempText.Length > 0 && (tempText.EndsWith('}') || CodeUtils.IsDeclaration(tempText, features))) { - tempIndent = Sci.GetLineIndentation(tempLine); - tab = tempIndent; - if (tempText.EndsWith("{")) tab += Sci.TabWidth; + tab = sci.GetLineIndentation(tempLine); + if (tempText.EndsWith('{')) tab += sci.TabWidth; break; } tempLine--; } - if (tab > 0) - { - tempIndent = Sci.GetLineIndentation(line); - Sci.SetLineIndentation(line, tab); - } + if (tab > 0) sci.SetLineIndentation(line, tab); + var list = support.Select(static it => new DeclarationItem(it)).ToArray(); + CompletionList.Show(list, autoHide, tail); + return true; + } - // build list - List known = new List(); - foreach(string token in support) - known.Add(new DeclarationItem(token)); + #endregion - // show - CompletionList.Show(known, autoHide, tail); - return true; - } + #region function_completion + internal static string calltipDef; + protected static MemberModel calltipMember; + static bool calltipDetails; + static int calltipPos = -1; + static int calltipOffset; + static ClassModel calltipRelClass; + static string prevParam = ""; - private static bool IsDeclaration(string line) - { - ContextFeatures features = ASContext.Context.Features; - if (!string.IsNullOrEmpty(features.privateKey) && line.StartsWith(features.privateKey)) return true; - if (!string.IsNullOrEmpty(features.protectedKey) && line.StartsWith(features.protectedKey)) return true; - if (!string.IsNullOrEmpty(features.internalKey) && line.StartsWith(features.internalKey)) return true; - if (!string.IsNullOrEmpty(features.publicKey) && line.StartsWith(features.publicKey)) return true; - if (!string.IsNullOrEmpty(features.varKey) && line.StartsWith(features.varKey)) return true; - if (!string.IsNullOrEmpty(features.constKey) && line.StartsWith(features.constKey)) return true; - if (!string.IsNullOrEmpty(features.overrideKey) && line.StartsWith(features.overrideKey)) return true; - if (!string.IsNullOrEmpty(features.inlineKey) && line.StartsWith(features.inlineKey)) return true; - if (!string.IsNullOrEmpty(features.functionKey) && line.StartsWith(features.functionKey)) return true; - if (!string.IsNullOrEmpty(features.staticKey) && line.StartsWith(features.staticKey)) return true; - if (!string.IsNullOrEmpty(features.finalKey) && line.StartsWith(features.finalKey)) return true; - return false; - } + public static bool HasCalltip() => UITools.CallTip.CallTipActive && (calltipDef != null); - #endregion - - #region function_completion - static private string calltipDef; - static private MemberModel calltipMember; - static private bool calltipDetails; - static private int calltipPos = -1; - static private int calltipOffset; - static private ClassModel calltipRelClass; - static private string prevParam = ""; - static private string paramInfo = ""; - - static public bool HasCalltip() - { - return UITools.CallTip.CallTipActive && (calltipDef != null); - } - - /// - /// Show highlighted calltip - /// - /// Scintilla control - /// Highlight param number - static private void ShowCalltip(ScintillaControl Sci, int paramNumber) - { - ShowCalltip(Sci, paramNumber, false); - } - - static private void ShowCalltip(ScintillaControl Sci, int paramIndex, bool forceRedraw) - { + /// + /// Show highlighted calltip + /// + /// Scintilla control + /// Highlight param number + static void ShowCalltip(ScintillaControl sci, int paramIndex) + { // measure highlighting - int start = calltipDef.IndexOf('('); + int start = calltipDef.IndexOf('('); while ((start >= 0) && (paramIndex-- > 0)) - start = FindNearSymbolInFunctDef(calltipDef, ",", start + 1); - - int end = FindNearSymbolInFunctDef(calltipDef, ",", start + 1); - if (end < 0) - end = FindNearSymbolInFunctDef(calltipDef, ")", start + 1); - - // get parameter name - string paramName = ""; - if (calltipMember.Comments != null && start >= 0 && end > 0) - { - paramName = calltipDef.Substring(start + 1, end - start - 1).Trim(); - int p = paramName.IndexOf(':'); - if (p > 0) - paramName = paramName.Substring(0, p).TrimEnd(); - if (paramName.Length > 0) - { - Match mParam = Regex.Match(calltipMember.Comments, "@param\\s+" + Regex.Escape(paramName) + "[ \t:]+(?[^\r\n]*)"); - if (mParam.Success) - paramInfo = "\n" + "[U]" + paramName + ":" + "[/U]" + mParam.Groups["desc"].Value.Trim(); - else - paramInfo = ""; - } - else paramInfo = ""; - } - - // show calltip + start = FindNearSymbolInFunctDef(calltipDef, ',', start + 1); + + int end = FindNearSymbolInFunctDef(calltipDef, ',', start + 1); + if (end < 0) + end = FindNearSymbolInFunctDef(calltipDef, ')', start + 1); + + // get parameter name + string paramName = ""; + if (calltipMember.Comments != null && start >= 0 && end > 0) + { + paramName = calltipDef.Substring(start + 1, end - start - 1); + + int p = paramName.IndexOf(':'); + if (p > 0) paramName = paramName.Substring(0, p); + else + { + p = paramName.IndexOf('='); + if (p > 0) paramName = paramName.Substring(0, p); + } + paramName = paramName.Trim(' ', '\t', '\n', '\r', '*', '?'); + } + + // show calltip if (!UITools.CallTip.CallTipActive || UITools.Manager.ShowDetails != calltipDetails || paramName != prevParam) - { - prevParam = paramName; + { + prevParam = paramName; calltipDetails = UITools.Manager.ShowDetails; - string text = calltipDef + ASDocumentation.GetTipDetails(calltipMember, paramName); - UITools.CallTip.CallTipShow(Sci, calltipPos - calltipOffset, text, forceRedraw); - } - - // highlight - if ((start < 0) || (end < 0)) UITools.CallTip.CallTipSetHlt(0, 0, true); - else UITools.CallTip.CallTipSetHlt(start + 1, end, true); - } - - static string[] featStart = new string[] { "/*", "{", "<", "[", "(" }; - static string[] featEnd = new string[] { "*/", "}", ">", "]", ")" }; - - static private int FindNearSymbolInFunctDef(string defBody, string symbol, int startAt) - { - int end = -1; - int featBeg; - while (true) - { - end = defBody.IndexOf(symbol, startAt); - if (end < 0) break; - bool cont = false; - for (int i = 0; i < featStart.Length; i++) - { - featBeg = defBody.IndexOf(featStart[i], startAt); - if (featBeg >= 0 && featBeg < end) + string text = calltipDef + ASDocumentation.GetTipDetails(calltipMember, paramName); + UITools.CallTip.CallTipShow(sci, calltipPos - calltipOffset, text); + } + + // highlight + if ((start < 0) || (end < 0)) UITools.CallTip.CallTipSetHlt(0, 0, true); + else UITools.CallTip.CallTipSetHlt(start + 1, end, true); + } + + static int FindNearSymbolInFunctDef(string defBody, char symbol, int startAt) + { + string featEnd = null; + for (int i = startAt, count = defBody.Length; i < count; i++) + { + char c = defBody[i]; + if (featEnd is null) + { + switch (c) { - startAt = Math.Max(featBeg + 1, defBody.IndexOf(featEnd[i], featBeg)); - cont = true; - break; + case '/': + if (i < count - 1 && defBody[i + 1] == '*') + { + i++; + featEnd = "*/"; + } + break; + case '{': + featEnd = "}"; + break; + case '<': + featEnd = ">"; + break; + case '[': + featEnd = "]"; + break; + case '(': + featEnd = ")"; + break; + case '\'': + featEnd = "'"; + break; + case '"': + featEnd = "\""; + break; + default: + if (c == symbol) + return i; + break; } } - if (!cont) break; - } - return end; - } - - /// - /// Display method signature - /// - /// Scintilla control - /// Auto-completion has been handled - static public bool HandleFunctionCompletion(ScintillaControl Sci, bool autoHide) - { - return HandleFunctionCompletion(Sci, autoHide, false); - } - - static public bool HandleFunctionCompletion(ScintillaControl Sci, bool autoHide, bool forceRedraw) - { - // only auto-complete where it makes sense - if (DeclarationSectionOnly()) - return false; + else if (c == featEnd[0]) + { + if (featEnd == "\"" || featEnd == "'") + { + // Are we on an escaped ' or ""? + int escNo = 0; + int l = i - 1; + while (l > -1 && defBody[l--] == '\\') + escNo++; + + if (escNo % 2 != 0) + continue; + } + else + { + int ci = i + 1; + int j; + int fl = featEnd.Length; + for (j = 1; j < fl && ci < count; j++) + { + if (defBody[ci++] != featEnd[j]) + break; + } + + if (j != fl) + continue; - int position = Sci.CurrentPos - 1; - int paramIndex = FindParameterIndex(Sci, ref position); + i = ci - 1; + } + + featEnd = null; + } + } + return -1; + } + + /// + /// Display method signature + /// + /// Scintilla control + /// Auto-started completion (is false when pressing Ctrl+Space) + /// Auto-completion has been handled + public static bool HandleFunctionCompletion(ScintillaControl sci, bool autoHide) + { + // only auto-complete where it makes sense + if (DeclarationSectionOnly()) return false; + var position = sci.CurrentPos - 1; + var paramIndex = FindParameterIndex(sci, ref position); if (position < 0) return false; - // continuing calltip ? - if (HasCalltip()) - { - if (calltipPos == position) - { - ShowCalltip(Sci, paramIndex, forceRedraw); - return true; - } - else UITools.CallTip.Hide(); - } - - if (!ResolveFunction(Sci, position, autoHide)) - return true; - - // EventDispatchers - if (paramIndex == 0 && calltipRelClass != null && calltipMember.Name.EndsWith("EventListener")) + if (HasCalltip()) + { + if (calltipPos == position) + { + ShowCalltip(sci, paramIndex); + return true; + } + UITools.CallTip.Hide(); + } + if (!ASContext.Context.CodeComplete.ResolveFunction(sci, position, autoHide)) return true; + // EventDispatchers + if (paramIndex == 0 && calltipRelClass != null && calltipMember.Name.EndsWithOrdinal("EventListener")) { - ShowListeners(Sci, position, calltipRelClass); + ShowListeners(sci, position, calltipRelClass); return true; } - // show calltip - ShowCalltip(Sci, paramIndex, forceRedraw); - return true; + ShowCalltip(sci, paramIndex); + return true; } /// /// Find declaration of function called in code /// + /// Scintilla control /// Position obtained by FindParameterIndex() + /// Auto-started completion (is false when pressing Ctrl+Space) /// Function successfully resolved - private static bool ResolveFunction(ScintillaControl Sci, int position, bool autoHide) + protected internal bool ResolveFunction(ScintillaControl sci, int position, bool autoHide) { calltipPos = 0; calltipMember = null; calltipRelClass = null; - + var ctx = ASContext.Context; // get expression at cursor position - ASExpr expr = GetExpression(Sci, position, true); - if (expr.Value == null || expr.Value.Length == 0 - || (expr.WordBefore == "function" && expr.Separator == ' ')) - return false; - - // Context - IASContext ctx = ASContext.Context; - FileModel aFile = ctx.CurrentModel; - ClassModel aClass = ctx.CurrentClass; - ASResult result; - + var expr = GetExpression(sci, position, true); + if (string.IsNullOrEmpty(expr.Value) || (expr.WordBefore == ctx.Features.functionKey && expr.Separator == " ")) + return false; // Expression before cursor expr.LocalVars = ParseLocalVars(expr); - result = EvalExpression(expr.Value, expr, aFile, aClass, true, true); - if (!result.IsNull() && result.Member == null && result.Type != null) - { - foreach(MemberModel member in result.Type.Members) - if (member.Name == result.Type.Constructor) - { - result.Member = member; - break; - } - } - if (result.IsNull() || (result.Member != null && (result.Member.Flags & FlagType.Function) == 0)) + var result = EvalExpression(expr.Value, expr, ctx.CurrentModel, ctx.CurrentClass, true, true); + if (result.Member is null && result.Type != null) + result.Member = result.Type.SearchMember(result.Type.Constructor, true); + return ResolveFunction(sci, position, result, autoHide); + } + + /// + /// Find declaration of function called in code + /// + /// Scintilla control + /// Position obtained by FindParameterIndex() + /// Expression before cursor + /// Auto-started completion (is false when pressing Ctrl+Space) + /// Function successfully resolved + protected virtual bool ResolveFunction(ScintillaControl sci, int position, ASResult expr, bool autoHide) + { + var ctx = ASContext.Context; + if (expr.IsNull() || (expr.Member != null && (expr.Member.Flags & FlagType.Function) == 0)) { // custom completion - MemberModel customMethod = ctx.ResolveFunctionContext(Sci, expr, autoHide); - if (customMethod != null) - { - result = new ASResult(); - result.Member = customMethod; - } + var customMethod = ctx.ResolveFunctionContext(sci, expr.Context, autoHide); + if (customMethod != null) expr = new ASResult {Member = customMethod, Context = new ASExpr()}; } - if (result.IsNull()) + if (expr.IsNull()) return false; - MemberModel method = result.Member; - if (method == null) - { - if (result.Type == null) - return false; - string constructor = ASContext.GetLastStringToken(result.Type.Name, "."); - result.Member = method = result.Type.Members.Search(constructor, FlagType.Constructor, 0); - if (method == null) - return false; - } + var method = expr.Member; + if (method is null) + { + if (expr.Type is null) return false; + var constructor = ASContext.GetLastStringToken(expr.Type.Name, "."); + expr.Member = method = expr.Type.Members.Search(constructor, FlagType.Constructor); + if (method is null) return false; + } else if ((method.Flags & FlagType.Function) == 0) { - if (method.Name == "super" && result.Type != null) + if (method.Name == "super" && expr.Type != null) { - result.Member = method = result.Type.Members.Search(result.Type.Constructor, FlagType.Constructor, 0); - if (method == null) - return false; + expr.Member = method = expr.Type.Members.Search(expr.Type.Constructor, FlagType.Constructor); + if (method is null) return false; } else return false; } // inherit doc - while ((method.Flags & FlagType.Override) > 0 && result.InClass != null - && (method.Comments == null || method.Comments.Trim() == "" || method.Comments.Contains("@inheritDoc"))) + while ((method.Flags & FlagType.Override) > 0 && expr.InClass != null + && (method.Comments is null || method.Comments.Trim().Length == 0 || method.Comments.Contains("@inheritDoc"))) { - FindMember(method.Name, result.InClass.Extends, result, 0, 0); - method = result.Member; - if (method == null) - return false; + FindMember(method.Name, expr.InClass.Extends, expr, 0, 0); + method = expr.Member; + if (method is null) return false; } - if ((method.Comments == null || method.Comments.Trim() == "") - && result.InClass != null && result.InClass.Implements != null) + if ((method.Comments is null || method.Comments.Trim().Length == 0) && expr.InClass?.Implements != null) { - ASResult iResult = new ASResult(); - foreach (string type in result.InClass.Implements) + var iResult = new ASResult(); + foreach (var type in expr.InClass.Implements) { - ClassModel model = ASContext.Context.ResolveType(type, result.InFile); + var model = ResolveType(type, expr.InFile); FindMember(method.Name, model, iResult, 0, 0); if (iResult.Member != null) { - iResult.RelClass = result.RelClass; - result = iResult; + iResult.RelClass = expr.RelClass; + iResult.Context = expr.Context; + expr = iResult; method = iResult.Member; break; } } } - - expr.Position = position; - FunctionContextResolved(Sci, expr, method, result.RelClass, false); + expr.Context.Position = position; + FunctionContextResolved(sci, expr.Context, method, expr.RelClass, false); return true; } - public static void FunctionContextResolved(ScintillaControl Sci, ASExpr expr, MemberModel method, ClassModel inClass, bool showTip) + public static void FunctionContextResolved(ScintillaControl sci, ASExpr expr, MemberModel method, ClassModel inClass, bool showTip) { - if (method == null || string.IsNullOrEmpty(method.Name)) - return; + if (string.IsNullOrEmpty(method?.Name)) return; if (calltipMember != null && calltipMember.Name == method.Name) { // use FD-extracted comments - if (method.Comments == null && !string.IsNullOrEmpty(calltipMember.Comments)) + if (method.Comments is null && !string.IsNullOrEmpty(calltipMember.Comments)) method.Comments = calltipMember.Comments; } int position = expr.Position; calltipPos = position; calltipOffset = Math.Min(expr.Value.Length, method.Name.Length); - calltipDef = method.ToString(); + calltipDef = ASContext.Context.CodeComplete.GetCalltipDef(method); calltipMember = method; calltipDetails = UITools.Manager.ShowDetails; calltipRelClass = inClass; @@ -1510,117 +1614,145 @@ public static void FunctionContextResolved(ScintillaControl Sci, ASExpr expr, Me if (showTip) { - position++; - int paramIndex = FindParameterIndex(Sci, ref position); + position = sci.CurrentPos - 1; + sci.Colourise(0, -1); + var paramIndex = FindParameterIndex(sci, ref position); if (position < 0) return; - ShowCalltip(Sci, paramIndex, true); + ShowCalltip(sci, paramIndex); } } + public virtual MemberModel FunctionTypeToMemberModel(string type, FileModel inFile) => null; + + protected virtual string GetCalltipDef(MemberModel member) => member.ToString(); + /// /// Find type of current parameter in current function call /// /// /// Resolve only if parameter is an Object with an index type /// - private static ClassModel ResolveParameterType(int paramIndex, bool indexTypeOnly) + static ClassModel ResolveParameterType(int paramIndex, bool indexTypeOnly) { - if (calltipMember != null && calltipMember.Parameters != null - && paramIndex < calltipMember.Parameters.Count) - { - MemberModel param = calltipMember.Parameters[paramIndex]; - string type = param.Type; - if (indexTypeOnly && (String.IsNullOrEmpty(type) || type.IndexOf('@') < 0)) - return ClassModel.VoidClass; - if (ASContext.Context.Features.objectKey == "Dynamic" && type.StartsWith("Dynamic@")) - type = type.Replace("Dynamic@", "Dynamic<") + ">"; - return ASContext.Context.ResolveType(type, ASContext.Context.CurrentModel); - } - else return ClassModel.VoidClass; + if (calltipMember?.Parameters is null || paramIndex >= calltipMember.Parameters.Count) return ClassModel.VoidClass; + var type = calltipMember.Parameters[paramIndex].Type; + if (indexTypeOnly && (string.IsNullOrEmpty(type) || !type.Contains('@'))) return ClassModel.VoidClass; + if (ASContext.Context.Features.objectKey == "Dynamic" && type.StartsWithOrdinal("Dynamic@")) + type = type.Replace("Dynamic@", "Dynamic<") + ">"; + return ResolveType(type, ASContext.Context.CurrentModel); } /// /// Locate beginning of function call parameters and return index of current parameter /// - private static int FindParameterIndex(ScintillaControl Sci, ref int position) + protected internal static int FindParameterIndex(ScintillaControl sci, ref int position) { - int parCount = 0; - int braCount = 0; - int comaCount = 0; - int arrCount = 0; - int style = 0; - int stylemask = (1 << Sci.StyleBits) - 1; - char c; - while (position >= 0) + var characterClass = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage).characterclass.Characters; + var ctx = ASContext.Context; + var parCount = 0; + var braCount = 0; + var comaCount = 0; + var arrCount = 0; + var genCount = 0; + var hasChar = false; + var endPosition = ctx.CurrentMember != null ? sci.LineEndPosition(ctx.CurrentMember.LineFrom - 1) : 0; + while (position >= endPosition) { - style = Sci.StyleAt(position) & stylemask; - if (style == 19) + if (sci.PositionIsOnComment(position)) + { + position--; + continue; + } + var c = (char) sci.CharAt(position); + // skip {} () [] "" '' blocks + if (((braCount > 0 && c != '{' && c != '}') + || (parCount > 0 && c != '(' && c != ')') + || (arrCount > 0 && c != '[' && c != ']')) + || (sci.PositionIsInString(position) && !ctx.CodeComplete.IsStringInterpolationStyle(sci, position))) + { + position--; + continue; + } + if (c <= ' ') + { + position--; + continue; + } + if (parCount < 0) { - string keyword = GetWordLeft(Sci, ref position); - if (!ASContext.Context.Features.HasTypePreKey(keyword)) + if (characterClass.Contains(c) || c == '>' || c == ']' || c == ')') { - position = -1; - break; + position++; + break; // function start found } + if (char.IsPunctuation(c) || char.IsSymbol(c)) parCount = 0; + } + else if (c == ';' && braCount == 0) + { + position = -1; + break; + } + if (c == '}') braCount++; + else if (c == ']') arrCount++; + else if (c == ')') parCount++; + else if (c == '{') + { + if (braCount == 0) comaCount = 0; + else braCount--; + } + else if (c == '[') + { + if (arrCount == 0) comaCount = 0; + else arrCount--; } - if (!IsLiteralStyle(style) && IsTextStyleEx(style)) + else if (c == '(') --parCount; + else if (c == '?' && genCount > 0) genCount = 0; + else if (c == '>') { - c = (char)Sci.CharAt(position); - if (c == ';') + // for example: -> + if (position - 1 >= endPosition && sci.CharAt(position - 1) == '-') { - position = -1; - break; + position -= 2; + continue; } - // skip {} () [] blocks - if (((braCount > 0) && (c != '{' && c != '}')) - || ((parCount > 0) && (c != '(' && c != ')')) - || ((arrCount > 0) && (c != '[' && c != ']'))) + if (hasChar) { position--; continue; } - // new block - if (c == '}') braCount++; - else if (c == ']') arrCount++; - else if (c == ')') parCount++; - - // block closed - else if (c == '{') - { - if (braCount == 0) comaCount = 0; - else braCount--; - } - else if (c == '[') - { - if (arrCount == 0) comaCount = 0; - else arrCount--; - } - else if (c == '(') + genCount++; + } + else if (c == '<') + { + if (hasChar) { - if (--parCount < 0) - // function start found - break; + position--; + continue; } - - // new parameter reached - else if ((c == ',') && (parCount == 0)) - comaCount++; + if (genCount > 0) genCount--; + } + // new parameter reached + else if (c == ',') + { + parCount = 0; + if (genCount == 0) comaCount++; + hasChar = false; } + else if (characterClass.Contains(c)) hasChar = true; position--; } return comaCount; } - private static void ShowListeners(ScintillaControl Sci, int position, ClassModel ofClass) + static void ShowListeners(ScintillaControl sci, int position, ClassModel ofClass) { // find event metadatas - List events = new List(); + var events = new List(); while (ofClass != null && !ofClass.IsVoid()) { - FileModel inFile = ofClass.InFile; - if (inFile.MetaDatas != null) + if (ofClass.MetaDatas != null) { - foreach (ASMetaData meta in inFile.MetaDatas) + foreach (ASMetaData meta in ofClass.MetaDatas) if (meta.Kind == ASMetaKind.Event) events.Add(meta); } ofClass = ofClass.Extends; @@ -1629,28 +1761,22 @@ private static void ShowListeners(ScintillaControl Sci, int position, ClassModel // format events.Sort(); - Dictionary eventTypes = new Dictionary(); - List list = new List(); - foreach (ASMetaData meta in events) - { - string name = meta.Params["name"]; - Regex reName = new Regex("[\"']" + name + "[\"']"); - string type = meta.Params["type"]; - string comments = meta.Comments; - FlagType flags = FlagType.Variable | FlagType.Constant; - Visibility acc = Visibility.Public; + var eventTypes = new Dictionary(); + var list = new List(); + foreach (var meta in events) + { + var name = meta.Params["name"]; + var reName = new Regex("[\"']" + name + "[\"']"); + var type = meta.Params["type"]; + var comments = meta.Comments; if (name.Length > 0 && type.Length > 0) { - ClassModel evClass; - if (!eventTypes.ContainsKey(type)) + if (!eventTypes.TryGetValue(type, out var evClass)) { - evClass = ASContext.Context.ResolveType(type.Replace(':', '.'), null); + evClass = ResolveType(type.Replace(':', '.'), null); eventTypes.Add(type, evClass); } - else evClass = eventTypes[type]; - if (evClass.IsVoid()) - continue; - + if (evClass.IsVoid()) continue; bool typeFound = false; foreach (MemberModel member in evClass.Members) { @@ -1658,9 +1784,7 @@ private static void ShowListeners(ScintillaControl Sci, int position, ClassModel { typeFound = true; name = evClass.Name + '.' + member.Name; - flags = member.Flags; - acc = member.Access; - if (meta.Comments == null && member.Comments != null) + if (meta.Comments is null && member.Comments != null) comments = member.Comments; break; } @@ -1668,7 +1792,7 @@ private static void ShowListeners(ScintillaControl Sci, int position, ClassModel if (!typeFound) { - if (evClass.InFile.Package.StartsWith("flash.")) + if (evClass.InFile.Package.StartsWithOrdinal("flash.")) continue; // hide built-in events not available in current player target name = '"' + name + '"'; } @@ -1678,184 +1802,171 @@ private static void ShowListeners(ScintillaControl Sci, int position, ClassModel // filter list.Sort(new CompletionItemComparer()); - List items = new List(); + var items = new List(list.Count); string prev = null; - foreach (ICompletionListItem item in list) + foreach (var item in list) { if (item.Label != prev) items.Add(item); prev = item.Label; } // display - Sci.SetSel(position + 1, Sci.CurrentPos); - string tail = Sci.SelText; - Sci.SetSel(Sci.SelectionEnd, Sci.SelectionEnd); + sci.SetSel(position + 1, sci.CurrentPos); + var tail = sci.SelText; + sci.SetSel(sci.SelectionEnd, sci.SelectionEnd); CompletionList.Show(items, true, tail); } - int CompareEvents(Object a, Object b) + #endregion + + #region dot_completion + /// + /// Complete object member + /// + /// Scintilla control + /// Don't keep the list open if the word does not match + /// Auto-completion has been handled + static bool HandleDotCompletion(ScintillaControl sci, bool autoHide) + => ASContext.Context.CodeComplete.HandleDotCompletion(sci, autoHide, null, null); + + /// + /// Complete object member + /// + /// Scintilla control + /// Don't keep the list open if the word does not match + /// + /// + /// Auto-completion has been handled + protected bool HandleDotCompletion(ScintillaControl sci, bool autoHide, List list, Comparison comparison) { - return 0; - } - #endregion - - #region dot_completion - /// - /// Complete object member - /// - /// Scintilla control - /// Don't keep the list open if the word does not match - /// Auto-completion has been handled - static private bool HandleDotCompletion(ScintillaControl Sci, bool autoHide) - { //this method can exit at multiple points, so reset the current class now rather than later currentClassHash = null; // only auto-complete where it makes sense - if (autoHide && DeclarationSectionOnly()) - return false; - - // get expression at cursor position - int position = Sci.CurrentPos; - ASExpr expr = GetExpression(Sci, position); - if (expr.Value == null) - return true; - IASContext ctx = ASContext.Context; - ContextFeatures features = ctx.Features; - int dotIndex = expr.Value.LastIndexOf(features.dot); - if (dotIndex == 0 && expr.Separator != '"') - return true; - - // complete keyword - string word = expr.WordBefore; - if (word != null && - (word == features.varKey || word == features.functionKey || word == features.constKey - || word == features.getKey || word == features.setKey)) - return false; + if (autoHide && DeclarationSectionOnly()) return false; + + var position = sci.CurrentPos; + var expr = GetExpression(sci, position); + if (expr.Value is null) return true; + // for example: expr;.$(EntryPoint) + if (expr.Value.Length == 0 && sci.CharAt(position - 1) == '.') return false; + var ctx = ASContext.Context; + var features = ctx.Features; + var dotIndex = expr.Value.LastIndexOfOrdinal(features.dot); + if (dotIndex == 0 && expr.Separator != "\"") return true; + + // complete keyword + var word = expr.WordBefore; + if (!word.IsNullOrEmpty() && features.declKeywords.Contains(word)) return false; ClassModel argumentType = null; if (dotIndex < 0) { - if (word != null) + if (!word.IsNullOrEmpty()) { - if (word == "class" || word == "package" || word == "interface" || word == "catch") + if (word == features.ClassKey || word == features.PackageKey || word == features.InterfaceKey || word == "catch") return false; if (features.hasInference && word == "for") // haxe doesn't have 'var' in for() return false; // new/extends/implements if (features.HasTypePreKey(word)) - return HandleNewCompletion(Sci, expr.Value, autoHide, word); + return HandleNewCompletion(sci, expr.Value, autoHide, word); // import if (features.hasImports && (word == features.importKey || word == features.importKeyAlt)) - return HandleImportCompletion(Sci, expr.Value, autoHide); + return HandleImportCompletion(sci, expr.Value, autoHide); + if (word == features.overrideKey) return HandleOverrideCompletion(expr.Value, autoHide); } // type - else if (features.hasEcmaTyping && expr.Separator == ':' - && HandleColonCompletion(Sci, expr.Value, autoHide)) + else if (features.hasEcmaTyping && expr.Separator == ":" && HandleColonCompletion(sci, expr.Value, autoHide)) return true; // no completion - if ((expr.BeforeBody && expr.Separator != '=') + if ((expr.BeforeBody && expr.Separator != "=") || expr.coma == ComaExpression.AnonymousObject || expr.coma == ComaExpression.FunctionDeclaration) return false; if (expr.coma == ComaExpression.AnonymousObjectParam) { - int cpos = Sci.CurrentPos - 1; - int paramIndex = FindParameterIndex(Sci, ref cpos); - if (calltipPos != cpos) ResolveFunction(Sci, cpos, autoHide); - if (calltipMember == null) return false; + var cpos = sci.CurrentPos - 1; + var paramIndex = FindParameterIndex(sci, ref cpos); + if (calltipPos != cpos) ctx.CodeComplete.ResolveFunction(sci, cpos, autoHide); + if (calltipMember is null) return false; argumentType = ResolveParameterType(paramIndex, true); if (argumentType.IsVoid()) return false; } // complete declaration - MemberModel cMember = ASContext.Context.CurrentMember; - int line = Sci.LineFromPosition(position); - if (cMember == null && !ASContext.Context.CurrentClass.IsVoid()) + var cMember = ctx.CurrentMember; + if (cMember is null && !ctx.CurrentClass.IsVoid()) { - if (expr.Value != null && expr.Value.Length > 0) - return HandleDeclarationCompletion(Sci, expr.Value, autoHide); - else if (ASContext.Context.CurrentModel.Version >= 2) - return ASGenerator.HandleGeneratorCompletion(Sci, autoHide, features.overrideKey); + if (expr.Value.Length != 0) return HandleDeclarationCompletion(sci, expr.Value, autoHide); + if (ctx.CurrentModel.Version >= 2) return ASGenerator.HandleGeneratorCompletion(sci, autoHide, features.overrideKey); } - else if (cMember != null && line == cMember.LineFrom) + else if (cMember != null && sci.LineFromPosition(position) is { } line && line == cMember.LineFrom) { - string text = Sci.GetLine(line); - int p = text.IndexOf(cMember.Name); - if (p < 0 || position < Sci.PositionFromLine(line) + p) - return HandleDeclarationCompletion(Sci, expr.Value, autoHide); + var text = sci.GetLine(line); + int p; + if ((cMember.Flags & FlagType.Constructor) != 0 && !string.IsNullOrEmpty(features.ConstructorKey)) + p = text.IndexOfOrdinal(features.ConstructorKey); + else p = text.IndexOfOrdinal(cMember.Name); + if (p < 0 || position < sci.PositionFromLine(line) + p) + return HandleDeclarationCompletion(sci, expr.Value, autoHide); } } - else - { - if (expr.Value.EndsWith("..") || Regex.IsMatch(expr.Value, "^[0-9]+\\.")) - return false; - } + else if (expr.Value.EndsWithOrdinal("..") || Regex.IsMatch(expr.Value, "^[0-9]+\\.")) + return false; - string tail = (dotIndex >= 0) ? expr.Value.Substring(dotIndex + features.dot.Length) : expr.Value; - // custom completion - MemberList items = ASContext.Context.ResolveDotContext(Sci, expr, autoHide); + var items = ctx.ResolveDotContext(sci, expr, autoHide); if (items != null) { - DotContextResolved(Sci, expr, items, autoHide); + DotContextResolved(sci, expr, items, autoHide); return true; } + + var tail = (dotIndex >= 0) ? expr.Value.Substring(dotIndex + features.dot.Length) : expr.Value; + + var outOfDate = (expr.Separator == ":") && ctx.UnsetOutOfDate(); + var cClass = ctx.CurrentClass; - // Context ASResult result; - ClassModel tmpClass; - bool outOfDate = (expr.Separator == ':') ? ctx.UnsetOutOfDate() : false; - FileModel cFile = ctx.CurrentModel; - ClassModel cClass = ctx.CurrentClass; - - expr.LocalVars = ParseLocalVars(expr); + ClassModel inClass; if (argumentType != null) { - result = new ASResult(); - tmpClass = argumentType; + inClass = argumentType; expr.LocalVars.Clear(); + result = new ASResult {Context = expr}; } - else if (dotIndex > 0) - { - // Expression before cursor - result = EvalExpression(expr.Value, expr, cFile, cClass, false, false); + else if (dotIndex > 0) + { + expr.LocalVars = ParseLocalVars(expr); + // Expression before cursor + result = EvalExpression(expr.Value, expr, ctx.CurrentModel, cClass, false, false); if (result.IsNull()) { if (outOfDate) ctx.SetOutOfDate(); return true; } - if (autoHide && features.hasE4X && IsXmlType(result.Type)) - return true; - tmpClass = result.Type; - } - else - { - result = new ASResult(); - if (expr.Separator == '"') - { - tmpClass = ctx.ResolveType("String", null); - result.Type = tmpClass; + if (autoHide && features.hasE4X && IsXmlType(result.Type)) return true; + inClass = result.Type; + } + else + { + expr.LocalVars = ParseLocalVars(expr); + result = new ASResult {Context = expr}; + if (expr.Separator == "\"") + { + inClass = ResolveType(ctx.Features.stringKey, null); + result.Type = inClass; dotIndex = 1; } - else tmpClass = cClass; - } - - //stores a reference to our current class. tmpClass gets overwritten later, so we need to store the current class separately - ClassModel classScope = tmpClass; - - MemberList mix = new MemberList(); - // local vars are the first thing to try - if ((result.IsNull() || (dotIndex < 0)) && expr.ContextFunction != null) - mix.Merge(expr.LocalVars); + else inClass = cClass; + } + var mix = new MemberList(); + ctx.ResolveDotContext(sci, result, mix); - // get all members - FlagType mask = 0; - // members visibility - ClassModel curClass = cClass; - curClass.ResolveExtends(); - Visibility acc = ctx.TypesAffinity(curClass, tmpClass); + // local vars are the first thing to try + if ((result.IsNull() || dotIndex < 0) && expr.ContextFunction != null) mix.Merge(expr.LocalVars); // list package elements if (result.IsPackage) @@ -1864,263 +1975,357 @@ static private bool HandleDotCompletion(ScintillaControl Sci, bool autoHide) mix.Merge(result.InFile.Members); } // list instance members - else if (expr.ContextFunction != null || expr.Separator != ':' || (dotIndex > 0 && !result.IsNull())) - { - // user setting may ask to hide some members - bool limitMembers = autoHide; // ASContext.Context.HideIntrinsicMembers || (autoHide && !ASContext.Context.AlwaysShowIntrinsicMembers); - + else if (expr.ContextFunction != null || expr.Separator != ":" || (dotIndex > 0 && !result.IsNull())) + { // static or instance members? + FlagType mask; if (!result.IsNull()) mask = result.IsStatic ? FlagType.Static : FlagType.Dynamic; - else if (expr.ContextFunction == null || IsStatic(expr.ContextFunction)) mask = FlagType.Static; + else if (IsStatic(expr.ContextFunction)) mask = FlagType.Static; else mask = 0; if (argumentType != null) mask |= FlagType.Variable; + var limitMembers = autoHide; + if (!limitMembers || result.IsStatic || inClass.Name != features.objectKey) + GetInstanceMembers(autoHide, result, inClass, mask, dotIndex, mix); + } - // explore members - tmpClass.ResolveExtends(); - if (!limitMembers || result.IsStatic || tmpClass.Name != features.objectKey) - while (tmpClass != null && !tmpClass.IsVoid()) - { - mix.Merge(tmpClass.GetSortedMembersList(), mask, acc); + // known types/toplevel vars/methods + if (argumentType is null && (result.IsNull() || dotIndex < 0)) + { + mix.Merge(ctx.CurrentModel.GetSortedMembersList()); + IEnumerable topLevelElements = ctx.GetTopLevelElements(); + if (expr.ContextFunction != null && expr.ContextFunction.Flags.HasFlag(FlagType.Static)) + topLevelElements = topLevelElements.Where(static it => it.Flags.HasFlag(FlagType.Static)); + mix.Merge(topLevelElements); + if (!ctx.Settings.LazyClasspathExploration && ctx.Settings.CompletionListAllTypes) + mix.Merge(ctx.GetAllProjectClasses()); + mix.Merge(ctx.GetVisibleExternalElements()); + mix.Merge(GetKeywords()); + } - // static inheritance - if ((mask & FlagType.Static) > 0) - { - if ((!features.hasStaticInheritance || dotIndex > 0) && (tmpClass.Flags & FlagType.TypeDef) == 0) - break; - } + // show + list ??= new List(mix.Count); + foreach (var member in mix) + { + if ((member.Flags & FlagType.Template) > 0) list.Add(new TemplateItem(member)); + else list.Add(new MemberItem(member)); + } + if (comparison != null) list.Sort(comparison); + EventManager.DispatchEvent(null, new DataEvent(EventType.Command, "ASCompletion.DotCompletion", list)); + CompletionList.Show(list, autoHide, tail); + + // smart focus token + AutoselectDotToken(inClass, tail); + + if (outOfDate) ctx.SetOutOfDate(); + return true; + } + + protected virtual void GetInstanceMembers(bool autoHide, ASResult expr, ClassModel exprType, FlagType mask, int dotIndex, MemberList result) + { + var ctx = ASContext.Context; + var features = ctx.Features; + var currentClass = ctx.CurrentClass; - //if ((mask & FlagType.Static) > 0 // only show direct static inheritance - // && (!features.hasStaticInheritance || dotIndex > 0)) break; + currentClass.ResolveExtends(); + var access = TypesAffinity(expr.Context, currentClass, exprType); - tmpClass = tmpClass.Extends; - // hide Object class members - if (limitMembers && tmpClass != null && tmpClass.InFile.Package == "" && tmpClass.Name == features.objectKey) + // explore members + exprType.ResolveExtends(); + if (exprType.ExtendsType is { } extendsType && !string.IsNullOrEmpty(extendsType) && extendsType != features.objectKey + && exprType.Extends.IsVoid() && !string.IsNullOrEmpty(exprType.Template) && !string.IsNullOrEmpty(exprType.IndexType)) + { + /** + * Temporary fix: + * If `inClass` is generic type with the concrete type explicit definition, like `Null`, + * there can be problems in `inClass.ResolveExtends()` because `inClass` contains a link to the real file with origin declaration, like `Null`, not current file + */ + exprType = exprType.Clone(); + if (expr.InFile != null && !ResolveType(extendsType, expr.InFile).IsVoid()) exprType.InFile = expr.InFile; + else exprType.InFile = ctx.CurrentModel; + exprType.ResolveExtends(); + } + while (!exprType.IsVoid()) + { + result.Merge(exprType.GetSortedMembersList(), mask, access); + // static inheritance + if ((mask & FlagType.Static) > 0) + { + if ((!features.hasStaticInheritance || dotIndex > 0) && (exprType.Flags & FlagType.TypeDef) == 0) break; - // members visibility - acc = ctx.TypesAffinity(curClass, tmpClass); } - } - // known classes / toplevel vars/methods - if (argumentType == null && (result.IsNull() || (dotIndex < 0))) - { - mix.Merge(cFile.GetSortedMembersList()); - mix.Merge(ctx.GetTopLevelElements()); - mix.Merge(ctx.GetVisibleExternalElements()); - MemberList decl = new MemberList(); - foreach (string key in features.codeKeywords) - decl.Add(new MemberModel(key, key, FlagType.Template, 0)); - decl.Sort(); - mix.Merge(decl); + else if (!features.hasStaticInheritance) mask |= FlagType.Dynamic; + exprType = exprType.Extends; + // hide Object class members + if (autoHide && !exprType.IsVoid() && exprType.InFile.Package == "" && exprType.Name == features.objectKey) + break; + // members visibility + access = ctx.TypesAffinity(currentClass, exprType); } + } - // show - List list = new List(); - foreach(MemberModel member in mix) - list.Add(new MemberItem(member)); - CompletionList.Show(list, autoHide, tail); + protected virtual Visibility TypesAffinity(ASExpr context, ClassModel inClass, ClassModel withClass) => ASContext.Context.TypesAffinity(inClass, withClass); - // smart focus token - //if (!features.externalCompletion) - AutoselectDotToken(classScope, tail); + static MemberList GetKeywords() + { + var ctx = ASContext.Context; + var features = ctx.Features; + var inClass = !ctx.CurrentClass.IsVoid(); - if (outOfDate) ctx.SetOutOfDate(); - return true; - } + var result = new MemberList(); + if (inClass || !ctx.CurrentModel.haXe) + { + foreach (var key in features.codeKeywords) + result.Add(new MemberModel(key, key, FlagType.Template, 0)); + } + if (!inClass) + { + foreach (var key in features.accessKeywords) result.Add(new MemberModel(key, key, FlagType.Template, 0)); + foreach (var key in features.typesKeywords) result.Add(new MemberModel(key, key, FlagType.Template, 0)); + } + result.Sort(); + return result; + } - private static bool DeclarationSectionOnly() + static bool DeclarationSectionOnly() { - ClassModel inClass = ASContext.Context.CurrentClass; - if (!inClass.IsVoid() && (inClass.Flags & (FlagType.Enum | FlagType.TypeDef | FlagType.Struct)) > 0) - return true; - return false; + var inClass = ASContext.Context.CurrentClass; + return !inClass.IsVoid() && (inClass.Flags & (FlagType.Enum | FlagType.TypeDef | FlagType.Struct)) > 0; } - private static void AutoselectDotToken(ClassModel classScope, string tail) + static void AutoselectDotToken(ClassModel classScope, string tail) { // remember the latest class resolved for completion to store later the inserted member - currentClassHash = classScope != null ? classScope.QualifiedName : null; + currentClassHash = classScope?.QualifiedName; // if the completion history has a matching entry, it means the user has previously completed from this class. - if (currentClassHash != null && completionHistory.ContainsKey(currentClassHash)) + if (currentClassHash is null) return; + if (!completionHistory.TryGetValue(currentClassHash, out var history)) return; + // If the last-completed member for the class starts with the currently typed text (tail), select it! + // Note that if the tail is currently empty (i.e., the user has just typed the first dot), this still passes. + // This allows it to highlight the last-completed member instantly just by hitting the dot. + // Also does a check if the tail matches exactly the currently selected item; don't change it! + if (CompletionList.SelectedLabel != tail && history.ToLower().StartsWithOrdinal(tail.ToLower())) { - // If the last-completed member for the class starts with the currently typed text (tail), select it! - // Note that if the tail is currently empty (i.e., the user has just typed the first dot), this still passes. - // This allows it to highlight the last-completed member instantly just by hitting the dot. - // Also does a check if the tail matches exactly the currently selected item; don't change it! - if (CompletionList.SelectedLabel != tail && completionHistory[currentClassHash].ToLower().StartsWith(tail.ToLower())) - { - CompletionList.SelectItem(completionHistory[currentClassHash]); - } + CompletionList.SelectItem(history); } } - static public void DotContextResolved(ScintillaControl Sci, ASExpr expr, MemberList items, bool autoHide) + public static void DotContextResolved(ScintillaControl sci, ASExpr expr, MemberList items, bool autoHide) { // still valid context and position? - if (Sci != ASContext.CurSciControl) return; - int position = Sci.CurrentPos; - ContextFeatures features = ASContext.Context.Features; - ASExpr local = GetExpression(Sci, position); - if (!local.Value.StartsWith(expr.Value) - || expr.Value.LastIndexOf(features.dot) != local.Value.LastIndexOf(features.dot)) + if (sci != PluginBase.MainForm.CurrentDocument?.SciControl) return; + var features = ASContext.Context.Features; + var position = sci.CurrentPos; + var local = GetExpression(sci, position); + if (!local.Value.StartsWithOrdinal(expr.Value) + || expr.Value.LastIndexOfOrdinal(features.dot) != local.Value.LastIndexOfOrdinal(features.dot)) return; - string word = Sci.GetWordLeft(position-1, false); + var word = sci.GetWordLeft(position - 1, false); // current list string reSelect = null; if (CompletionList.Active) reSelect = CompletionList.SelectedLabel; // show completion - List customList = new List(); - bool testActive = !CompletionList.Active && expr.Position != position; - foreach (MemberModel member in items) + var list = new List(items.Count); + var testActive = !CompletionList.Active && expr.Position != position; + foreach (var member in items) { - if (testActive && member.Name == word) - return; - customList.Add(new MemberItem(member)); + if (testActive && member.Name == word) return; + list.Add(CompletionList.Get(member.Name) ?? new MemberItem(member)); } - CompletionList.Show(customList, autoHide, word); + EventManager.DispatchEvent(null, new DataEvent(EventType.Command, "ASCompletion.DotCompletion", list)); + CompletionList.Show(list, autoHide, word); if (reSelect != null) CompletionList.SelectItem(reSelect); } - #endregion + #endregion - #region types_completion + #region types_completion - static private void SelectTypedNewMember(ScintillaControl sci) + /// + /// List methods to override + /// + /// Don't keep the list open if the word does not match + /// Completion was handled + internal bool HandleOverrideCompletion(string tail, bool autoHide) { - try + var ctx = ASContext.Context; + var curClass = ctx.CurrentClass; + if (curClass.IsVoid()) return false; + + var members = new List(); + curClass.ResolveExtends(); + + const FlagType mask = FlagType.Function | FlagType.Getter | FlagType.Setter; + var tmpClass = curClass.Extends; + var access = ctx.TypesAffinity(curClass, tmpClass); + while (!tmpClass.IsVoid()) { - ASExpr expr = GetExpression(sci, sci.CurrentPos); - if (expr.Value == null) return; - IASContext ctx = ASContext.Context; - // try local var - expr.LocalVars = ParseLocalVars(expr); - foreach (MemberModel localVar in expr.LocalVars) + if (tmpClass.QualifiedName.StartsWithOrdinal("flash.utils.Proxy")) { - if (localVar.LineTo == ctx.CurrentLine) + foreach (var member in tmpClass.Members) { - if (localVar.Type != null) // Might be non typed var - { - string typeName = localVar.Type; - ClassModel aClass = ctx.ResolveType(typeName, ctx.CurrentModel); - if (!aClass.IsVoid()) typeName = aClass.Constructor ?? aClass.Name; - CompletionList.SelectItem(typeName); - } - return; + member.Namespace = "flash_proxy"; + members.Add(member); } + break; } - // try member - string currentLine = sci.GetLine(sci.LineFromPosition(sci.CurrentPos)); - Match mVarNew = Regex.Match(currentLine, "\\s*(?[a-z_$][a-z._$0-9]*)(?[: ]*)(?[a-z.0-9<>]*)\\s*=\\s*new\\s", RegexOptions.IgnoreCase); - if (mVarNew.Success) + foreach (var member in tmpClass.Members) { - string name = mVarNew.Groups["name"].Value; - ASResult result = EvalExpression(name, expr, ctx.CurrentModel, ctx.CurrentClass, true, false); - if (result != null && result.Member != null && result.Member.Type != null) // Might be missing or wrongly typed member + if (curClass.Members.Contains(member.Name, FlagType.Override, 0)) continue; + if ((member.Flags & FlagType.Dynamic) == 0 + || (member.Access & access) == 0 + || ((member.Flags & FlagType.Function) == 0 && (member.Flags & mask) == 0)) continue; + if (!member.Parameters.IsNullOrEmpty()) { - string typeName = result.Member.Type; - ClassModel aClass = ctx.ResolveType(typeName, ctx.CurrentModel); - if (!aClass.IsVoid()) typeName = aClass.Constructor ?? aClass.Name; - CompletionList.SelectItem(typeName); + foreach (var it in member.Parameters) + { + if ((it.Flags & FlagType.Function) == 0 || it.Parameters is null) continue; + it.Type = ctx.CodeComplete.ToFunctionDeclarationString(it); + it.Parameters = null; + } + // for example: function get value():Function/*(v:*):ReturnType*/ + if ((member.Flags & FlagType.Getter) != 0) + { + member.Type = ctx.CodeComplete.ToFunctionDeclarationString(member); + member.Parameters = null; + } } + members.Add(member); } + tmpClass = tmpClass.Extends; + // members visibility + access = ctx.TypesAffinity(curClass, tmpClass); + } + members.Sort(); + var list = new List(members.Count); + MemberModel last = null; + foreach (var member in members) + { + if (last is null || last.Name != member.Name) + list.Add(new MemberItem(member)); + last = member; } - catch {} // Do not throw exception with incorrect types + if (list.Count > 0) CompletionList.Show(list, autoHide, tail); + return true; } - static private bool HandleNewCompletion(ScintillaControl Sci, string tail, bool autoHide, string keyword) - { + protected static bool HandleNewCompletion(ScintillaControl sci, string tail, bool autoHide, string keyword) + { + List list; + if (!ASContext.Context.Settings.LazyClasspathExploration && ASContext.Context.Settings.CompletionListAllTypes) { - // show all project classes - HandleAllClassesCompletion(Sci, tail, true, true); - SelectTypedNewMember(Sci); - return true; + list = GetAllClasses(sci, true, true); + if (list is null) return true; + } + else + { + // Consolidate known classes + var known = GetVisibleElements(); + list = known + .Select(static it => new MemberItem(new MemberModel(it.Type, it.Type, it.Flags, it.Access))) + .ToList(); } + return ASContext.Context.CodeComplete.HandleNewCompletion(sci, tail, autoHide, keyword, list); + } - // Consolidate known classes - MemberList known = new MemberList(); - known.Merge(ASContext.Context.GetVisibleExternalElements()); - // show - List list = new List(); - foreach(MemberModel member in known) - list.Add(new MemberItem(new MemberModel(member.Type, member.Type, member.Flags, member.Access))); - CompletionList.Show(list, autoHide, tail); - SelectTypedNewMember(Sci); - return true; - } - - static private bool HandleImportCompletion(ScintillaControl Sci, string tail, bool autoHide) - { - if (!ASContext.Context.Features.hasImports) return false; + protected virtual bool HandleNewCompletion(ScintillaControl sci, string tail, bool autoHide, string keyword, List list) + { + // If we are instantiating a class: + // 1. Type exists: + // a. Generic type -> Show it with our index type. + // b. Not generic type -> Show existing one + // 2. Type doesn't exist -> Show it with a warning symbol. + if (keyword == "new" && !tail.IsNullOrEmpty()) + { + var newItemType = tail; + ICompletionListItem newItem = null; + var aClass = ResolveType(newItemType, ASContext.Context.CurrentModel); + if (!aClass.IsVoid()) + { + // AS2 special srictly typed Arrays supports + if (newItemType.Contains('@', out var p)) newItemType = newItemType.Substring(0, p); + else if (!string.IsNullOrEmpty(aClass.IndexType)) + { + newItem = new MemberItem(new MemberModel(newItemType, aClass.Type, aClass.Flags, aClass.Access)); + } + } + else newItem = new NonexistentMemberItem(newItemType); + if (newItem != null) + { + var itemIndex = list.FindIndex(item => string.Compare(item.Label, newItem.Label, StringComparison.OrdinalIgnoreCase) >= 0); + if (newItemType.Contains('<', out var genericStart) && ASContext.Context.Features.HasGenericsShortNotation) + { + newItemType = newItemType.Substring(0, genericStart); + itemIndex = itemIndex > 0 ? itemIndex : 0; + } + else itemIndex = itemIndex > 0 ? itemIndex - 1 : 0; + list.Insert(itemIndex, newItem); + } + CompletionList.Show(list, autoHide); + CompletionList.SelectItem(newItemType); + } + else CompletionList.Show(list, autoHide, tail); + return true; + } + static bool HandleImportCompletion(ScintillaControl sci, string tail, bool autoHide) + { + if (!ASContext.Context.Features.hasImports) return false; if (!ASContext.Context.Settings.LazyClasspathExploration && ASContext.Context.Settings.CompletionListAllTypes) { // show all project classes - HandleAllClassesCompletion(Sci, "", false, false); + HandleAllClassesCompletion(sci, "", false, false); } else { // list visible classes - MemberList known = new MemberList(); - known.Merge(ASContext.Context.GetVisibleExternalElements()); - - // show - List list = new List(); - foreach (MemberModel member in known) - list.Add(new MemberItem(member)); + var known = GetVisibleElements(); + var list = known.Select(static it => new MemberItem(it)).ToArray(); CompletionList.Show(list, autoHide, tail); } - return true; - } - - static private bool HandleColonCompletion(ScintillaControl Sci, string tail, bool autoHide) - { - ComaExpression coma; - if (DeclarationSectionOnly()) coma = ComaExpression.FunctionDeclaration; - else coma = GetFunctionContext(Sci, autoHide); + return true; + } + static bool HandleColonCompletion(ScintillaControl sci, string tail, bool autoHide) + { + var coma = DeclarationSectionOnly() + ? ComaExpression.FunctionDeclaration + : GetFunctionContext(sci, autoHide); if (coma != ComaExpression.FunctionDeclaration && coma != ComaExpression.VarDeclaration) return false; - if (!ASContext.Context.Settings.LazyClasspathExploration - && ASContext.Context.Settings.CompletionListAllTypes) + var ctx = ASContext.Context; + if (!ctx.Settings.LazyClasspathExploration && ctx.Settings.CompletionListAllTypes) { // show all project classes - HandleAllClassesCompletion(Sci, tail, true, false); + HandleAllClassesCompletion(sci, tail, true, false); } else { - bool outOfDate = ASContext.Context.UnsetOutOfDate(); - + var outOfDate = ctx.UnsetOutOfDate(); // list visible classes - MemberList known = new MemberList(); - ClassModel cClass = ASContext.Context.CurrentClass; - known.Merge(ASContext.Context.GetVisibleExternalElements()); - - // show - List list = new List(); - foreach (MemberModel member in known) - list.Add(new MemberItem(member)); + var known = GetVisibleElements(); + var list = known.Select(static it => new MemberItem(it)).ToArray(); CompletionList.Show(list, autoHide, tail); - if (outOfDate) ASContext.Context.SetOutOfDate(); + if (outOfDate) ctx.SetOutOfDate(); } return true; - } + } - private static ComaExpression GetFunctionContext(ScintillaControl Sci, bool autoHide) + static ComaExpression GetFunctionContext(ScintillaControl sci, bool autoHide) { - ComaExpression coma = ComaExpression.None; - int position = Sci.CurrentPos - 1; - char c = ' '; + var position = sci.CurrentPos - 1; + var c = ' '; //bool inGenericType = false; while (position > 0) { - c = (char)Sci.CharAt(position); + c = (char)sci.CharAt(position); //if (c == '<') inGenericType = true; if (c == ':' || c == ';' || c == '=' || c == ',') break; position--; @@ -2128,18 +2333,20 @@ private static ComaExpression GetFunctionContext(ScintillaControl Sci, bool auto position--; // var declaration - GetWordLeft(Sci, ref position); - string keyword = (c == ':') ? GetWordLeft(Sci, ref position) : null; - if (keyword == ASContext.Context.Features.varKey || keyword == ASContext.Context.Features.constKey) - coma = ComaExpression.VarDeclaration; + GetWordLeft(sci, ref position); + var ctx = ASContext.Context; + var features = ctx.Features; + var keyword = c == ':' ? GetWordLeft(sci, ref position) : null; + if (keyword == features.varKey || (features.constKey != null && keyword == features.constKey)) + return ComaExpression.VarDeclaration; // function return type - else if ((char)Sci.CharAt(position) == ')') + if ((char)sci.CharAt(position) == ')') { - int parCount = 0; + var parCount = 0; while (position > 0) { position--; - c = (char)Sci.CharAt(position); + c = (char)sci.CharAt(position); if (c == ')') parCount++; else if (c == '(') { @@ -2151,155 +2358,226 @@ private static ComaExpression GetFunctionContext(ScintillaControl Sci, bool auto } } } - keyword = GetWordLeft(Sci, ref position); - ContextFeatures features = ASContext.Context.Features; - if (keyword == features.functionKey) - coma = ComaExpression.FunctionDeclaration; - else + keyword = GetWordLeft(sci, ref position); + if (keyword.Length == 0 && sci.CharAt(position) == '>' && features.hasGenerics) { - keyword = GetWordLeft(Sci, ref position); - if (keyword == features.functionKey || keyword == features.getKey || keyword == features.setKey) - coma = ComaExpression.FunctionDeclaration; + var groupCount = 1; + position--; + while (position >= 0 && groupCount > 0) + { + c = (char)sci.CharAt(position); + if ("({[<".Contains(c)) groupCount--; + else if (")}]>".Contains(c)) groupCount++; + position--; + } + keyword = GetWordLeft(sci, ref position); } + if (keyword == features.functionKey) return ComaExpression.FunctionDeclaration; + keyword = GetWordLeft(sci, position); + if (keyword == features.functionKey || keyword == features.getKey || keyword == features.setKey) + return ComaExpression.FunctionDeclaration; + if (ctx.CurrentModel.haXe + && keyword == features.varKey + && (ctx.CurrentMember is null || (ctx.CurrentMember.Flags & FlagType.Function) == 0)) + return ComaExpression.VarDeclaration; // Haxe Properties + return ComaExpression.None; } - // needs more guessing - else + // config constant, or namespace access + if (autoHide && string.IsNullOrEmpty(keyword) && position > 0 && (char)sci.CharAt(position) == ':') { - // config constant, or namespace access - if (keyword == "" && position > 0 && (char)Sci.CharAt(position) == ':') - { - int pos = position - 1; - keyword = GetWordLeft(Sci, ref pos); - if (keyword != "" && autoHide) return ComaExpression.None; - } - coma = DisambiguateComa(Sci, position, 0); + keyword = GetWordLeft(sci, position - 1); + if (keyword.Length == 0) return ComaExpression.None; } - return coma; + return DisambiguateComa(sci, position, 0); } /// /// Display the full project classes list /// - /// - static public void HandleAllClassesCompletion(ScintillaControl Sci, string tail, bool classesOnly, bool showClassVars) + /// + public static void HandleAllClassesCompletion(ScintillaControl sci, string tail, bool classesOnly, bool showClassVars) { - MemberList known = ASContext.Context.GetAllProjectClasses(); - if (known.Count == 0) return; - - // get local Class vars - if (showClassVars) - { - MemberList found = new MemberList(); + var list = GetAllClasses(sci, classesOnly, showClassVars); + list.Sort(new CompletionItemCaseSensitiveImportComparer()); + CompletionList.Show(list, false, tail); + } - ASExpr expr = GetExpression(Sci, Sci.CurrentPos); - if (expr.Value != null) - { - MemberList locals = ParseLocalVars(expr); - foreach (MemberModel local in locals) - if (local.Type == "Class") - found.Add(local); - } + static bool HandleInterpolationCompletion(ScintillaControl sci, bool autoHide, bool expressions) + { + var expr = GetExpression(sci, sci.CurrentPos); + if (expr.ContextMember is null) return false; + var ctx = ASContext.Context; + var members = new MemberList(); + members.Merge(ctx.CurrentClass.GetSortedMembersList()); + if ((expr.ContextMember.Flags & FlagType.Static) > 0) + members.RemoveAllWithoutFlag(FlagType.Static); + else members.Merge(ctx.CurrentClass.GetSortedInheritedMembersList()); + members.Merge(ParseLocalVars(expr)); + if (!expressions) members.RemoveAllWithFlag(FlagType.Function); + var list = members.Select(static it => new MemberItem(it)).ToArray(); + CompletionList.Show(list, autoHide); + return true; + } + #endregion - if (found.Count > 0) + /// + /// Handle completion after inserting a space character + /// + /// Scintilla control + /// Current cursor position + /// Don't keep the list open if the word does not match + /// Auto-completion has been handled + bool HandleWhiteSpaceCompletion(ScintillaControl sci, int position, bool autoHide) + { + var pos = position - 1; + var word = GetWordLeft(sci, ref pos); + if (HandleWhiteSpaceCompletion(sci, position, word, autoHide)) return true; + var ctx = ASContext.Context; + var features = ctx.Features; + if (word.Length == 0) + { + var c = (char)sci.CharAt(pos); + if (c == ':' && features.hasEcmaTyping) return HandleColonCompletion(sci, string.Empty, autoHide); + if (c == ',') { - found.Sort(); - found.Merge(known); - known = found; + var currentClass = ctx.CurrentClass; + if (currentClass.Flags.HasFlag(FlagType.Class) && PositionIsBeforeBody(sci, pos, currentClass)) + { + var endPosition = sci.PositionFromLine(currentClass.LineFrom); + for (var i = pos; i > endPosition; i--) + { + if (sci.PositionIsOnComment(i)) continue; + var e = GetExpressionType(sci, i, false, true); + if (e.Type == currentClass) break; + var value = e.Context.Value; + if (value == features.ExtendsKey) break; + if (value == features.ImplementsKey) return HandleNewCompletion(sci, string.Empty, autoHide, string.Empty); + i -= value.Length; + } + } } + if (autoHide && (c == '(' || c == ',') && !ASContext.CommonSettings.DisableCallTip) + return HandleFunctionCompletion(sci, autoHide); + return false; } - - if (ASContext.Context.Features.hasDelegates && !ASContext.Context.CurrentClass.IsVoid()) + // import + if (features.hasImports && (word == features.importKey || word == features.importKeyAlt)) + return HandleImportCompletion(sci, string.Empty, autoHide); + if (word == features.PackageKey || features.typesKeywords.Contains(word)) return false; + if (word == features.ImplementsKey) return HandleImplementsCompletion(sci, autoHide); + // new/extends/instanceof/... + if (features.HasTypePreKey(word)) { - foreach (MemberModel field in ASContext.Context.CurrentClass.Members) - if ((field.Flags & FlagType.Delegate) > 0) - known.Add(field); + var tail = string.Empty; + // for example: var v:Type = new $(EntryPoint) + if (GetOperatorLeft(sci, ref pos) == "=" && GetExpression(sci, pos)?.Value is { } v) + tail = v; + return HandleNewCompletion(sci, tail, autoHide, word); } + if (features.OperatorKeywords.Contains(word)) return OnChar(sci, '.', autoHide); + var expr = CurrentResolvedContext?.Result?.Context; + var beforeBody = expr is not null && (expr.ContextFunction is null || expr.BeforeBody); + if (!beforeBody && features.codeKeywords.Contains(word)) return false; + if (word == features.overrideKey) return ASGenerator.HandleGeneratorCompletion(sci, autoHide, word); + // public/internal/private/protected/static + if (features.accessKeywords.Contains(word)) return HandleDeclarationCompletion(sci, string.Empty, autoHide); + return false; + } - List list = new List(); - string prev = null; - FlagType mask = (classesOnly) ? - FlagType.Class | FlagType.Interface | FlagType.Enum | FlagType.Delegate | FlagType.Struct | FlagType.TypeDef - : (FlagType)uint.MaxValue; - foreach (MemberModel member in known) + /// + /// Handle completion after inserting a space character + /// + /// Scintilla control + /// Current cursor position + /// Word before cursor + /// Don't keep the list open if the word does not match + /// Auto-completion has been handled + protected virtual bool HandleWhiteSpaceCompletion(ScintillaControl sci, int position, string wordLeft, bool autoHide) => false; + + /// + /// Display the full project interfaces list + /// + /// Scintilla control + /// Don't keep the list open if the word does not match + /// Auto-completion has been handled + protected virtual bool HandleImplementsCompletion(ScintillaControl sci, bool autoHide) + { + var classes = ASContext.Context.GetAllProjectClasses(); + var list = new List(classes.Count); + foreach (var it in classes) { - if ((member.Flags & mask) == 0 || prev == member.Name) - if (!showClassVars || member.Type != "Class") continue; - prev = member.Name; - list.Add(new MemberItem(member)); + if (!it.Flags.HasFlag(FlagType.Interface)) continue; + list.Add(new MemberItem(it)); } - - CompletionList.Show(list, false, tail); + CompletionList.Show(list, autoHide); + return true; } - #endregion - #region expression_evaluator - /// - /// Find expression type in function context - /// - /// To evaluate + #region expression_evaluator + + /// + /// Find expression type in function context + /// + /// To evaluate /// Completion context /// File context - /// Class context - /// Complete (sub-expression) or partial (dot-completion) evaluation - /// Class/member struct - static private ASResult EvalExpression(string expression, ASExpr context, FileModel inFile, ClassModel inClass, bool complete, bool asFunction) - { - ASResult notFound = new ASResult(); - notFound.Context = context; - if (expression == null || expression.Length == 0) - return notFound; + /// Class context + /// Complete (sub-expression) or partial (dot-completion) evaluation + /// + /// Class/member struct + static ASResult EvalExpression(string expression, ASExpr context, FileModel inFile, ClassModel inClass, bool complete, bool asFunction) + => ASContext.Context.CodeComplete.EvalExpression(expression, context, inFile, inClass, complete, asFunction, true); - ContextFeatures features = ASContext.Context.Features; - if (expression.StartsWith(features.dot)) + /// + /// Find expression type in function context + /// + /// To evaluate + /// Completion context + /// File context + /// Class context + /// Complete (sub-expression) or partial (dot-completion) evaluation + /// + /// + /// Class/member struct + protected virtual ASResult EvalExpression(string expression, ASExpr context, FileModel inFile, ClassModel inClass, bool complete, bool asFunction, bool filterVisibility) + { + var notFound = new ASResult {Context = context}; + if (string.IsNullOrEmpty(expression)) return notFound; + if (expression[0] == '.') { - if (expression.StartsWith(features.dot + "#")) expression = expression.Substring(1); - else if (context.Separator == '"') expression = '"' + expression; + if (expression.StartsWithOrdinal(".#")) expression = expression.Substring(1); + else if (context.Separator == "\"") expression = "\"" + expression; else return notFound; } - string[] tokens = Regex.Split(expression, Regex.Escape(features.dot)); - - // eval first token - string token = tokens[0]; + var tokens = Split(expression); + var token = tokens[0]; + if (token.Length == 0) return notFound; if (asFunction && tokens.Length == 1) token += "("; - - ASResult head; - if (token.Length == 0) - return notFound; - - else if (token.StartsWith("#")) + var ctx = ASContext.Context; + var features = ctx.Features; + ASResult head; + if (token[0] == '#') { - Match mSub = re_sub.Match(token); + var mSub = re_sub.Match(token); if (mSub.Success) { - bool haxeCast = false; - if (ASContext.Context.CurrentModel.haXe && context.SubExpressions.Contains("cast")) - { - haxeCast = true; - context.SubExpressions.Remove("cast"); - } - string subExpr = context.SubExpressions[Convert.ToInt16(mSub.Groups["index"].Value)]; - if (haxeCast) subExpr = subExpr.Replace(" ", "").Replace(",", " as "); + var subExpr = context.SubExpressions[Convert.ToInt16(mSub.Groups["index"].Value)]; // parse sub expression subExpr = subExpr.Substring(1, subExpr.Length - 2).Trim(); - ASExpr subContext = new ASExpr(context); + var subContext = new ASExpr(context); subContext.SubExpressions = ExtractedSubex = new List(); - subExpr = re_balancedParenthesis.Replace(subExpr, new MatchEvaluator(ExtractSubex)); - Match m = re_refineExpression.Match(subExpr); + subExpr = re_balancedParenthesis.Replace(subExpr, ExtractSubex); + var m = re_refineExpression.Match(subExpr); if (!m.Success) return notFound; - Regex re_dot = new Regex("[\\s]*" + Regex.Escape(features.dot) + "[\\s]*"); + var re_dot = new Regex("[\\s]*" + Regex.Escape(features.dot) + "[\\s]*"); subExpr = re_dot.Replace(re_whiteSpace.Replace(m.Value, " "), features.dot).Trim(); - int space = subExpr.LastIndexOf(' '); - if (space > 0) - { - string trash = subExpr.Substring(0, space).TrimEnd(); - subExpr = subExpr.Substring(space + 1); - if (trash.EndsWith("as")) subExpr += features.dot + "#"; - } + var space = subExpr.LastIndexOf(' '); + if (space > 0) subExpr = subExpr.Substring(space + 1); // eval sub expression head = EvalExpression(subExpr, subContext, inFile, inClass, true, false); if (head.Member != null) - head.Type = ASContext.Context.ResolveType(head.Member.Type, head.Type.InFile); + head.Type = ResolveType(head.Member.Type, head.Type.InFile); } else { @@ -2307,93 +2585,116 @@ static private ASResult EvalExpression(string expression, ASExpr context, FileMo head = EvalVariable(token, context, inFile, inClass); } } - else if (token == "\"") // literal string + else { - head = new ASResult(); - head.Type = ASContext.Context.ResolveType("String", null); + var type = ctx.ResolveToken(token, inClass.InFile); + if (!type.IsVoid()) return EvalTail(context, inFile, new ASResult {Type = type}, tokens, complete, filterVisibility) ?? notFound; + head = token.Contains('<') + ? new ASResult {Type = ResolveType(token, inFile)} + : EvalVariable(token, context, inFile, inClass); } - else head = EvalVariable(token, context, inFile, inClass); // regular eval - // no head, exit - if (head.IsNull()) return notFound; + // no head, exit + if (head.IsNull()) return notFound; // accessing instance member in static function, exit - if (IsStatic(context.ContextFunction) && head.RelClass == inClass + if (IsStatic(context.ContextFunction) && context.WordBefore != features.overrideKey + && head.RelClass == inClass && head.Member != null && !IsStatic(head.Member) && (head.Member.Flags & FlagType.Constructor) == 0) return notFound; // resolve - ASResult result = EvalTail(context, inFile, head, tokens, complete); + var result = EvalTail(context, inFile, head, tokens, complete, filterVisibility); // if failed, try as qualified class name - if ((result == null || result.IsNull()) && tokens.Length > 1) + if ((result is null || result.IsNull()) && tokens.Length > 1) + { + var qualif = ResolveType(expression, null); + if (!qualif.IsVoid()) return new ASResult {Context = context, IsStatic = true, InFile = qualif.InFile, Type = qualif}; + } + return result ?? notFound; + // Utils + static string[] Split(string expr) { - ClassModel qualif = ASContext.Context.ResolveType(expression, null); - if (!qualif.IsVoid()) + var list = new List(); + var groupCount = 0; + var prevStartIndex = 0; + var length = expr.Length - 1; + for (var i = 0; i <= length; i++) { - result = new ASResult(); - result.Context = context; - result.IsStatic = true; - result.InFile = qualif.InFile; - result.Type = qualif; + var c = expr[i]; + if (c == '[' || c == '(' || c == '{') groupCount++; + else if (c == ']' || c == ')' || c == '}') groupCount--; + if (groupCount == 0 && (c == '.' || i == length)) + { + var len = i - prevStartIndex; + if (c != '.' && i == length) len++; + list.Add(expr.Substring(prevStartIndex, len)); + prevStartIndex = i + 1; + if (c == '.' && i == length) list.Add(string.Empty); + } } + if (list.Count == 0) list.Add(expr); + return list.ToArray(); } - return result ?? notFound; } - static ASResult EvalTail(ASExpr context, FileModel inFile, ASResult head, string[] tokens, bool complete) + static ASResult EvalTail(ASExpr context, FileModel inFile, ASResult head, IList tokens, bool complete, bool filterVisibility) { - // eval tail - int n = tokens.Length; - if (!complete) n--; - // context - ContextFeatures features = ASContext.Context.Features; - ASResult step = head; - ClassModel resultClass = head.Type; - // look for static or dynamic members? - FlagType mask = head.IsStatic ? FlagType.Static : FlagType.Dynamic; + // eval tail + int n = tokens.Count; + if (!complete) n--; + // context + var ctx = ASContext.Context; + var features = ctx.Features; + var step = head; + // look for static or dynamic members? + var mask = head.IsStatic ? FlagType.Static : FlagType.Dynamic; // members visibility - IASContext ctx = ASContext.Context; - ClassModel curClass = ctx.CurrentClass; + var curClass = ctx.CurrentClass; curClass.ResolveExtends(); - Visibility acc = ctx.TypesAffinity(curClass, step.Type); + var acc = ctx.CodeComplete.TypesAffinity(context, curClass, step.Type); - // explore - bool inE4X = false; - string token = tokens[0]; - string path = token; - step.Path = token; + // explore + var inE4X = false; + var path = tokens[0]; + step.Path = path; step.Context = context; - for (int i=1; i classB -> classA), // restore the private, protected, and internal member references - if (curClass != null && curClass == step.Type) + if (curClass == step.Type) { // full visibility for this evaluation only - Visibility selfVisibility = acc | Visibility.Private | Visibility.Protected | Visibility.Internal; + var selfVisibility = acc | Visibility.Private | Visibility.Protected | Visibility.Internal; FindMember(token, resultClass, step, mask, selfVisibility); } - else - { - FindMember(token, resultClass, step, mask, acc); - } + else FindMember(token, resultClass, step, mask, filterVisibility ? acc : 0); // Haxe modules - if (step.Type == null && features.hasModules) + if (step.Type is null && features.hasModules) { foreach(ClassModel oClass in resultClass.InFile.Classes) if (oClass.Name == token) @@ -2428,14 +2726,14 @@ static ASResult EvalTail(ASExpr context, FileModel inFile, ASResult head, string } // handle E4X expressions - if (step.Type == null) + if (step.Type is null) { if (inE4X || (ctx.Features.hasE4X && IsXmlType(resultClass))) { inE4X = false; step = new ASResult(); step.Member = new MemberModel(token, "XMLList", FlagType.Variable | FlagType.Dynamic | FlagType.AutomaticVar, Visibility.Public); - step.Type = ctx.ResolveType("XMLList", null); + step.Type = ResolveType("XMLList", null); step.Context = context; step.Path = path; } @@ -2445,13 +2743,10 @@ static ASResult EvalTail(ASExpr context, FileModel inFile, ASResult head, string } else inE4X = false; - if (!step.IsStatic) + if (!step.IsStatic && (mask & FlagType.Static) > 0) { - if ((mask & FlagType.Static) > 0) - { - mask -= FlagType.Static; - mask |= FlagType.Dynamic; - } + mask -= FlagType.Static; + mask |= FlagType.Dynamic; } } else @@ -2462,337 +2757,294 @@ static ASResult EvalTail(ASExpr context, FileModel inFile, ASResult head, string step.Type = null; return step; } - } - return step; - } - - private static bool IsStatic(MemberModel member) - { - return member != null && (member.Flags & FlagType.Static) > 0; + } + return step; } - /// - /// Find variable type in function context - /// - /// Variable name - /// Completion context + static bool IsStatic(MemberModel member) => member != null && (member.Flags & FlagType.Static) > 0; + + /// + /// Find variable type in function context + /// + /// Variable name + /// Completion context /// File context - /// Class context - /// Class/member struct - static private ASResult EvalVariable(string token, ASExpr local, FileModel inFile, ClassModel inClass) - { - ASResult result = new ASResult(); - IASContext context = ASContext.Context; + /// Class context + /// Class/member struct + static ASResult EvalVariable(string token, ASExpr local, FileModel inFile, ClassModel inClass) + { + var result = new ASResult(); + if (local.coma == ComaExpression.AnonymousObjectParam) return result; + var ctx = ASContext.Context; if (!inClass.IsVoid()) inFile = inClass.InFile; - int p = token.IndexOf('('); + var p = token.IndexOf('('); if (p > 0) token = token.Substring(0, p); // top-level elements resolution - context.ResolveTopLevelElement(token, result); + ctx.ResolveTopLevelElement(token, result); if (!result.IsNull()) { if (result.Member != null && (result.Member.Flags & FlagType.Function) > 0 && p < 0) result.Type = ResolveType("Function", null); return result; } - - // local vars - if (local.LocalVars != null) + var features = ctx.Features; + if (!inClass.IsVoid() && !string.IsNullOrEmpty(features.ConstructorKey) && token == features.ConstructorKey && local.BeforeBody) + return EvalVariable(inClass.Name, local, inFile, inClass); + if (local.Separator != ":") { - // Haxe 3 get/set keyword in properties declaration - if ((token == "set" || token == "get") && local.ContextFunction == null - && local.ContextMember != null && local.ContextMember.Parameters != null && local.ContextMember.Parameters.Count == 2) - { - if (token == "get" && local.ContextMember.Parameters[0].Name == "get") return EvalVariable("get_" + local.ContextMember.Name, local, inFile, inClass); - if (token == "set" && local.ContextMember.Parameters[1].Name == "set") return EvalVariable("set_" + local.ContextMember.Name, local, inFile, inClass); - } - - foreach (MemberModel var in local.LocalVars) + var contextMember = local.ContextMember; + if (contextMember is null + || (contextMember.Flags & (FlagType.Getter | FlagType.Setter)) > 0 + || local.coma != ComaExpression.None + || local.WordBefore != features.functionKey) { - if (var.Name == token) + // local vars + if (local.LocalVars != null) { - result.Member = var; - result.InFile = inFile; - result.InClass = inClass; - if (var.Type == null && (var.Flags & FlagType.LocalVar) > 0 - && context.Features.hasInference /*&& !context.Features.externalCompletion*/) - InferVariableType(local, var); - - if ((var.Flags & FlagType.Function) > 0) - result.Type = ResolveType("Function", null); - else - result.Type = ResolveType(var.Type, inFile); - - return result; + // Haxe 3 get/set keyword in properties declaration + if ((token == "set" || token == "get") && local.ContextFunction is null && contextMember?.Parameters != null && contextMember.Parameters.Count == 2) + { + if (token == "get" && contextMember.Parameters[0].Name == "get") return EvalVariable("get_" + contextMember.Name, local, inFile, inClass); + if (token == "set" && contextMember.Parameters[1].Name == "set") return EvalVariable("set_" + contextMember.Name, local, inFile, inClass); + } + if (local.LocalVars.Count > 0) + { + var vars = local.LocalVars.Where(it => it.Name == token).ToList(); + if (vars.Count > 0) + { + MemberModel var = null; + if (vars.Count > 1) + { + vars.Sort((l, r) => r.LineFrom.CompareTo(l.LineFrom)); + var = vars.FirstOrDefault(it => it.LineTo < local.LineTo); + } + var ??= vars.FirstOrDefault(); + if (var != null) + { + result.Member = var; + result.InFile = inFile; + result.InClass = inClass; + if (features.hasInference && (var.Type is null || ResolveType(var.Type, inFile).IsVoid())) + { + if (var.Flags.HasFlag(FlagType.Variable)) ctx.CodeComplete.InferType(PluginBase.MainForm.CurrentDocument?.SciControl, local, var); + } + if (string.IsNullOrEmpty(var.Type)) result.Type = ResolveType(features.objectKey, null); + else if (var.Flags.HasFlag(FlagType.Function)) result.Type = ResolveType("Function", null); + else result.Type = ResolveType(var.Type, inFile); + return result; + } + } + } + } + // method parameters + if (local.ContextFunction?.Parameters != null) + { + foreach (var para in local.ContextFunction.Parameters) + if (para.Name == token || (para.Name[0] == '?' && para.Name.Substring(1) == token)) + { + result.Member = para; + result.Type = ResolveType(para.Type, inFile); + return result; + } } } } - // method parameters - if (local.ContextFunction != null && local.ContextFunction.Parameters != null) - { - foreach(MemberModel para in local.ContextFunction.Parameters) - if (para.Name == token || (para.Name[0] == '?' && para.Name.Substring(1) == token)) - { - result.Member = para; - result.Type = ResolveType(para.Type, inFile); - return result; - } - } - - // class members + // class members if (!inClass.IsVoid()) { FindMember(token, inClass, result, 0, 0); if (!result.IsNull()) + { + if (features.hasInference && result.Member is {Type: null} member) + { + ctx.CodeComplete.InferType(PluginBase.MainForm.CurrentDocument?.SciControl, local, member); + if (member.Type != null) result.Type = ResolveType(member.Type, inFile); + } return result; + } } + // file member if (inFile.Version != 2 || inClass.IsVoid()) { - // file member FindMember(token, inFile, result, 0, 0); - if (!result.IsNull()) - return result; + if (!result.IsNull()) return result; + } + // current file types + foreach(var aClass in inFile.Classes) + { + if (aClass.Name != token || (ctx.InPrivateSection && aClass.Access != Visibility.Private)) continue; + result.Type = aClass; + result.IsStatic = p < 0; + return result; } - - // current file types - foreach(ClassModel aClass in inFile.Classes) - if (aClass.Name == token) - { - if (!context.InPrivateSection || aClass.Access == Visibility.Private) - { - result.Type = aClass; - result.IsStatic = (p < 0); - return result; - } - } - // visible types & declarations - var visible = context.GetVisibleExternalElements(); - foreach (MemberModel aDecl in visible) + var list = ctx.GetVisibleExternalElements(); + foreach (var aDecl in list) { - if (aDecl.Name == token) + if (aDecl.Name != token) continue; + if ((aDecl.Flags & FlagType.Package) > 0) { - if ((aDecl.Flags & FlagType.Package) > 0) - { - FileModel package = context.ResolvePackage(token, false); - if (package != null) - { - result.InFile = package; - result.IsPackage = true; - result.IsStatic = true; - return result; - } - } - else if ((aDecl.Flags & (FlagType.Class | FlagType.Enum)) > 0) + var package = ctx.ResolvePackage(token, false); + if (package != null) { - ClassModel friendClass = null; - if (aDecl.InFile != null) - { - foreach(ClassModel aClass in aDecl.InFile.Classes) - if (aClass.Name == token) - { - friendClass = aClass; - break; - } - } - if (friendClass == null) friendClass = context.ResolveType(aDecl.Type, inFile); - - if (!friendClass.IsVoid()) - { - result.Type = friendClass; - result.IsStatic = (p < 0); - return result; - } - } - else if ((aDecl.Flags & FlagType.Function) > 0) - { - result.Member = aDecl; - result.RelClass = ClassModel.VoidClass; - result.InClass = ClassModel.VoidClass; - result.Type = (p < 0) - ? context.ResolveType("Function", null) - : context.ResolveType(aDecl.Type, aDecl.InFile); - result.InFile = aDecl.InFile; + result.InFile = package; + result.IsPackage = true; + result.IsStatic = true; return result; } } - } - - // types & imports - /*MemberList imports = context.ResolveImports(inFile); - foreach (MemberModel item in imports) - if (item.Name == token) + else if ((aDecl.Flags & (FlagType.Class | FlagType.Enum)) > 0) { - if (item is ClassModel) - { - result.Type = item as ClassModel; - result.IsStatic = (p < 0); - } - else if ((item.Flags & FlagType.Class) > 0) + ClassModel friendClass = null; + if (aDecl.InFile != null) { - result.Type = context.ResolveType(item.Type, null); - result.IsStatic = (p < 0); - return result; + foreach(var aClass in aDecl.InFile.Classes) + if (aClass.Name == token) + { + friendClass = aClass; + break; + } } - else + friendClass ??= ResolveType(aDecl.Type, inFile); + if (!friendClass.IsVoid()) { - result.Member = item; - result.RelClass = ClassModel.VoidClass; - result.InClass = ClassModel.VoidClass; - result.Type = (p < 0 && (item.Flags & FlagType.Function) > 0) - ? context.ResolveType("Function", null) - : context.ResolveType(item.Type, item.InFile); - result.InFile = item.InFile; + result.Type = friendClass; + result.IsStatic = p < 0; return result; } - }*/ - - /*if (context.Features.hasPackages) - { - if (inFile.Package.Length > 0) + } + else if ((aDecl.Flags & FlagType.Function) > 0) { - FindInPackage(token, inFile, inFile.Package, result); - if (!result.IsNull()) return result; + result.Member = aDecl; + result.RelClass = ClassModel.VoidClass; + result.InClass = FindClassOf(aDecl); + result.Type = (p < 0) + ? ResolveType("Function", null) + : ResolveType(aDecl.Type, aDecl.InFile); + result.InFile = aDecl.InFile; + return result; } - - FindInPackage(token, inFile, null, result); - if (!result.IsNull()) return result; - }*/ - - // toplevel types - /*ClassModel topClass = context.ResolveType(token, null); - if (!topClass.IsVoid()) - { - result.Type = topClass; - if (p > 0) + else if ((aDecl.Flags & (FlagType.Variable | FlagType.Getter)) > 0) { - if (topClass.Constructor != null) - { - FindMember(topClass.Constructor, topClass, result, 0, 0); - if (!result.IsNull()) return result; - else - { - result.Member = null; - result.Type = topClass; - } - } + result.Member = aDecl; + result.RelClass = ClassModel.VoidClass; + result.InClass = FindClassOf(aDecl); + result.Type = ResolveType(aDecl.Type, aDecl.InFile); + result.InFile = aDecl.InFile; return result; } - else result.IsStatic = true; - }*/ - - // packages folders - /*FileModel package = context.ResolvePackage(token, false); - if (package != null) - { - result.InFile = package; - result.IsPackage = true; - result.IsStatic = true; - }*/ - - return result; - } + } + return result; + } - private static ClassModel ResolveType(string qname, FileModel inFile) + static ClassModel FindClassOf(MemberModel aDecl) { - IASContext context = ASContext.Context; - - if (inFile == null || inFile == context.CurrentModel) - foreach (MemberModel aDecl in context.GetVisibleExternalElements()) + if (aDecl.InFile is null) return ClassModel.VoidClass; + foreach (var aClass in aDecl.InFile.Classes) + { + if (aClass.Members.Any(member => member == aDecl)) { - if (aDecl.Name == qname || aDecl.Type == qname) - { - if (aDecl.InFile != null) - { - foreach (ClassModel aClass in aDecl.InFile.Classes) - if (aClass.Name == aDecl.Name) return aClass; - return context.GetModel(aDecl.InFile.Package, qname, inFile != null ? inFile.Package : null); - } - else return context.ResolveType(aDecl.Type, inFile); - } + return aClass; } - - return context.ResolveType(qname, inFile); + } + return ClassModel.VoidClass; } /// - /// Infer very simple cases: var foo = {expression} + /// Retrieves a class model from its name /// - private static void InferVariableType(ASExpr local, MemberModel var) + /// Class (short or full) name + /// Current file + /// A parsed class or an empty ClassModel if the class is not found + protected static ClassModel ResolveType(string cname, FileModel inFile) { - ScintillaControl sci = ASContext.CurSciControl; - if (sci == null || var.LineFrom >= sci.LineCount) - return; - // is it a simple affectation inference? - string text = sci.GetLine(var.LineFrom); - Regex reVar = new Regex("\\s*var\\s+" + var.Name + "\\s*=([^;]+)"); - Match m = reVar.Match(text); - if (m.Success && m.Groups[1].Length > 1) - { - int p = text.IndexOf(';'); - text = text.TrimEnd(); - if (p < 0) p = text.Length; - if (text.EndsWith("(")) p--; - // resolve expression - ASExpr expr = GetExpression(sci, sci.PositionFromLine(var.LineFrom) + p, true); - if (!string.IsNullOrEmpty(expr.Value)) - { - ASResult result = EvalExpression(expr.Value, expr, ASContext.Context.CurrentModel, ASContext.Context.CurrentClass, true, false); - if (!result.IsNull()) + if (cname is null) return ClassModel.VoidClass; + var ctx = ASContext.Context; + if (inFile is null || inFile == ctx.CurrentModel) + { + var isQualified = cname.Contains('.'); + foreach (var aDecl in ctx.GetVisibleExternalElements()) + { + if (aDecl.Name == cname || (isQualified && aDecl.Type == cname)) { - if (result.Member != null) - { - var.Type = result.Member.Type; - var.Flags |= FlagType.Inferred; - } - else if (result.Type != null && !result.Type.IsVoid()) - { - var.Type = result.Type.QualifiedName; - var.Flags |= FlagType.Inferred; - } + if (aDecl.InFile is null) return ctx.ResolveType(aDecl.Type, inFile); + return aDecl.InFile.Classes.FirstOrDefault(it => it.Name == aDecl.Name) + ?? ctx.GetModel(aDecl.InFile.Package, cname, inFile?.Package); } } } + return ctx.ResolveType(cname, inFile); } - private static void FindInPackage(string token, FileModel inFile, string pkg, ASResult result) - { - IASContext context = ASContext.Context; - int p = token.IndexOf('('); + public void InferType(ScintillaControl sci, MemberModel member) => InferType(sci, new ASExpr(), member); - FileModel inPackage = context.ResolvePackage(pkg, false); - if (inPackage != null) + protected virtual void InferType(ScintillaControl sci, ASExpr local, MemberModel member) + { + var lineStartPosition = sci.PositionFromLine(member.LineFrom); + var lineEndPosition = sci.LineEndPosition(member.LineFrom); + for (var i = lineStartPosition; i < lineEndPosition; i++) { - int pLen = pkg != null ? pkg.Length : 0; - foreach (MemberModel friend in inPackage.Imports) - { - if (friend.Name == token && (pLen == 0 || friend.Type.LastIndexOf(context.Features.dot) == pLen)) - { - ClassModel friendClass = context.GetModel(inFile.Package, token, inFile.Package); - if (!friendClass.IsVoid()) - { - result.Type = friendClass; - result.IsStatic = (p < 0); - return; - } - break; - } - } - foreach (MemberModel friend in inPackage.Members) + if (sci.PositionIsOnComment(i) || sci.PositionIsInString(i)) continue; + var c = (char) sci.CharAt(i); + if (c == '=' || c == ';') break; + if (c == '_' || c == ',' || c == '(' || c == ')') continue; + if (char.IsPunctuation(c)) return; + } + var text = sci.GetLine(member.LineFrom); + var m = Regex.Match(text, "=([^;]+)"); + if (!m.Success) return; + var rvalue = m.Groups[1]; + if (rvalue.Length == 0) return; + var offset = rvalue.Length - rvalue.Value.TrimStart().Length; + var rvalueStart = lineStartPosition + rvalue.Index + offset; + if (local.ContextFunction is {} function) + { + /** + * for example: + * function foo() { + * var expr = foo(); + * return expr; + * } + */ + var p = rvalueStart; + if (function.Name == GetWordRight(sci, ref p) && GetCharRight(sci, ref p) == '(') { - if (friend.Name == token) - { - result.Member = friend; - result.Type = (p < 0 && (friend.Flags & FlagType.Function) > 0) - ? context.ResolveType("Function", null) - : context.ResolveType(friend.Type, friend.InFile); - return; - } + // TODO slavara: trace possible stack overflow error + member.Type = function.Type ?? ASContext.Context.Features.voidKey; + member.Flags |= FlagType.Inferred; + return; } } - return; + InferVariableType(sci, text, rvalueStart, local, member); + } + + protected virtual void InferVariableType(ScintillaControl sci, string declarationLine, int rvalueStart, ASExpr local, MemberModel var) + { + if (!var.Flags.HasFlag(FlagType.Variable) && !var.Flags.HasFlag(FlagType.ParameterVar)) return; + var p = declarationLine.IndexOf(';'); + var text = declarationLine.TrimEnd(); + if (p < 0) p = text.Length; + if (text.EndsWith('(')) p--; + // resolve expression + var expr = GetExpression(sci, sci.PositionFromLine(var.LineFrom) + p, true); + if (string.IsNullOrEmpty(expr.Value)) return; + var ctx = ASContext.Context; + var result = EvalExpression(expr.Value, expr, ctx.CurrentModel, ctx.CurrentClass, true, false); + if (result.IsNull()) return; + if (result.Type != null && !result.Type.IsVoid()) + { + var.Type = result.Type.QualifiedName; + var.Flags |= FlagType.Inferred; + } + else if (result.Member != null) + { + var.Type = result.Member.Type; + if (string.IsNullOrEmpty(var.Type)) var.Type = ResolveType(ctx.Features.objectKey, null).Name; + var.Flags |= FlagType.Inferred; + } } /// @@ -2802,14 +3054,19 @@ private static void FindInPackage(string token, FileModel inFile, string pkg, AS /// In given file /// Class/Member struct /// Flags mask - /// Visibility mask - static public void FindMember(string token, FileModel inFile, ASResult result, FlagType mask, Visibility acc) + /// Visibility mask + public static void FindMember(string token, FileModel inFile, ASResult result, FlagType mask, Visibility access) + => ASContext.Context.CodeComplete.FindMemberEx(token, inFile, result, mask, access); + + protected virtual void FindMemberEx(string token, FileModel inFile, ASResult result, FlagType mask, Visibility access) { + if (string.IsNullOrEmpty(token)) return; + // package if (result.IsPackage) { - string fullName = (result.InFile.Package.Length > 0) ? result.InFile.Package + "." + token : token; - int p; + var ctx = ASContext.Context; + var fullName = (result.InFile.Package.Length > 0) ? result.InFile.Package + "." + token : token; foreach (MemberModel mPack in result.InFile.Imports) { if (mPack.Name == token) @@ -2817,7 +3074,7 @@ static public void FindMember(string token, FileModel inFile, ASResult result, F // sub-package if (mPack.Flags == FlagType.Package) { - FileModel package = ASContext.Context.ResolvePackage(fullName, false); + var package = ctx.ResolvePackage(fullName, false); if (package != null) result.InFile = package; else { @@ -2829,24 +3086,24 @@ static public void FindMember(string token, FileModel inFile, ASResult result, F else { result.IsPackage = false; - result.Type = ResolveType(fullName, ASContext.Context.CurrentModel); + result.Type = ResolveType(fullName, ctx.CurrentModel); result.InFile = result.Type.InFile; } return; } - else if ((p = mPack.Name.IndexOf('<')) > 0) + if (mPack.Name.Contains('<', out var p) && p > 0) { if (p > 1 && mPack.Name[p - 1] == '.') p--; if (mPack.Name.Substring(0, p) == token) { result.IsPackage = false; - result.Type = ResolveType(fullName + mPack.Name.Substring(p), ASContext.Context.CurrentModel); + result.Type = ResolveType(fullName + mPack.Name.Substring(p), ctx.CurrentModel); result.InFile = result.Type.InFile; return; } } } - foreach (MemberModel member in result.InFile.Members) + foreach (var member in result.InFile.Members) { if (member.Name == token) { @@ -2866,15 +3123,14 @@ static public void FindMember(string token, FileModel inFile, ASResult result, F return; } - MemberModel found; // variable - found = inFile.Members.Search(token, mask, acc); + var found = inFile.Members.Search(token, mask, access); // ignore setters if (found != null && (found.Flags & FlagType.Setter) > 0) { found = null; - MemberList matches = inFile.Members.MultipleSearch(token, mask, acc); - foreach (MemberModel member in matches) + var matches = inFile.Members.MultipleSearch(token, mask, access); + foreach (var member in matches) { found = member; if ((member.Flags & FlagType.Setter) == 0) break; @@ -2887,408 +3143,638 @@ static public void FindMember(string token, FileModel inFile, ASResult result, F result.Member = found; result.Type = ResolveType(found.Type, inFile); result.IsStatic = false; - return; } } - /// - /// Match token to a class' member - /// - /// To match - /// In given class - /// Class/Member struct + /// + /// Match token to a class' member + /// + /// To match + /// In given class + /// Class/Member struct /// Flags mask - /// Visibility mask - static public void FindMember(string token, ClassModel inClass, ASResult result, FlagType mask, Visibility acc) - { - if (token.Length == 0) - return; - - IASContext context = ASContext.Context; - ContextFeatures features = context.Features; - MemberModel found = null; - ClassModel tmpClass = inClass; + /// Visibility mask + public static void FindMember(string token, ClassModel inClass, ASResult result, FlagType mask, Visibility access) + => ASContext.Context.CodeComplete.FindMemberEx(token, inClass, result, mask, access); - if (inClass == null) + protected virtual void FindMemberEx(string token, ClassModel inClass, ASResult result, FlagType mask, Visibility access) + { + if (string.IsNullOrEmpty(token)) return; + if (inClass is null) { - if (result.InFile != null) FindMember(token, result.InFile, result, mask, acc); + if (result.InFile != null) FindMember(token, result.InFile, result, mask, access); return; } - else result.RelClass = inClass; + var features = ASContext.Context.Features; + result.RelClass = inClass; // previous member accessed as an array - if (token == "[]") + if (token.Length >= 2 && token[0] == '[' && token[token.Length - 1] == ']') { result.IsStatic = false; - if (result.Type == null || result.Type.IndexType == null) + if (result.Type?.IndexType is null) { result.Member = null; result.InFile = null; - result.Type = ResolveType(context.Features.objectKey, null); - } - else - { - result.Type = ResolveType(result.Type.IndexType, result.InFile); + result.Type = ResolveType(features.objectKey, null); } + else result.Type = ResolveType(result.Type.IndexType, result.InFile); return; } // previous member called as a method - else if (token[0] == '#') + if (token[0] == '#') { result.IsStatic = false; if (result.Member != null) { - if ((result.Member.Flags & FlagType.Constructor) > 0) - result.Type = inClass; - else result.Type = ResolveType(result.Member.Type, result.InFile); + result.Type = (result.Member.Flags & FlagType.Constructor) > 0 + ? inClass + : ResolveType(result.Member.Type, result.InFile); } return; } - // variable - else if (tmpClass != null) + // variable + MemberModel found = null; + // member + var tmpClass = inClass; + tmpClass.ResolveExtends(); + while (!tmpClass.IsVoid()) { - // member - tmpClass.ResolveExtends(); - while (!tmpClass.IsVoid()) + found = tmpClass.Members.Search(token, mask, access); + // ignore setters + if (found != null && (found.Flags & FlagType.Setter) > 0) { - found = tmpClass.Members.Search(token, mask, acc); - // ignore setters - if (found != null && (found.Flags & FlagType.Setter) > 0) + found = null; + var matches = tmpClass.Members.MultipleSearch(token, mask, access); + foreach (var member in matches) { - found = null; - MemberList matches = tmpClass.Members.MultipleSearch(token, mask, acc); - foreach (MemberModel member in matches) - { - found = member; - if ((member.Flags & FlagType.Getter) > 0) break; - } + found = member; + if ((member.Flags & FlagType.Getter) > 0) break; } - if (found != null) + } + if (found != null) + { + result.Member = found; + // variable / getter + if ((found.Flags & FlagType.Function) == 0) { - result.Member = found; - // variable / getter - if ((found.Flags & FlagType.Function) == 0) - { - result.Type = ResolveType(found.Type, tmpClass.InFile); - result.IsStatic = false; - } - // constructor - else if ((found.Flags & FlagType.Constructor) > 0) - { - // is the constructor - ie. a Type - if (tmpClass != inClass) // constructor of inherited type - { - found = null; - result.Type = null; - result.Member = null; - break; - } - result.Type = tmpClass; - result.IsStatic = true; - } - // in enum - else if ((found.Flags & FlagType.Enum) > 0) - { - result.Type = ResolveType(found.Type, tmpClass.InFile); - } - // method - else - { - result.Type = ResolveType("Function", null); - result.IsStatic = false; - } - break; + result.Type = ResolveType(found.Type, tmpClass.InFile); + result.IsStatic = false; } - // Flash IDE-like typing - else if (tmpClass.Name == "MovieClip") + // constructor + else if ((found.Flags & FlagType.Constructor) > 0) { - string autoType = null; - if (tmpClass.InFile.Version < 3) - { - if (token.EndsWith("_mc") || token.StartsWith("mc")) autoType = "MovieClip"; - else if (token.EndsWith("_txt") || token.StartsWith("txt")) autoType = "TextField"; - else if (token.EndsWith("_btn") || token.StartsWith("bt")) autoType = "Button"; - } - else if (tmpClass.InFile.Version == 3) - { - if (token.EndsWith("_mc") || token.StartsWith("mc")) autoType = "flash.display.MovieClip"; - else if (token.EndsWith("_txt") || token.StartsWith("txt")) autoType = "flash.text.TextField"; - else if (token.EndsWith("_btn") || token.StartsWith("bt")) autoType = "flash.display.SimpleButton"; - } - if (autoType != null) + // is the constructor - ie. a Type + if (tmpClass != inClass) // constructor of inherited type { - result.Type = ASContext.Context.ResolveType(autoType, null); - result.Member = new MemberModel(token, autoType, FlagType.Variable | FlagType.Dynamic | FlagType.AutomaticVar, Visibility.Public); - result.IsStatic = false; - return; + found = null; + result.Type = null; + result.Member = null; + break; } + result.Type = tmpClass; + result.IsStatic = true; } - - // static inheritance: only AS2 and Haxe typedefs inherit static members - if ((mask & FlagType.Static) > 0) + // in enum + else if ((found.Flags & FlagType.Enum) > 0) { - if (!features.hasStaticInheritance && (tmpClass.Flags & FlagType.TypeDef) == 0) - break; + result.Type = ResolveType(found.Type, tmpClass.InFile); } - - tmpClass = tmpClass.Extends; - - if (acc == 0 && !tmpClass.IsVoid() && tmpClass.InFile.Version == 3) + // method + else { - acc = Visibility.Public | Visibility.Protected; - if (inClass.InFile.Package == tmpClass.InFile.Package) acc |= Visibility.Internal; + result.Type = ResolveType("Function", null); + result.IsStatic = false; } + break; } - } - - // result found! - if (found != null) - { + // Flash IDE-like typing + if (tmpClass.Name == "MovieClip") + { + string autoType = null; + if (tmpClass.InFile.Version < 3) + { + if (token.EndsWithOrdinal("_mc") || token.StartsWithOrdinal("mc")) autoType = "MovieClip"; + else if (token.EndsWithOrdinal("_txt") || token.StartsWithOrdinal("txt")) autoType = "TextField"; + else if (token.EndsWithOrdinal("_btn") || token.StartsWithOrdinal("bt")) autoType = "Button"; + } + else if (tmpClass.InFile.Version == 3) + { + if (token.EndsWithOrdinal("_mc") || token.StartsWithOrdinal("mc")) + autoType = "flash.display.MovieClip"; + else if (token.EndsWithOrdinal("_txt") || token.StartsWithOrdinal("txt")) + autoType = "flash.text.TextField"; + else if (token.EndsWithOrdinal("_btn") || token.StartsWithOrdinal("bt")) + autoType = "flash.display.SimpleButton"; + } + if (autoType != null) + { + result.Type = ResolveType(autoType, null); + result.Member = new MemberModel(token, autoType, FlagType.Variable | FlagType.Dynamic | FlagType.AutomaticVar, Visibility.Public); + result.IsStatic = false; + return; + } + } + // static inheritance: only AS2 and Haxe typedefs inherit static members + if ((mask & FlagType.Static) > 0) + { + if (!features.hasStaticInheritance && (tmpClass.Flags & FlagType.TypeDef) == 0) + break; + } + tmpClass = tmpClass.Extends; + if (access == 0 && !tmpClass.IsVoid() && tmpClass.InFile.Version == 3) + { + access = Visibility.Public | Visibility.Protected; + if (inClass.InFile.Package == tmpClass.InFile.Package) access |= Visibility.Internal; + } + } + // result found! + if (found != null) + { result.InClass = tmpClass; result.InFile = tmpClass.InFile; - if (result.Type == null) - result.Type = ASContext.Context.ResolveType(found.Type, tmpClass.InFile); - return; - } - // try subpackages - else if (inClass.InFile.TryAsPackage) - { - result.Type = ASContext.Context.ResolveType(inClass.Name + "." + token, null); - if (!result.Type.IsVoid()) - return; - } - - // not found - result.Type = null; - result.Member = null; - } - - #endregion - - #region main_code_parser - static private List ExtractedSubex; + result.Type ??= ResolveType(found.Type, tmpClass.InFile); + return; + } + // try subpackages + if (inClass.InFile.TryAsPackage) + { + result.Type = ResolveType(inClass.Name + "." + token, null); + if (!result.Type.IsVoid()) return; + } + // not found + result.Type = null; + result.Member = null; + } + + public static MemberModel FindMember(string name, ClassModel inClass) + { + var list = inClass == ClassModel.VoidClass + ? ASContext.Context.CurrentModel.Members + : inClass.Members; + + return list.FirstOrDefault(member => member.Name == name); + } + + public static T FindMember(int line, IEnumerable list) where T : MemberModel + => list.FirstOrDefault(it => it.LineFrom <= line && it.LineTo >= line); + + #endregion + + #region main_code_parser + + static List ExtractedSubex; /// - /// Find Actionscript expression at cursor position + /// Find expression at cursor position /// /// Scintilla Control /// Cursor position /// - static private ASExpr GetExpression(ScintillaControl Sci, int position) - { - return GetExpression(Sci, position, false); - } + internal static ASExpr GetExpression(ScintillaControl sci, int position) => GetExpression(sci, position, false); + + /// + /// Find expression at cursor position + /// + /// Scintilla Control + /// Cursor position + /// Skip whitespace at position + /// + protected static ASExpr GetExpression(ScintillaControl sci, int position, bool ignoreWhiteSpace) + => ASContext.Context.CodeComplete.GetExpressionEx(sci, position, ignoreWhiteSpace); - /// - /// Find Actionscript expression at cursor position - /// - /// Scintilla Control - /// Cursor position + /// + /// Find expression at cursor position + /// + /// Scintilla Control + /// Cursor position /// Skip whitespace at position - /// - static private ASExpr GetExpression(ScintillaControl Sci, int position, bool ignoreWhiteSpace) - { - bool haXe = ASContext.Context.CurrentModel.haXe; - ASExpr expression = new ASExpr(); - expression.Position = position; - expression.Separator = ' '; + /// + protected virtual ASExpr GetExpressionEx(ScintillaControl sci, int position, bool ignoreWhiteSpace) + { + var ctx = ASContext.Context; + var haXe = ctx.CurrentModel.haXe; + var expression = new ASExpr {Position = position, Separator = " "}; + var minPos = 0; // file's member declared at this position - expression.ContextMember = ASContext.Context.CurrentMember; - int minPos = 0; - string body = null; - if (expression.ContextMember != null) - { - minPos = Sci.PositionFromLine(expression.ContextMember.LineFrom); - StringBuilder sbBody = new StringBuilder(); - for (int i = expression.ContextMember.LineFrom; i <= expression.ContextMember.LineTo; i++) - sbBody.Append(Sci.GetLine(i)).Append('\n'); - body = sbBody.ToString(); - //int tokPos = body.IndexOf(expression.ContextMember.Name); - //if (tokPos >= 0) minPos += tokPos + expression.ContextMember.Name.Length; - + MemberModel contextMember = null; + var currentLine = sci.LineFromPosition(position); + if (sci.FileName != ctx.CurrentFile) + { + var model = ctx.GetFileModel(sci.FileName); + if (FindMember(currentLine, model.Classes) is { } contextClass) + contextMember = FindMember(currentLine, contextClass.Members); + contextMember ??= FindMember(currentLine, model.Members); + } + else contextMember = FindMember(currentLine, ctx.CurrentClass.Members); + if (contextMember != null) + { + expression.ContextMember = contextMember; + minPos = sci.PositionFromLine(contextMember.LineFrom); + var body = sci.GetTextRange(minPos, sci.PositionFromLine(contextMember.LineTo + 1)); var hasBody = FlagType.Function | FlagType.Constructor; if (!haXe) hasBody |= FlagType.Getter | FlagType.Setter; - - if ((expression.ContextMember.Flags & hasBody) > 0) + if (!contextMember.Flags.HasFlag(FlagType.Variable) && (contextMember.Flags & hasBody) > 0) { - expression.ContextFunction = expression.ContextMember; - expression.FunctionOffset = expression.ContextMember.LineFrom; - - Match mStart = Regex.Match(body, "(\\)|[a-z0-9*.,-<>])\\s*{", RegexOptions.IgnoreCase); - if (mStart.Success) + expression.ContextFunction = contextMember; + expression.FunctionOffset = contextMember.LineFrom; + var m = Regex.Match(body, "(\\)|[a-z0-9*.,-<>])\\s*{", RegexOptions.IgnoreCase); + if (m.Success) { // cleanup function body & offset - int pos = mStart.Index + mStart.Length - 1; - expression.BeforeBody = (position < Sci.PositionFromLine(expression.ContextMember.LineFrom) + pos); - string pre = body.Substring(0, pos); - for (int i = 0; i < pre.Length - 1; i++) - if (pre[i] == '\r') { expression.FunctionOffset++; if (pre[i + 1] == '\n') i++; } + var pos = m.Index + m.Length - 1; + expression.BeforeBody = (position < minPos + pos); + var pre = body.Substring(0, pos); + for (var i = 0; i < pre.Length - 1; i++) + if (pre[i] == '\r') + { + expression.FunctionOffset++; + if (pre[i + 1] == '\n') i++; + } else if (pre[i] == '\n') expression.FunctionOffset++; + body = body.Substring(pos); } expression.FunctionBody = body; } else { - int eqPos = body.IndexOf('='); - expression.BeforeBody = (eqPos < 0 || position < Sci.PositionFromLine(expression.ContextMember.LineFrom) + eqPos); + var eqPos = body.IndexOf('='); + expression.BeforeBody = (eqPos < 0 || position < minPos + eqPos); } } // get the word characters from the syntax definition - string characterClass = ScintillaControl.Configuration.GetLanguage(Sci.ConfigurationLanguage).characterclass.Characters; + var characterClass = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage).characterclass.Characters; // get expression before cursor - ContextFeatures features = ASContext.Context.Features; - int stylemask = (1 << Sci.StyleBits) -1; - int style = (position >= minPos) ? Sci.StyleAt(position) & stylemask : 0; - StringBuilder sb = new StringBuilder(); - StringBuilder sbSub = new StringBuilder(); - int subCount = 0; - char c = ' '; - char c2; - int startPos = position; - int braceCount = 0; - int sqCount = 0; - int genCount = 0; - bool hasGenerics = features.hasGenerics; - bool hadWS = false; - bool hadDot = ignoreWhiteSpace; - int dotCount = 0; - bool inRegex = false; - char dot = features.dot[features.dot.Length-1]; + var features = ctx.Features; + var sb = new StringBuilder(); + var sbSub = new StringBuilder(); + var subCount = 0; + var c = ' '; + var startPosition = position; + var positionExpression = position; + var arrCount = 0; + var parCount = 0; + var genCount = 0; + var braCount = 0; + var dQuotes = 0; + var sQuotes = 0; + var hasGenerics = features.hasGenerics; + var hadWS = false; + var hadDot = ignoreWhiteSpace; + var dotCount = 0; + var inRegex = false; + var dot = features.dot[features.dot.Length - 1]; while (position > minPos) { position--; - style = Sci.StyleAt(position) & stylemask; - if (style == 14) // regex literal + if (arrCount == 0 && braCount == 0 && parCount == 0 && ctx.CodeComplete.IsRegexStyle(sci, position)) { - if (hadDot) inRegex = true; - else break; + inRegex = true; + positionExpression = position; + continue; } - else if (!IsCommentStyle(style)) + var style = sci.BaseStyleAt(position); + if (!IsCommentStyle(style)) { - c2 = c; - c = (char)Sci.CharAt(position); // end of regex literal if (inRegex) { - inRegex = false; - if (expression.SubExpressions == null) expression.SubExpressions = new List(); + if (expression.SubExpressions is null) + { + expression.SubExpressions = new List(); + expression.SubExpressionPositions = new List(); + } expression.SubExpressions.Add(""); - sb.Insert(0, "RegExp.#" + (subCount++) + "~"); + expression.SubExpressionPositions.Add(position + 1); + sb.Insert(0, "#RegExp.#" + (subCount++) + "~"); + expression.Separator = ";"; + break; + } + var c2 = c; + c = (char)sci.CharAt(position); + if ((dQuotes > 0 && c != '\"') || (sQuotes > 0 && c != '\'')) + { + sbSub.Insert(0, c); + continue; } + if (arrCount == 0 && braCount == 0 && parCount == 0 + && dQuotes == 0 && sQuotes == 0 + && c != '\"' && c != '\'' + && (IsStringStyle(style) || IsCharStyle(style)) + && !IsStringInterpolationStyle(sci, position)) break; // array access - if (c == '[') + if (c == ']') { - sqCount--; - if (sqCount == 0) + if (parCount == 0) { - if (sbSub.Length > 0) sbSub.Insert(0, '['); - if (braceCount == 0) sb.Insert(0, ".[]"); - continue; - } - if (sqCount < 0) + /** + * for example: + * var v = [] + * v. + */ + if (!hadDot && sb.Length > 0 && characterClass.Contains(sb[0])) + { + expression.Separator = ";"; + break; + } + ignoreWhiteSpace = false; + if (arrCount == 0) // start sub-expression + { + if (expression.SubExpressions is null) + { + expression.SubExpressions = new List(); + expression.SubExpressionPositions = new List(); + } + sbSub.Clear(); + } + arrCount++; + } + } + else if (c == '[') + { + if (parCount == 0) { - expression.Separator = ';'; - break; + arrCount--; + if (arrCount == 0 && braCount == 0) + { + positionExpression = position; + sbSub.Insert(0, c); + expression.SubExpressions.Add(sbSub.ToString()); + expression.SubExpressionPositions.Add(position + 1); + sbSub.Clear(); + sb.Insert(0, ".#" + (subCount++) + "~"); + var pos = position - 1; + var word = GetWordLeft(sci, ref pos); + // for example: return []. + if (word.Length > 0 && features.codeKeywords.Contains(word)) + { + expression.Separator = ";"; + expression.WordBefore = word; + expression.WordBeforePosition = pos + 1; + break; + } + continue; + } + if (arrCount < 0) + { + expression.Separator = ";"; + break; + } } } - else if (c == ']') + else if (c == '<') { - sqCount++; + if (hasGenerics && arrCount == 0 && parCount == 0) + { + genCount--; + if (genCount < 0) + { + expression.Separator = ";"; + break; + } + } } - // - else if (c == '<' && hasGenerics) + else if (c == '>') { - genCount--; - if (genCount < 0) + if (arrCount == 0 && parCount == 0) { - expression.Separator = ';'; - break; + // for example: -> + if (haXe && position - 1 > minPos && (char)sci.CharAt(position - 1) == '-') + { + } + else if (hasGenerics) + { + if (c2 == '.' || c2 == ',' || c2 == '(' || c2 == '[' || c2 == '>' || c2 == '}' || c2 == ')' || position + 1 == startPosition) + { + genCount++; + var length = sb.Length; + if (length >= 3) + { + var fc = sb[0]; + var sc = sb[1]; + var lc = sb[length - 1]; + if (fc == '.' && sc == '[' && (lc == ']' || (length >= 4 && sb[length - 2] == ']' && lc == '.'))) + { + sbSub.Insert(0, sb.ToString(1, length - 1)); + sb.Clear(); + } + } + } + else break; + } } } // ignore sub-expressions (method calls' parameters) else if (c == '(') { - braceCount--; - if (braceCount == 0) + if (arrCount == 0) { - int testPos = position - 1; - string testWord = GetWordLeft(Sci, ref testPos); - - sbSub.Insert(0, c); - if (haXe && testWord == "cast") expression.SubExpressions.Add("cast"); - expression.SubExpressions.Add(sbSub.ToString()); - sb.Insert(0, ".#" + (subCount++) + "~"); // method call or sub expression - - if (testWord == "return" || testWord == "case" || testWord == "defaut" || (haXe && testWord == "cast")) + parCount--; + if (parCount == 0) { + positionExpression = position; + sbSub.Insert(0, c); + expression.SubExpressions.Add(sbSub.ToString()); + expression.SubExpressionPositions.Add(position + 1); + sbSub.Clear(); + sb.Insert(0, ".#" + (subCount++) + "~"); // method call or sub expression + var pos = position - 1; + var word = GetWordLeft(sci, ref pos); // AS3, AS2, Loom ex: return (a as B). - // Haxe ex: return cast(a, B). - expression.Separator = ';'; - expression.WordBefore = testWord; + if (word.Length > 0 && word != "new" && word != "trace" && features.codeKeywords.Contains(word)) + { + expression.Separator = ";"; + expression.WordBefore = word; + expression.WordBeforePosition = pos + 1; + break; + } + continue; + } + if (parCount < 0) + { + expression.Separator = ";"; + var testPos = position - 1; + var testWord = GetWordLeft(sci, ref testPos); // anonymous function + var testWord2 = GetWordLeft(sci, testPos); // regular function + if (testWord == features.functionKey + || testWord == "catch" + || testWord2 == features.functionKey + || testWord2 == features.getKey + || testWord2 == features.setKey) + { + expression.Separator = ","; + expression.coma = ComaExpression.FunctionDeclaration; + } + else + { + expression.WordBefore = testWord; + expression.WordBeforePosition = testPos + 1; + } break; } - else continue; } - else if (braceCount < 0) + } + else if (c == ')') + { + if (arrCount == 0) { - expression.Separator = ';'; - int testPos = position - 1; - string testWord = GetWordLeft(Sci, ref testPos); // anonymous function - string testWord2 = GetWordLeft(Sci, ref testPos) ?? "null"; // regular function - if (testWord == features.functionKey || testWord == "catch" - || testWord2 == features.functionKey - || testWord2 == features.getKey || testWord2 == features.setKey) + ignoreWhiteSpace = false; + if (!hadDot) { - expression.Separator = ','; - expression.coma = ComaExpression.FunctionDeclaration; + expression.Separator = ";"; + break; } - else expression.WordBefore = testWord; - break; + if (parCount == 0) // start sub-expression + { + if (expression.SubExpressions is null) + { + expression.SubExpressions = new List(); + expression.SubExpressionPositions = new List(); + } + sbSub.Clear(); + } + parCount++; } } - else if (c == ')') + else if (genCount == 0 && arrCount == 0 && parCount == 0) { - if (!hadDot) + if (c == '}') { - expression.Separator = ';'; - break; + /** + * for example: + * var v = {} + * v. + */ + if (!hadDot && sb.Length > 0 && characterClass.Contains(sb[0])) + { + expression.Separator = ";"; + break; + } + if (!ignoreWhiteSpace && hadWS) + { + expression.Separator = ";"; + break; + } + braCount++; } - if (braceCount == 0) // start sub-expression + else if (c == '{') { - if (expression.SubExpressions == null) expression.SubExpressions = new List(); - sbSub = new StringBuilder(); + braCount--; + if (braCount == 0) + { + positionExpression = position; + sb.Insert(0, "{}"); + expression.Separator = ";"; + continue; + } + if (braCount < 0) + { + expression.Separator = ";"; + break; + } } - braceCount++; - } - else if (c == '>' && hasGenerics) - { - if (c2 == '.' || c2 == '(') - genCount++; - else break; - } - if (braceCount > 0 || sqCount > 0 || genCount > 0) - { - if (c == ';') // not expected: something's wrong + else if (braCount == 0) { - expression.Separator = ';'; - break; + if (c == '\"' && sQuotes == 0) + { + if (position == 0 || (char)sci.CharAt(position - 1) == '\\') continue; + if (dQuotes == 0) dQuotes++; + else + { + dQuotes--; + if (dQuotes == 0) + { + positionExpression = position; + expression.Separator = ";"; + if (expression.SubExpressions != null) + { + sbSub.Insert(0, c); + sb.Insert(0, sbSub.ToString()); + break; + } + sb.Insert(0, string.Concat(c, sbSub, c)); + continue; + } + } + if (hadDot) + { + sbSub.Clear(); + sbSub.Insert(0, c); + if (expression.SubExpressions is null) + { + expression.SubExpressions = new List(); + expression.SubExpressionPositions = new List(); + } + expression.SubExpressions.Add(string.Empty); + expression.SubExpressionPositions.Add(position + 1); + sb.Insert(0, ".#" + (subCount++) + "~"); + } + ignoreWhiteSpace = false; + continue; + } + if (c == '\'' && dQuotes == 0) + { + if (position == 0 || (char)sci.CharAt(position - 1) == '\\') continue; + if (sQuotes == 0) sQuotes++; + else + { + sQuotes--; + if (sQuotes == 0) + { + positionExpression = position; + expression.Separator = ";"; + if (expression.SubExpressions != null) + { + sbSub.Insert(0, c); + sb.Insert(0, sbSub.ToString()); + break; + } + sb.Insert(0, string.Concat(c, sbSub, c)); + continue; + } + } + if (hadDot) + { + sbSub.Clear(); + sbSub.Insert(0, c); + if (expression.SubExpressions is null) + { + expression.SubExpressions = new List(); + expression.SubExpressionPositions = new List(); + } + expression.SubExpressions.Add(string.Empty); + expression.SubExpressionPositions.Add(position + 1); + sb.Insert(0, ".#" + (subCount++) + "~"); + } + ignoreWhiteSpace = false; + continue; + } } + } + if (parCount > 0 || arrCount > 0 || genCount > 0 || braCount > 0) + { // build sub expression sbSub.Insert(0, c); continue; } // build expression - if (c <= 32) + if (c <= ' ') { if (genCount == 0) hadWS = true; + else + { + sb.Insert(sb.Length, sbSub.ToString().ToCharArray()); + positionExpression = position + 1; + expression.Separator = " "; + break; + } } else if (c == dot) { - if (features.dot.Length == 2) - hadDot = position > 0 && Sci.CharAt(position - 1) == features.dot[0]; + if (features.dot.Length == 2) hadDot = position > 0 && sci.CharAt(position - 1) == features.dot[0]; else { hadDot = true; @@ -3300,139 +3786,241 @@ static private ASExpr GetExpression(ScintillaControl Sci, int position, bool ign } sb.Insert(0, c); } - else if (characterClass.IndexOf(c) >= 0) - { - if (hadWS && !hadDot) - { - expression.Separator = ' '; - break; - } - hadWS = false; - hadDot = false; - dotCount = 0; - sb.Insert(0, c); - startPos = position; - } else if (c == ';') { - expression.Separator = ';'; + if(expression.Separator == " ") expression.Separator = ";"; break; } - else if (hasGenerics && (genCount > 0 || c == '<')) + else if (c == '<' && hasGenerics) { - sb.Insert(0, c); + sbSub.Insert(0, c); + if (genCount < 0 + && sci.ConfigurationLanguage == "as3" + && position > minPos && sci.CharAt(position - 1) != '.') + { + positionExpression = position; + position--; + expression.Separator = " "; + break; + } + genCount--; + sb.Insert(0, sbSub); + sbSub.Clear(); } else if (c == '{') { - expression.coma = DisambiguateComa(Sci, position, minPos); - expression.Separator = (expression.coma == ComaExpression.None) ? ';' : ','; + expression.coma = DisambiguateComa(sci, position, minPos); + if (expression.Separator == " ") expression.Separator = (expression.coma == ComaExpression.None) ? ";" : ","; + if (expression.coma == ComaExpression.AnonymousObjectParam) + { + positionExpression = position; + sb.Append(c); + braCount++; + position++; + var endPos = sci.LineEndPosition(expression.ContextFunction?.LineTo ?? expression.ContextMember.LineTo); + while (position < endPos) + { + style = sci.BaseStyleAt(position); + if (!IsCommentStyle(style)) + { + c = (char) sci.CharAt(position); + sb.Append(c); + if (c == '}') + { + if (--braCount == 0) break; + } + else if (c == '{') braCount++; + } + position++; + } + } break; } else if (c == ',') { - expression.coma = DisambiguateComa(Sci, position, minPos); - expression.Separator = (expression.coma == ComaExpression.None) ? ';' : ','; + expression.coma = DisambiguateComa(sci, position, minPos); + expression.Separator = ","; + expression.SeparatorPosition = position; break; } else if (c == ':') { - expression.Separator = ':'; + expression.Separator = ":"; + expression.SeparatorPosition = position; break; } - else if (c == '=') + else if (features.ArithmeticOperators.Contains(c)) { - expression.Separator = '='; - break; + var p = position - 1; + // for example: 5e-324, 1.79e+308 + if ((c == '-' || c == '+') && p > minPos && sci.CharAt(p) == 'e') + { + sb.Insert(0, c); + continue; + } + expression.SeparatorPosition = position; + var curOp = c.ToString(); + foreach (var op in features.IncrementDecrementOperators) + { + while (op.StartsWithOrdinal(curOp) && p > minPos) + { + var cc = (char)sci.CharAt(p); + if (cc == c) curOp += cc; + else break; + p--; + } + if (curOp.Length > 1) + { + var buf = string.Empty; + while (p > minPos) + { + if (sci.PositionIsOnComment(p)) + { + p--; + continue; + } + var cc = (char)sci.CharAt(p--); + if (cc <= ' ') buf += cc; + else if (features.ArithmeticOperators.Contains(cc)) + { + buf = cc + buf; + break; + } + else + { + buf = string.Empty; + break; + } + } + if (buf.Length > 0) curOp = buf + curOp; + break; + } + } + if (sb.Length != 0) + { + expression.Separator = curOp; + expression.SeparatorPosition -= curOp.Length - 1; + break; + } + position -= curOp.Length - 1; + expression.RightOperator = curOp; + hadDot = true; + } + else if (characterClass.Contains(c)) + { + if (hadWS && !hadDot) + { + expression.Separator = " "; + break; + } + hadWS = false; + hadDot = false; + dotCount = 0; + sb.Insert(0, c); + positionExpression = position; } else //if (hadWS && !hadDot) { - if (c == '\'' || c == '"') expression.Separator = '"'; - else expression.Separator = ';'; + if (hadDot && features.SpecialPostfixOperators.Contains(c)) + { + sb.Insert(0, $".{c}"); + continue; + } + if (c == '\'' || c == '"') expression.Separator = "\""; break; } } // string literals only allowed in sub-expressions else { - if (braceCount == 0) // not expected: something's wrong + if (parCount == 0 && !hadDot) // not expected: something's wrong { - expression.Separator = ';'; + expression.Separator = ";"; break; } } } - + + var value = sb.ToString().TrimStart('.'); + if (features.hasE4X && value.Length >= 2 && value[0] == '<' && value[value.Length - 1] == '>') + { + expression.Separator = ";"; + value = ""; + } + + expression.Value = value; + expression.PositionExpression = positionExpression; + expression.LineFrom = sci.LineFromPosition(positionExpression); + expression.LineTo = sci.LineFromPosition(expression.Position); // check if there is a particular keyword - if (expression.Separator == ' ') + if (expression.Separator == " " && position > 0) { - expression.WordBefore = GetWordLeft(Sci, ref position); + var pos = position; + expression.WordBefore = GetWordLeft(sci, ref pos); + if (expression.WordBefore.Length > 0) + { + position = pos; + expression.WordBeforePosition = position + 1; + } } - - // result - expression.Value = sb.ToString(); - expression.PositionExpression = startPos; + GetOperatorLeft(sci, position, expression); LastExpression = expression; - return expression; - } + return expression; + } /// /// Find out in what context is a coma-separated expression /// /// - private static ComaExpression DisambiguateComa(ScintillaControl Sci, int position, int minPos) + internal static ComaExpression DisambiguateComa(ScintillaControl sci, int position, int minPos) { - ContextFeatures features = ASContext.Context.Features; + var features = ASContext.Context.Features; // find block start '(' or '{' int parCount = 0; int braceCount = 0; int sqCount = 0; - char c = (char)Sci.CharAt(position); - bool wasPar = false; - //if (c == '{') { wasPar = true; position--; } while (position > minPos) { - c = (char)Sci.CharAt(position); - if (c == ';') - { - return ComaExpression.None; - } - else if ((c == ',' || c == '=') && wasPar) - { - return ComaExpression.AnonymousObject; - } - // var declaration - else if (c == ':') + var c = (char)sci.CharAt(position); + if (c == ';') return ComaExpression.None; + if (c == ':') { position--; - string word = GetWordLeft(Sci, ref position); - word = GetWordLeft(Sci, ref position); + GetWordLeft(sci, ref position); + var word = GetWordLeft(sci, ref position); if (word == features.varKey) return ComaExpression.VarDeclaration; - else continue; + continue; } // Array values - else if (c == '[') + if (c == '[') { sqCount--; - if (sqCount < 0) - { - return ComaExpression.ArrayValue; - } + if (sqCount < 0) return ComaExpression.ArrayValue; } - else if (c == ']') - { - if (wasPar) return ComaExpression.None; - sqCount++; - } - // function declaration or parameter + else if (c == ']') sqCount++; else if (c == '(') { parCount--; if (parCount < 0) { position--; - string word1 = GetWordLeft(Sci, ref position); + var word1 = GetWordLeft(sci, ref position); + if (word1.Length == 0 && sci.CharAt(position) == '>' && features.hasGenerics) + { + // Generic function: function generic(arg:K) + int groupCount = 1; + position--; + while (position >= 0 && groupCount > 0) + { + c = (char) sci.CharAt(position); + if ("({[<".Contains(c)) groupCount--; + else if (")}]>".Contains(c)) groupCount++; + position--; + } + word1 = GetWordLeft(sci, ref position); + } if (word1 == features.functionKey) return ComaExpression.FunctionDeclaration; // anonymous function - string word2 = GetWordLeft(Sci, ref position); + var word2 = GetWordLeft(sci, ref position); if (word2 == features.functionKey || word2 == features.setKey || word2 == features.getKey) return ComaExpression.FunctionDeclaration; // function declaration if (features.hasDelegates && word2 == "delegate") @@ -3440,59 +4028,78 @@ private static ComaExpression DisambiguateComa(ScintillaControl Sci, int positio return ComaExpression.FunctionParameter; // function call } } - else if (c == ')') - { - if (wasPar) return ComaExpression.None; - parCount++; - } - // code block or anonymous object + else if (c == ')') parCount++; else if (c == '{') { braceCount--; if (braceCount < 0) { position--; - string word1 = GetWordLeft(Sci, ref position); - c = (word1.Length > 0) ? word1[word1.Length - 1] : (char)Sci.CharAt(position); - if (":,(=".IndexOf(c) >= 0) + var word1 = GetWordLeft(sci, ref position); + c = word1.Length > 0 ? word1[word1.Length - 1] : (char) sci.CharAt(position); + if (":,(=".Contains(c)) { - string line = Sci.GetLine(Sci.LineFromPosition(position)); + var line = sci.GetLine(sci.LineFromPosition(position)); + //TODO: Very limited check, the case|default could be in a previous line, or it could be something else in the same line if (Regex.IsMatch(line, @"\b(case|default)\b.*:")) break; // case: code block + if (c == ':' && sci.ConfigurationLanguage == "haxe") + { + // Anonymous structures + var coma = DisambiguateComa(sci, position, minPos); + if (coma == ComaExpression.FunctionDeclaration || coma == ComaExpression.VarDeclaration) + { + return ComaExpression.VarDeclaration; + } + } return ComaExpression.AnonymousObjectParam; } - else if (c != ')' && c != '}' && !Char.IsLetterOrDigit(c)) return ComaExpression.AnonymousObject; + if (c != ')' && c != '}' && !char.IsLetterOrDigit(c)) return ComaExpression.AnonymousObject; break; } } - else if (c == '}') + else if (c == '}') braceCount++; + else if (c == '?') { - if (wasPar) return ComaExpression.None; - braceCount++; + //TODO: Change to ASContext.Context.CurrentModel + if (sci.ConfigurationLanguage == "haxe") // Haxe optional fields + { + var coma = DisambiguateComa(sci, position - 1, minPos); + if (coma == ComaExpression.FunctionDeclaration) return coma; // Function optional argument + if (coma == ComaExpression.VarDeclaration) + { + // Possible anonymous structure optional field. Check we are not in a ternary operator + position--; + var word1 = GetWordLeft(sci, ref position); + c = word1.Length > 0 ? word1[word1.Length - 1] : (char) sci.CharAt(position); + if (c == ',' || c == '{') return coma; + } + } + return ComaExpression.AnonymousObject; } - else if (c == '?') return ComaExpression.AnonymousObject; position--; } return ComaExpression.None; } - /// - /// Parse function body for local var definitions - /// TODO ASComplete: parse coma separated local vars definitions - /// - /// Expression source - /// Local vars dictionnary (name, type) - static public MemberList ParseLocalVars(ASExpr expression) - { - FileModel model; - if (expression.FunctionBody != null && expression.FunctionBody.Length > 0) - { - MemberModel cm = expression.ContextMember; - string functionBody = Regex.Replace(expression.FunctionBody, "function\\s*\\(", "function __anonfunc__("); // name anonymous functions - model = ASContext.Context.GetCodeModel(functionBody); - int memberCount = model.Members.Count; - for (int memberIndex = 0; memberIndex < memberCount; memberIndex++) - { - MemberModel member = model.Members[memberIndex]; + /// + /// Parse function body for local var definitions + /// TODO ASComplete: parse coma separated local vars definitions + /// + /// Expression source + /// Local vars dictionary (name, type) + public static MemberList ParseLocalVars(ASExpr expression) + { + FileModel model; + var ctx = ASContext.Context; + if (!string.IsNullOrEmpty(expression.FunctionBody)) + { + var cm = expression.ContextMember; + var functionBody = Regex.Replace(expression.FunctionBody, "function\\s*\\(", "function __anonfunc__("); // name anonymous functions + model = ctx.GetCodeModel(functionBody, true); + var memberCount = model.Members.Count; + for (var memberIndex = 0; memberIndex < memberCount; memberIndex++) + { + var member = model.Members[memberIndex]; if (cm.Equals(member)) continue; @@ -3500,273 +4107,837 @@ static public MemberList ParseLocalVars(ASExpr expression) member.LineFrom += expression.FunctionOffset; member.LineTo += expression.FunctionOffset; - if ((member.Flags & FlagType.Function) == FlagType.Function) + if ((member.Flags & FlagType.Function) != FlagType.Function) continue; + if (member.Name == "__anonfunc__") + { + model.Members.Remove(member); + memberCount--; + memberIndex--; + } + if (member.Parameters is null) continue; + foreach (var parameter in member.Parameters) + { + parameter.LineFrom += expression.FunctionOffset; + parameter.LineTo += expression.FunctionOffset; + model.Members.Add(parameter); + } + } + } + else model = new FileModel(); + model.Members.Sort(); + if (expression.ContextFunction?.Parameters != null) + { + ctx.CodeComplete.ParseLocalVars(expression, model); + var arguments = ctx.Features.functionArguments; + if (arguments != null) model.Members.MergeByLine(arguments); + } + return model.Members; + } + + protected virtual void ParseLocalVars(ASExpr expression, FileModel model) + { + var dot = ASContext.Context.Features.dot; + foreach (var item in expression.ContextFunction.Parameters) + { + var name = item.Name; + if (name.StartsWithOrdinal(dot)) model.Members.MergeByLine(new MemberModel(name.Substring(name.LastIndexOfOrdinal(dot) + 1), "Array", item.Flags, item.Access)); + else model.Members.MergeByLine(item); + } + } + + /// + /// Extract sub-expressions + /// + static string ExtractSubex(Match m) + { + ExtractedSubex.Add(m.Value); + return ".#" + (ExtractedSubex.Count - 1) + "~"; + } + #endregion + + #region tools_functions + + /// + /// Text style is a literal. + /// + public static bool IsLiteralStyle(int style) => IsNumericStyle(style) || IsStringStyle(style) || IsCharStyle(style); + + /// + /// Text style is a numeric literal. + /// + public static bool IsNumericStyle(int style) => style == (int) CPP.NUMBER; + + /// + /// Text style is a string literal. + /// + public static bool IsStringStyle(int style) => style == (int) CPP.STRING; + + /// + /// Text style is a multiline string literal. + /// + protected virtual bool IsMultilineStringStyle(ScintillaControl sci, int position) + { + return false; + } + + /// + /// Text style is character literal. + /// + public static bool IsCharStyle(int style) => style == (int) CPP.CHARACTER; + + /// + /// Text is word + /// + public static bool IsTextStyle(int style) + { + return style == (int) CPP.DEFAULT + || style == (int) CPP.OPERATOR + || style == (int) CPP.IDENTIFIER + || style == (int) CPP.WORD2 + || style == (int) CPP.WORD4 + || style == (int) CPP.WORD5 + || style == (int) HTML.PHP_OPERATOR; + } + + /// + /// Text is word or keyword + /// + public static bool IsTextStyleEx(int style) + => IsTextStyle(style) + || style == (int) CPP.WORD + || style == (int) CPP.GLOBALCLASS + || style == (int) CPP.WORD3; + + public static bool IsCommentStyle(int style) + => style == (int) CPP.COMMENT + || style == (int) CPP.COMMENTLINE + || style == (int) CPP.COMMENTDOC + || style == (int) CPP.COMMENTDOCKEYWORD + || style == (int) CPP.COMMENTDOCKEYWORDERROR; + + public virtual bool IsRegexStyle(ScintillaControl sci, int position) + => sci.BaseStyleAt(position) == (int) CPP.REGEX; + + public static string GetWordLeft(ScintillaControl sci, int position) => GetWordLeft(sci, ref position); + + public static string GetWordLeft(ScintillaControl sci, ref int position) + { + var characterClass = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage).characterclass.Characters; + var word = new StringBuilder(); + var skipWS = true; + while (position >= 0) + { + var style = sci.BaseStyleAt(position); + if (IsTextStyleEx(style)) + { + var c = (char)sci.CharAt(position); + if (c <= ' ') + { + if (!skipWS) break; + } + else if (!characterClass.Contains(c)) break; + else if (style != 6) + { + word.Insert(0, c); + skipWS = false; + } + } + position--; + } + return word.ToString(); + } + + public static string GetWordRight(ScintillaControl sci, int position) => GetWordRight(sci, ref position); + + public static string GetWordRight(ScintillaControl sci, ref int position) + { + var characterClass = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage).characterclass.Characters; + var word = new StringBuilder(); + var skipWS = true; + var length = sci.Length; + while (position < length) + { + var style = sci.BaseStyleAt(position); + if (IsTextStyleEx(style)) + { + var c = (char)sci.CharAt(position); + if (c <= ' ') + { + if (!skipWS) break; + } + else if (!characterClass.Contains(c)) break; + else if (style != 6) + { + word.Append(c); + skipWS = false; + } + } + position++; + } + return word.ToString(); + } + + protected static void GetOperatorLeft(ScintillaControl sci, int position, ASExpr expression) + { + if (expression.Separator == " " || (expression.Separator == ";" && sci.CharAt(position) != ';')) + { + var @operator = GetOperatorLeft(sci, ref position); + if (@operator.Length == 0) return; + expression.Separator = @operator; + expression.SeparatorPosition = position + 1; + } + } + + protected static string GetOperatorLeft(ScintillaControl sci, ref int position) + { + var result = string.Empty; + var skipWS = true; + while (position >= 0) + { + var c = (char)sci.CharAt(position); + if (char.IsDigit(c)) break; + var style = sci.BaseStyleAt(position); + if (IsTextStyleEx(style)) + { + if (c <= ' ') + { + if (!skipWS) break; + } + else if (char.IsLetterOrDigit(c) + || c == '.' || c == ',' || c == ';' || c == '_' || c == '$' + || c == '"' || c == '\'' + || c == ')' || c == '(' + || c == ']' || c == '[' + || c == '}' || c == '{') break; + else + { + skipWS = false; + result = c + result; + } + } + --position; + } + return result; + } + + public static char GetCharLeft(ScintillaControl sci, int position) => GetCharLeft(sci, true, ref position); + + public static char GetCharLeft(ScintillaControl sci, ref int position) => GetCharLeft(sci, true, ref position); + + public static char GetCharLeft(ScintillaControl sci, bool skipWhiteSpace, int position) => GetCharLeft(sci, skipWhiteSpace, ref position); + + public static char GetCharLeft(ScintillaControl sci, bool skipWhiteSpace, ref int position) + { + var result = position - 1; + while (result >= 0) + { + if (!sci.PositionIsOnComment(result)) + { + var c = (char) sci.CharAt(result); + if (!skipWhiteSpace || c > ' ') + { + position = result; + return c; + } + } + --result; + } + position = -1; + return ' '; + } + + public static char GetCharRight(ScintillaControl sci, ref int position) => GetCharRight(sci, true, ref position); + + public static char GetCharRight(ScintillaControl sci, bool skipWhiteSpace, int position) => GetCharRight(sci, skipWhiteSpace, ref position); + + public static char GetCharRight(ScintillaControl sci, bool skipWhiteSpace, ref int position) + { + var length = sci.Length; + var result = position; + while (result < length) + { + if (!sci.PositionIsOnComment(result)) + { + var c = (char)sci.CharAt(result); + if (!skipWhiteSpace || c > ' ') + { + position = result; + return c; + } + } + ++result; + } + position = -1; + return ' '; + } + + public static ASResult GetExpressionType(ScintillaControl sci, int position) => GetExpressionType(sci, position, true); + + public static ASResult GetExpressionType(ScintillaControl sci, int position, bool filterVisibility) => GetExpressionType(sci, position, filterVisibility, false); + + public static ASResult GetExpressionType(ScintillaControl sci, int position, bool filterVisibility, bool ignoreWhiteSpace) + { + // context + int line = sci.LineFromPosition(position); + if (line != ASContext.Context.CurrentLine) + ASContext.Context.UpdateContext(line); + try + { + var expr = GetExpression(sci, position, ignoreWhiteSpace); + expr.LocalVars = ParseLocalVars(expr); + if (string.IsNullOrEmpty(expr.Value)) return new ASResult {Context = expr}; + var aFile = ASContext.Context.CurrentModel; + var aClass = ASContext.Context.CurrentClass; + // Expression before cursor + return ASContext.Context.CodeComplete.EvalExpression(expr.Value, expr, aFile, aClass, true, false, filterVisibility); + } + finally + { + // restore context + if (line != ASContext.Context.CurrentLine) + ASContext.Context.UpdateContext(ASContext.Context.CurrentLine); + } + } + + static MemberList GetTypeParameters(MemberModel model) + { + MemberList result = null; + var template = model.Template; + if (template != null && template.StartsWith('<')) + { + var sb = new StringBuilder(); + int groupCount = 0; + bool inConstraint = false; + MemberModel genType = null; + for (int i = 1, count = template.Length - 1; i < count; i++) + { + char c = template[i]; + if (!inConstraint) + { + if (c == ':' || c == ',') + { + genType = new MemberModel + { + Name = sb.ToString(), + Type = sb.ToString(), + Flags = FlagType.TypeDef + }; + inConstraint = c == ':'; + result ??= new MemberList(); + result.Add(genType); + sb.Length = 0; + continue; + } + if (char.IsWhiteSpace(c)) continue; + sb.Append(c); + } + else + { + if (c == ',') + { + if (groupCount == 0) + { + genType.Type += ":" + sb; + genType = null; + inConstraint = false; + sb.Length = 0; + continue; + } + } + else if ("({[<".Contains(c)) groupCount++; + else if (")}]>".Contains(c)) groupCount--; + sb.Append(c); + } + } + if (sb.Length > 0) + { + result ??= new MemberList(); + if (!inConstraint) + { + var name = sb.ToString(); + result.Add(new MemberModel {Name = name, Type = name, Flags = FlagType.TypeDef}); + } + else genType.Type += ":" + sb; + } + } + return result; + } + + static List GetAllClasses(ScintillaControl sci, bool classesOnly, bool showClassVars) + { + var ctx = ASContext.Context; + var known = ctx.GetAllProjectClasses(); + if (known.Count == 0) return null; + + // get local Class vars + if (showClassVars) + { + var found = new MemberList(); + + var expr = GetExpression(sci, sci.CurrentPos); + if (expr.Value != null) + { + var list = ParseLocalVars(expr); + foreach (var it in list) + if (it.Type == "Class") + found.Add(it); + } + + if (found.Count > 0) + { + found.Sort(); + found.Merge(known); + known = found; + } + } + + if (!ctx.CurrentClass.IsVoid()) + { + if (ctx.Features.hasDelegates) + { + var delegates = new MemberList(); + + foreach (var field in ctx.CurrentClass.Members) + if ((field.Flags & FlagType.Delegate) > 0) + delegates.Add(field); + + if (delegates.Count > 0) + { + delegates.Sort(); + delegates.Merge(known); + known = delegates; + } + } + + if (ctx.Features.hasGenerics) + { + var typeParams = GetVisibleTypeParameters(); + if (!typeParams.IsNullOrEmpty()) + { + typeParams.Sort(); + typeParams.Merge(known); + known = typeParams; + } + } + } + + var result = new List(); + string prev = null; + var mask = (classesOnly) + ? FlagType.Class | FlagType.Interface | FlagType.Enum | FlagType.Delegate | FlagType.Struct | FlagType.TypeDef + : (FlagType)uint.MaxValue; + foreach (var member in known) + { + if ((member.Flags & mask) == 0 || prev == member.Name) + if (!showClassVars || member.Type != "Class") continue; + prev = member.Name; + result.Add(new MemberItem(member)); + } + return result; + } + + static MemberList GetVisibleElements() + { + var result = ASContext.Context.GetVisibleExternalElements(); + if (ASContext.Context.Features.hasGenerics && !ASContext.Context.CurrentClass.IsVoid() + && GetVisibleTypeParameters() is {Count: > 0} @params) + { + @params.Sort(); + @params.Merge(result); + return @params; + } + return result; + } + + static MemberList GetVisibleTypeParameters() + { + var result = GetTypeParameters(ASContext.Context.CurrentClass); + var member = ASContext.Context.CurrentMember; + if (member != null && (member.Flags & FlagType.Function) > 0) + { + var @params = GetTypeParameters(member); + if (result != null && @params != null) result.Add(@params); + else if (result is null) result = @params; + } + return result; + } + + /// + /// Returns whether or not position is inside of an expression block in String interpolation + /// Scintilla Control + /// Cursor position + /// + public virtual bool IsStringInterpolationStyle(ScintillaControl sci, int position) => false; + + protected bool IsEscapedCharacter(ScintillaControl sci, int position, char escapeChar = '\\') + { + var result = false; + for (var i = position - 1; i >= 0; i--) + { + if (sci.CharAt(i) != escapeChar) break; + result = !result; + } + return result; + } + + static bool IsMatchingQuote(char quote, int style) => quote == '"' && IsStringStyle(style) || quote == '\'' && IsCharStyle(style); + + protected virtual bool IsMetadataArgument(ScintillaControl sci, int position) => false; + + static bool IsXmlType(ClassModel model) => model != null && (model.QualifiedName == "XML" || model.QualifiedName == "XMLList"); + + public static int ExpressionEndPosition(ScintillaControl sci, int position) => ExpressionEndPosition(sci, position, false); + + public static int ExpressionEndPosition(ScintillaControl sci, int position, bool skipWhiteSpace) + { + var member = ASContext.Context.CurrentMember; + var endPosition = member != null ? sci.LineEndPosition(member.LineTo) : sci.TextLength; + return ExpressionEndPosition(sci, position, endPosition, skipWhiteSpace); + } + + public static int ExpressionEndPosition(ScintillaControl sci, int startPos, int endPos) => ExpressionEndPosition(sci, startPos, endPos, false); + + public static int ExpressionEndPosition(ScintillaControl sci, int startPos, int endPos, bool skipWhiteSpace) + { + var word = GetWordLeft(sci, sci.WordStartPosition(startPos, true) - 1); + var ctx = ASContext.Context; + if (ctx.Features.declKeywords.Contains(word) || ctx.Features.typesKeywords.Contains(word)) return sci.WordEndPosition(startPos, true); + var isInStringInterpolation = ctx.CodeComplete.IsStringInterpolationStyle(sci, startPos); + var result = startPos; + var statementEnd = startPos; + var characterClass = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage).characterclass.Characters; + var parCount = 0; + var brCount = 0; + var arrCount = 0; + var dQuotes = 0; + var sQuotes = 0; + var hadWS = false; + var stop = false; + var exprStarted = false; + sci.Colourise(0, -1); + while (statementEnd < endPos) + { + if (sci.PositionIsOnComment(statementEnd)) + { + statementEnd++; + continue; + } + if (ctx.CodeComplete.IsRegexStyle(sci, statementEnd)) + { + statementEnd++; + result = statementEnd; + continue; + } + var c = (char)sci.CharAt(statementEnd); + #region PositionIsInMultilineString + if ((dQuotes > 0 && c != '\"') || (sQuotes > 0 && c != '\'')) + { + result = ++statementEnd; + continue; + } + if (dQuotes > 0 && c == '\"') + { + result = ++statementEnd; + if (!ctx.CodeComplete.IsEscapedCharacter(sci, statementEnd - 1) && --dQuotes <= 0) break; + continue; + } + if (sQuotes > 0 && c == '\'') + { + result = ++statementEnd; + if (!ctx.CodeComplete.IsEscapedCharacter(sci, statementEnd - 1) && --sQuotes <= 0) break; + continue; + } + #endregion PositionIsInMultilineString + if (sci.PositionIsInString(statementEnd) && !ctx.CodeComplete.IsStringInterpolationStyle(sci, statementEnd)) + { + if (isInStringInterpolation) + { + result = statementEnd - 1; + break; + } + result = ++statementEnd; + continue; + } + statementEnd++; + if (c == '(') + { + if (arrCount == 0 && brCount == 0) + { + parCount++; + exprStarted = true; + } + } + else if (c == ')') + { + if (arrCount == 0 && brCount == 0) + { + parCount--; + if (parCount == 0) result = statementEnd; + if (parCount < 0) break; + } + } + else if (c == '{') + { + if (parCount == 0 && arrCount == 0) + { + if (stop) break; + brCount++; + exprStarted = true; + } + } + else if (c == '}') + { + if (parCount == 0 && arrCount == 0) + { + brCount--; + if (brCount == 0) result = statementEnd; + if (brCount < 0) break; + } + } + else if (c == '[') + { + if (parCount == 0 && brCount == 0) + { + // for example: ''.split()[] + if (GetCharLeft(sci, statementEnd - 2) == ')') + { + result = statementEnd - 1; + break; + } + if (stop) break; + arrCount++; + exprStarted = true; + } + } + else if (c == ']') + { + if (parCount == 0 && brCount == 0) + { + arrCount--; + if (arrCount == 0) result = statementEnd; + if (arrCount < 0) break; + } + } + else if (parCount == 0 && arrCount == 0 && brCount == 0) + { + if (dQuotes == 0 && c == '\'') { - if (member.Name == "__anonfunc__") - { - model.Members.Remove(member); - memberCount--; - memberIndex--; - } - - if (member.Parameters == null) continue; - - foreach (MemberModel parameter in member.Parameters) + result = ++statementEnd; + if (sQuotes == 0) sQuotes++; + else sQuotes--; + continue; + } + if (sQuotes > 0) continue; + if (sQuotes == 0 && c == '"') + { + result = ++statementEnd; + if (dQuotes == 0) dQuotes++; + else dQuotes--; + continue; + } + if (dQuotes > 0) continue; + if (characterClass.Contains(c)) + { + if (skipWhiteSpace) { - parameter.LineFrom += expression.FunctionOffset; - parameter.LineTo += expression.FunctionOffset; - model.Members.Add(parameter); + skipWhiteSpace = false; + hadWS = false; } + else if (hadWS) break; + stop = true; + result = statementEnd; + exprStarted = true; + } + else if (c <= ' ') hadWS = true; + else if (c == '.') + { + // for example: 0.0 + if (!exprStarted) break; + if (statementEnd >= endPos || !char.IsDigit((char) sci.CharAt(statementEnd))) break; + var p = statementEnd - 2; + if (p < 0 || !char.IsDigit((char) sci.CharAt(p))) break; + } + else if (c == '-' || c == '+') + { + if (!exprStarted) continue; + var p = statementEnd - 2; + // for example: 5e-324 + if (p < 1 || (sci.CharAt(p) != 'e' && !char.IsDigit((char) sci.CharAt(p - 1)))) break; } + else break; } } - else model = new FileModel(); - if (expression.ContextFunction != null && expression.ContextFunction.Parameters != null) + return result; + } + + /// + /// Returns true if position is before body of class or member + /// + public bool PositionIsBeforeBody(ScintillaControl sci, int position, MemberModel member) + { + var groupCount = 0; + var positionFrom = sci.PositionFromLine(member.LineFrom); + for (var i = positionFrom; i < position; i++) { - ContextFeatures features = ASContext.Context.Features; - foreach (MemberModel item in expression.ContextFunction.Parameters) - { - if (item.Name.StartsWith(features.dot)) - model.Members.Merge(new MemberModel(item.Name.Substring(item.Name.LastIndexOf(features.dot) + 1), "Array", item.Flags, item.Access)); - else if (item.Name[0] == '?') model.Members.Merge(new MemberModel(item.Name.Substring(1), item.Type, item.Flags, item.Access)); - else model.Members.Merge(item); - } - if (features.functionArguments != null) - model.Members.Add(ASContext.Context.Features.functionArguments); + if (sci.PositionIsOnComment(position)) continue; + var c = (char)sci.CharAt(i); + if (c == '(' || c == '<') groupCount++; + else if (c == ')' || (c == '>' && sci.CharAt(i - 1) != '-')) groupCount--; + else if (c == '{' && groupCount == 0) return false; } - model.Members.Sort(); - return model.Members; - } - - /// - /// Extract sub-expressions - /// - static private string ExtractSubex(Match m) - { - ExtractedSubex.Add(m.Value); - return ".#" + (ExtractedSubex.Count - 1) + "~"; - } - #endregion - - #region tools_functions + return true; + } + #endregion - static public bool IsLiteralStyle(int style) + #region tooltips formatting + public static string GetCodeTipCode(ASResult result) { - return (style == 4) || (style == 6) || (style == 7); + if (result.Member is null) return result.Type?.ToString(); + + var file = GetFileContents(result.InFile); + if (string.IsNullOrEmpty(file)) return MemberTooltipText(result.Member, ClassModel.VoidClass); + var eolMode = LineEndDetector.DetectNewLineMarker(file); + var eolMarker = LineEndDetector.GetNewLineMarker(eolMode); + var lines = file.Split(new[] { eolMarker }, StringSplitOptions.None); + var code = new StringBuilder(); + for (var index = result.Member.LineFrom; index < result.Member.LineTo; index++) + { + code.AppendLine(lines[index]); + } + code.Append(lines[result.Member.LineTo]); + return code.ToString(); } - /// - /// Text is word - /// - static public bool IsTextStyle(int style) - { - return style == 0 || style == 10 /*punctuation*/ || style == 11 /*identifier*/ - || style == 16 /*word2 (secondary keywords: class name)*/ - || style == 24 /*word4 (add keywords4)*/ || style == 25 /*word5 (add keywords5)*/ - || style == 127 /*PHP*/; - } - - /// - /// Text is word or keyword - /// - static public bool IsTextStyleEx(int style) - { - return style == 0 || style == 5 /*word (secondary keywords)*/ - || style == 10 /*punctuation*/ || style == 11 /*identifier*/ - || style == 16 /*word2 (secondary keywords: class name)*/ - || style == 19 /*globalclass (primary keywords)*/ || style == 23 /*word3 (add keywords3)*/ - || style == 24 /*word4 (add keywords4)*/ || style == 25 /*word5 (add keywords5)*/ - || style == 127 /*PHP*/; - } - - static public bool IsCommentStyle(int style) - { - return style == 1 || style == 2 || style == 3 /*comments*/ - || style == 17 || style == 18 /*javadoc tags*/; - } - - static public string GetWordLeft(ScintillaControl Sci, ref int position) - { - // get the word characters from the syntax definition - string characterClass = ScintillaControl.Configuration.GetLanguage(Sci.ConfigurationLanguage).characterclass.Characters; - - string word = ""; - //string exclude = "(){};,+*/\\=:.%\"<>"; - bool skipWS = true; - int style; - int stylemask = (1 << Sci.StyleBits) -1; - char c; - while (position >= 0) - { - style = Sci.StyleAt(position) & stylemask; - if (IsTextStyleEx(style)) - { - c = (char)Sci.CharAt(position); - if (c <= ' ') - { - if (!skipWS) - break; - } - else if (characterClass.IndexOf(c) < 0) break; - else if (style != 6) - { - word = c+word; - skipWS = false; - } - } - position--; - } - return word; - } - - static public ASResult GetExpressionType(ScintillaControl sci, int position) - { - // context - int line = sci.LineFromPosition(position); - if (line != ASContext.Context.CurrentLine) - ASContext.Context.UpdateContext(line); - try + static string GetFileContents(FileModel model) + { + if (!File.Exists(model?.FileName)) return null; + foreach (var doc in PluginBase.MainForm.Documents) { - ASExpr expr = GetExpression(sci, position); - expr.LocalVars = ParseLocalVars(expr); - if ((expr.Value == null) || (expr.Value.Length == 0)) + if (doc.SciControl is { } sci && string.Equals(sci.FileName, model.FileName, StringComparison.CurrentCultureIgnoreCase)) { - ASResult res = new ASResult(); - res.Context = expr; - return res; + return sci.Text; } - FileModel aFile = ASContext.Context.CurrentModel; - ClassModel aClass = ASContext.Context.CurrentClass; - // Expression before cursor - return EvalExpression(expr.Value, expr, aFile, aClass, true, false); } - finally + var info = FileHelper.GetEncodingFileInfo(model.FileName); + return info.Contents; + } + + public static string GetToolTipText(ASResult expr) => ASContext.Context.CodeComplete.GetToolTipTextEx(expr); + + protected virtual string GetToolTipTextEx(ASResult expr) + { + if (expr.IsNull()) return null; + if (expr.Member != null && expr.InClass != null) { - // restore context - if (line != ASContext.Context.CurrentLine) - ASContext.Context.UpdateContext(ASContext.Context.CurrentLine); + return MemberTooltipText(expr.Member, expr.InClass) + GetToolTipDoc(expr.Member); + } + if (expr.Member != null && (expr.Member.Flags & FlagType.Constructor) != FlagType.Constructor) + { + return MemberTooltipText(expr.Member, ClassModel.VoidClass) + GetToolTipDoc(expr.Member); + } + if (expr.InClass != null) + { + return ClassModel.ClassDeclaration(expr.InClass) + GetToolTipDoc(expr.InClass); } - } + if (expr.Type != null) + { + if (expr.Context.WordBefore == "new") return ASContext.Context.CodeComplete.GetConstructorTooltipText(expr.Type); + return ClassModel.ClassDeclaration(expr.Type) + GetToolTipDoc(expr.Type); + } + return null; + } - private static bool IsXmlType(ClassModel model) + protected virtual string GetConstructorTooltipText(ClassModel type) { - return model != null - && (model.QualifiedName == "XML" || model.QualifiedName == "XMLList"); + var name = type.Name; + var member = type.Members.Search(name, FlagType.Constructor) + ?? new MemberModel(name, name, FlagType.Access | FlagType.Function | FlagType.Constructor, Visibility.Public); + return MemberTooltipText(member, type) + GetToolTipDoc(member); } - #endregion - - #region tooltips formatting - static public string GetToolTipText(ASResult result) - { - if (result.Member != null && result.InClass != null) - { - return MemberTooltipText(result.Member, result.InClass) + GetToolTipDoc(result.Member); - } - else if (result.Member != null && (result.Member.Flags & FlagType.Constructor) != FlagType.Constructor) - { - return MemberTooltipText(result.Member, ClassModel.VoidClass) + GetToolTipDoc(result.Member); - } - else if (result.InClass != null) - { - return ClassModel.ClassDeclaration(result.InClass) + GetToolTipDoc(result.InClass); - } - else if (result.Type != null) - { - return ClassModel.ClassDeclaration(result.Type) + GetToolTipDoc(result.Type); - } - else return null; - } - - private static string GetToolTipDoc(MemberModel model) + protected static string GetToolTipDoc(MemberModel model) { - return ASDocumentation.GetTipShortDetails(model, null).TrimStart(new char[] { ' ', '\u2026' }); + var details = UITools.Manager.ShowDetails + ? ASDocumentation.GetTipFullDetails(model, null) + : ASDocumentation.GetTipShortDetails(model, null); + return details.TrimStart(' ', '\u2026'); } - static private string MemberTooltipText(MemberModel member, ClassModel inClass) - { - // modifiers - FlagType ft = member.Flags; - Visibility acc = member.Access; - string modifiers = ""; - if ((ft & FlagType.Class) == 0) - { - if ((ft & FlagType.LocalVar) > 0) - modifiers += "(local) "; - else if ((ft & FlagType.ParameterVar) > 0) - modifiers += "(parameter) "; - else if ((ft & FlagType.AutomaticVar) > 0) - modifiers += "(auto) "; - else - { - if ((ft & FlagType.Extern) > 0) - modifiers += "extern "; - if ((ft & FlagType.Native) > 0) - modifiers += "native "; - if ((ft & FlagType.Static) > 0) - modifiers += "static "; - if ((acc & Visibility.Private) > 0) - modifiers += "private "; - else if ((acc & Visibility.Public) > 0) - modifiers += "public "; - else if ((acc & Visibility.Protected) > 0) - modifiers += "protected "; - else if ((acc & Visibility.Internal) > 0) - modifiers += "internal "; - } - } - // signature - string foundIn = ""; + protected static string MemberTooltipText(MemberModel member, ClassModel inClass) + { + var modifiers = ASContext.Context.CodeComplete.GetMemberModifiersTooltipText(member); + // signature + var foundIn = ""; if (inClass != ClassModel.VoidClass) { - string package = inClass.InFile.Package; - foundIn = "\n[COLOR=#666666:MULTIPLY]in " + MemberModel.FormatType(inClass.QualifiedName) + "[/COLOR]"; + var themeForeColor = PluginBase.MainForm.GetThemeColor("MethodCallTip.InfoColor"); + var foreColorString = + themeForeColor != Color.Empty ? ColorTranslator.ToHtml(themeForeColor) : "#666666:MULTIPLY"; + foundIn = "\n[COLOR=" + foreColorString + "]in " + MemberModel.FormatType(inClass.QualifiedName) + "[/COLOR]"; + } + return ASContext.Context.CodeComplete.GetMemberSignatureTooltipText(member, modifiers, foundIn); + } + + protected virtual string GetMemberSignatureTooltipText(MemberModel member, string modifiers, string foundIn) + { + var ft = member.Flags; + if ((ft & (FlagType.Getter | FlagType.Setter)) > 0) return $"{modifiers}property {member}{foundIn}"; + if (ft == FlagType.Function) return $"{modifiers}function {member}{foundIn}"; + if ((ft & FlagType.Namespace) > 0) return $"{modifiers}namespace {member.Name}{foundIn}"; + if ((ft & FlagType.Constant) > 0) + { + if (member.Value is null) return $"{modifiers}const {member}{foundIn}"; + return $"{modifiers}const {member} = {member.Value}{foundIn}"; } - if ((ft & (FlagType.Getter | FlagType.Setter)) > 0) - return String.Format("{0}property {1}{2}", modifiers, member.ToString(), foundIn); - else if (ft == FlagType.Function) - return String.Format("{0}function {1}{2}", modifiers, member.ToString(), foundIn); - else if ((ft & FlagType.Namespace) > 0) - return String.Format("{0}namespace {1}{2}", modifiers, member.Name, foundIn); - else if ((ft & FlagType.Constant) > 0) + + if ((ft & FlagType.Variable) > 0) return $"{modifiers}var {member}{foundIn}"; + if ((ft & FlagType.Delegate) > 0) return $"{modifiers}delegate {member}{foundIn}"; + return $"{modifiers}{member}{foundIn}"; + } + + protected virtual string GetMemberModifiersTooltipText(MemberModel member) + { + var result = string.Empty; + var flags = member.Flags; + if ((flags & FlagType.Class) == 0) { - if (member.Value == null) - return String.Format("{0}const {1}{2}", modifiers, member.ToString(), foundIn); + if ((flags & FlagType.LocalVar) > 0) result += "(local) "; + else if ((flags & FlagType.ParameterVar) > 0) result += "(parameter) "; + else if ((flags & FlagType.AutomaticVar) > 0) result += "(auto) "; else - return String.Format("{0}const {1} = {2}{3}", modifiers, member.ToString(), member.Value, foundIn); + { + if ((flags & FlagType.Extern) > 0) result += "extern "; + if ((flags & FlagType.Native) > 0) result += "native "; + if ((flags & FlagType.Static) > 0) result += "static "; + var access = member.Access; + if ((access & Visibility.Private) > 0) result += "private "; + else if ((access & Visibility.Public) > 0) result += "public "; + else if ((access & Visibility.Protected) > 0) result += "protected "; + else if ((access & Visibility.Internal) > 0) result += "internal "; + } } - else if ((ft & FlagType.Variable) > 0) - return String.Format("{0}var {1}{2}", modifiers, member.ToString(), foundIn); - else if ((ft & FlagType.Delegate) > 0) - return String.Format("{0}delegate {1}{2}", modifiers, member.ToString(), foundIn); - else - return String.Format("{0}{1}{2}", modifiers, member.ToString(), foundIn); - } - #endregion + return result; + } + + #endregion + + #region automatic code generation - #region automatic code generation - static private ASExpr LastExpression; + static ASExpr LastExpression; /// /// When typing a fully qualified class name: /// - automatically insert import statement /// - replace with short name /// - static internal void HandleCompletionInsert(ScintillaControl sci, int position, string text, char trigger, ICompletionListItem item) + internal static void HandleCompletionInsert(ScintillaControl sci, int position, string text, char trigger, ICompletionListItem item) { // if the current class hash was set, we want to store whatever the user selected as the last-completed member for this class. - if (currentClassHash != null) - { - completionHistory[currentClassHash] = text; - } - - if (!ASContext.Context.IsFileValid) - return; + if (currentClassHash != null) completionHistory[currentClassHash] = text; + if (!ASContext.Context.IsFileValid) return; // let the context handle the insertion - if (ASContext.Context.OnCompletionInsert(sci, position, text, trigger)) - return; - + if (ASContext.Context.OnCompletionInsert(sci, position, text, trigger)) return; // event inserted if (item is EventItem) { @@ -3775,117 +4946,117 @@ static internal void HandleCompletionInsert(ScintillaControl sci, int position, } // default handling - if (ASContext.Context.Settings != null) + if (ASContext.Context.Settings is null) return; + var textEndPosition = position + text.Length; + // was a fully qualified type inserted? + var expr = GetExpression(sci, textEndPosition); + if (expr.Value is null) return; + var type = GetExpressionType(sci, textEndPosition); + if (type.IsPackage) return; + var features = ASContext.Context.Features; + // add ; for imports + if ((trigger == ' ' || trigger == '\n' || trigger == '\t') + && expr.WordBefore != null + && (expr.WordBefore == features.importKey || expr.WordBefore == features.importKeyAlt)) { - // was a fully qualified type inserted? - ASExpr expr = GetExpression(sci, position + text.Length); - if (expr.Value == null) return; - - // look for a snippet - ContextFeatures features = ASContext.Context.Features; - if (trigger == '\t' && expr.Value.IndexOf(features.dot) < 0) + if (!sci.GetLine(sci.CurrentLine).Contains(';')) sci.InsertText(sci.CurrentPos, ";"); + return; + } + // look for a snippet + if (!expr.Value.Contains(features.dot)) + { + if (trigger == '\t') { - foreach(string key in features.codeKeywords) + foreach(var key in features.codeKeywords) if (key == expr.Value) { InsertSnippet(key); return; } } + if (trigger != ' ' + // for example: priv$(EntryPoint) -> private $(EntryPoint) + && (features.accessKeywords.Contains(text) + // for example: va$(EntryPoint) -> var $(EntryPoint) + || text == features.varKey || text == features.constKey + // for example: re$(EntryPoint) -> return $(EntryPoint) + || text == features.ReturnKey + // for example: im$(EntryPoint) -> import $(EntryPoint) + || features.typesPreKeys.Contains(text) + // for example: cl$(EntryPoint) -> class $(EntryPoint) + || features.typesKeywords.Contains(text))) + { + if (text == features.ReturnKey) + { + var returnType = expr.ContextFunction?.Type; + if (returnType.IsNullOrEmpty() || returnType == features.voidKey) + { + return; + } + } - // resolve context & do smart insertion - expr.LocalVars = ParseLocalVars(expr); - ASResult context = EvalExpression(expr.Value, expr, ASContext.Context.CurrentModel, ASContext.Context.CurrentClass, true, false); - if (SmartInsertion(sci, position, expr, context)) - DispatchInsertedElement(context, trigger); + var pos = sci.CurrentPos; + sci.InsertText(pos++, " "); + sci.SetSel(pos, pos); + OnChar(sci, ' ', true); + return; + } } + // resolve context & do smart insertion + expr.LocalVars = ParseLocalVars(expr); + var context = EvalExpression(expr.Value, expr, ASContext.Context.CurrentModel, ASContext.Context.CurrentClass, true, false); + if (SmartInsertion(sci, position, expr, context)) + DispatchInsertedElement(context, trigger); } - private static void SmartEventInsertion(ScintillaControl sci, int position, ICompletionListItem item) + static void SmartEventInsertion(ScintillaControl sci, int position, ICompletionListItem item) { + if (!ASContext.Context.Settings.GenerateImports) return; try { - ClassModel import = (item as EventItem).EventType; - if (!ASContext.Context.IsImported(import, sci.LineFromPosition(position))) - { - if (ASContext.Context.Settings.GenerateImports) - { - int offset = ASGenerator.InsertImport(import, true); - if (offset > 0) - { - position += offset; - sci.SetSel(position, position); - } - } - } + var import = ((EventItem) item).EventType; + if (ASContext.Context.IsImported(import, sci.LineFromPosition(position))) return; + var offset = ASGenerator.InsertImport(import, true); + if (offset <= 0) return; + position += offset; + sci.SetSel(position, position); } - catch (Exception) // event type name already present in imports + catch // event type name already present in imports { } } - private static bool SmartInsertion(ScintillaControl sci, int position, ASExpr expr, ASResult context) + static bool SmartInsertion(ScintillaControl sci, int position, ASExpr expr, ASResult context) { - ContextFeatures features = ASContext.Context.Features; - FileModel cFile = ASContext.Context.CurrentModel; - ClassModel cClass = ASContext.Context.CurrentClass; - MemberModel cMember = ASContext.Context.CurrentMember; - FileModel inFile = null; - MemberModel import = null; + var features = ASContext.Context.Features; + var cFile = ASContext.Context.CurrentModel; + MemberModel import = context.Type; // if completed a package-level member - if (context.Member != null && context.Member.IsPackageLevel && context.Member.InFile.Package != "") + if (context.Member != null && context.Member.IsPackageLevel && context.Member.InFile.Package.Length != 0) { - inFile = context.Member.InFile; - import = context.Member.Clone() as MemberModel; - import.Type = inFile.Package + "." + import.Name; + import = context.Member.Clone(); + import.Type = context.Member.InFile.Package + "." + import.Name; } // if not completed a type - else if (context.IsNull() || !context.IsStatic || context.Type == null - || (context.Type.Type != null && context.Type.Type.IndexOf(features.dot) < 0) - || context.Type.IsVoid()) + else if (context.IsNull() || !context.IsStatic || context.Type is null + || (context.Type.Type != null && !context.Type.Type.Contains(features.dot)) + || context.Type.IsVoid()) { - if (context.Member != null && expr.Separator == ' ' - && expr.WordBefore == features.overrideKey) + if (context.Member != null && expr.Separator == " " && expr.WordBefore == features.overrideKey) { ASGenerator.GenerateOverride(sci, context.InClass, context.Member, position); return false; } - /*else if (context.Member != null && cMember == null && !context.inClass.IsVoid()) - { - string ins = features.overrideKey + " "; - string w = sci.GetWordFromPosition(position); - sci.SetSel(position, position); - sci.ReplaceSel(ins); - position = position + ins.Length; - sci.CurrentPos = position; - sci.SetSel(position, position); - ASGenerator.GenerateOverride(sci, context.inClass, context.Member, position); - return false; - }*/ - else if (!context.IsNull()) - { - if (expr.WordBefore == features.importKey) - ASContext.Context.RefreshContextCache(expr.Value); - } + if (!context.IsNull() && expr.WordBefore == features.importKey) ASContext.Context.RefreshContextCache(expr.Value); return true; } - // test inserted type - else - { - inFile = context.InFile; - import = context.Type; - } - if (inFile == null || import == null) - return false; - - if (expr.Separator == ' ' && expr.WordBefore != null && expr.WordBefore != "") + if (expr.Separator == " " && !string.IsNullOrEmpty(expr.WordBefore)) { if (expr.WordBefore == features.importKey || expr.WordBefore == features.importKeyAlt /*|| (!features.HasTypePreKey(expr.WordBefore) && expr.WordBefore != "case" && expr.WordBefore != "return")*/) { - if (expr.WordBefore == features.importKey || expr.WordBefore == features.importKeyAlt) - ASContext.Context.RefreshContextCache(expr.Value); + ASContext.Context.RefreshContextCache(expr.Value); return true; } } @@ -3893,175 +5064,142 @@ private static bool SmartInsertion(ScintillaControl sci, int position, ASExpr ex int offset = 0; int startPos = expr.PositionExpression; int endPos = sci.CurrentPos; - - if (shouldShortenType(sci, position, import, cFile, ref offset)) + if (ASContext.Context.Settings.GenerateImports && ShouldShortenType(sci, position, import, cFile, ref offset)) { // insert short name startPos += offset; endPos += offset; sci.SetSel(startPos, endPos); - sci.ReplaceSel(checkShortName(import.Name)); + sci.ReplaceSel(CheckShortName(import.Name)); sci.SetSel(sci.CurrentPos, sci.CurrentPos); } return true; } - private static bool shouldShortenType(ScintillaControl sci, int position, MemberModel import, FileModel cFile, ref int offset) + static bool ShouldShortenType(ScintillaControl sci, int position, MemberModel import, FileModel cFile, ref int offset) { - // check if in the same file or package - /*if (cFile == inFile || features.hasPackages && cFile.Package == inFile.Package) - return true*/ - - // type name already present in imports - try + var ctx = ASContext.Context; + if (!ctx.Settings.GenerateImports) return false; + if (ctx.CodeComplete.IsMetadataArgument(sci, position)) return false; + var importName = import.Name; + var curLine = sci.LineFromPosition(position); + if (ctx.IsImported(import, curLine)) { - int curLine = sci.LineFromPosition(position); - if (ASContext.Context.IsImported(import, curLine)) - return true; - } - catch (Exception) - { - return false; + var importType = import.Type; + var imports = ctx.ResolveImports(cFile); + return !imports.Any(it => it.Name == importName && it.Type != importType); } - - // class with same name exists in current package? - if (ASContext.Context.Features.hasPackages && import is ClassModel) + // insert import + sci.BeginUndoAction(); + try { - string cname = import.Name; - if (cFile.Package.Length > 0) cname = cFile.Package + "." + cname; - ClassModel inPackage = ASContext.Context.ResolveType(cname, cFile); - if (!inPackage.IsVoid()) - return true; + var imports = ctx.ResolveImports(cFile); + offset = ASGenerator.InsertImport(import, true); + if (imports.Any(it => it.Name == importName)) return false; } - - // insert import - if (ASContext.Context.Settings.GenerateImports) + finally { - sci.BeginUndoAction(); - try - { - offset = ASGenerator.InsertImport(import, true); - } - finally - { - sci.EndUndoAction(); - } - return true; + sci.EndUndoAction(); } - return false; + return true; } - private static string checkShortName(string name) + static string CheckShortName(string name) { int p = name.IndexOf('<'); if (p > 1 && name[p - 1] == '.') p--; return (p > 0) ? name.Substring(0, p) : name; } - private static void DispatchInsertedElement(ASResult context, char trigger) + static void DispatchInsertedElement(ASResult context, char trigger) { - Hashtable info = new Hashtable(); - info["context"] = context; - info["trigger"] = trigger; - DataEvent de = new DataEvent(EventType.Command, "ASCompletion.InsertedElement", info); + var info = new Hashtable {["context"] = context, ["trigger"] = trigger}; + var de = new DataEvent(EventType.Command, "ASCompletion.InsertedElement", info); EventManager.DispatchEvent(ASContext.Context, de); } - private static void InsertSnippet(string word) + static void InsertSnippet(string word) + { + if (HasSnippet(word)) PluginBase.MainForm.CallCommand("InsertSnippet", word); + } + + public static bool HasSnippet(string word) + { + return File.Exists(Path.Combine(PathHelper.SnippetDir, ASContext.Context.Settings.LanguageId, word + ".fds")) + || File.Exists(Path.Combine(PathHelper.SnippetDir, word + ".fds")); + } + + /// + /// Some characters can fire code generation + /// + /// + /// Character inserted + /// Code was generated + static bool CodeAutoOnChar(ScintillaControl sci, int value) { - String global = Path.Combine(PathHelper.SnippetDir, word + ".fds"); - String specificDir = Path.Combine(PathHelper.SnippetDir, ASContext.Context.Settings.LanguageId); - String specific = Path.Combine(specificDir, word + ".fds"); - if (File.Exists(specific) || File.Exists(global)) - PluginBase.MainForm.CallCommand("InsertSnippet", word); + if (ASContext.Context.Settings is null + || !ASContext.Context.Settings.GenerateImports + || value != '*') return false; + var position = sci.CurrentPos; + if (position > 1 && sci.CharAt(position - 2) == '.' && LastExpression != null) return HandleWildcardList(sci, position, LastExpression); + return false; } - private static void InsertSymbol(ScintillaControl sci, string p) + /// + /// User entered a qualified package with a wildcard, eg. flash.geom.*, at an unexpected position, eg. not after 'import'. + /// Remove expression, generate coresponding wildcard import, and show list of types of this package + /// + static bool HandleWildcardList(ScintillaControl sci, int position, ASExpr expr) { - if (ASContext.CommonSettings.AddClosingBraces) + // validate context + var context = ASContext.Context; + if (expr.Separator == " " && expr.WordBefore != null + && context.Features.HasTypePreKey(expr.WordBefore)) + return false; + + var cFile = context.CurrentModel; + var cClass = context.CurrentClass; + var resolved = EvalExpression(expr.Value, expr, cFile, cClass, true, false); + if (resolved.IsNull() || !resolved.IsPackage || resolved.InFile is null) return false; + var package = resolved.InFile.Package; + var check = Regex.Replace(expr.Value, "\\s", "").TrimEnd('.'); + if (check != package) return false; + sci.BeginUndoAction(); + try { - sci.InsertText(sci.CurrentPos, p); + // remove temp wildcard + int startPos = expr.PositionExpression; + sci.SetSel(startPos, position); + sci.ReplaceSel(string.Empty); + + // generate import + if (context.Settings.GenerateImports) + { + var wildcard = new MemberModel { Name = "*", Type = package + ".*" }; + if (!context.IsImported(wildcard, sci.LineFromPosition(position))) + { + startPos += ASGenerator.InsertImport(wildcard, true); + sci.SetSel(startPos, startPos); + } + } + } + finally + { + sci.EndUndoAction(); } + + // show types + var imports = context.ResolvePackage(package, false).Imports; + var list = imports.Select(static it => new MemberItem(it)).ToArray(); + CompletionList.Show(list, false); + return true; } - /// - /// Some characters can fire code generation - /// - /// - /// Character inserted - /// Code was generated - static private bool CodeAutoOnChar(ScintillaControl sci, int value) - { - if (ASContext.Context.Settings == null || !ASContext.Context.Settings.GenerateImports) - return false; - - int position = sci.CurrentPos; - - if (value == '*' && position > 1 && sci.CharAt(position-2) == '.' && LastExpression != null) - { - // context - if (LastExpression.Separator == ' ' && LastExpression.WordBefore != null - && !ASContext.Context.Features.HasTypePreKey(LastExpression.WordBefore)) - return false; - - FileModel cFile = ASContext.Context.CurrentModel; - ClassModel cClass = ASContext.Context.CurrentClass; - ASResult context = EvalExpression(LastExpression.Value, LastExpression, cFile, cClass, true, false); - if (context.IsNull() || !context.IsPackage || context.InFile == null) - return false; - - string package = LastExpression.Value; - int startPos = LastExpression.Position; - string check = ""; - char c; - while (startPos > LastExpression.PositionExpression && check.Length <= package.Length && check != package) - { - c = (char)sci.CharAt(--startPos); - if (c > 32) check = c+check; - } - if (check != package) - return false; - - // insert import - string statement = "import " + package + "*;" + LineEndDetector.GetNewLineMarker(sci.EOLMode); - int endPos = sci.CurrentPos; - int line = 0; - int curLine = sci.LineFromPosition(position); - bool found = false; - while (line < curLine) - { - if (sci.GetLine(line++).IndexOf("import") >= 0) found = true; - else if (found) { - line--; - break; - } - } - if (line == curLine) line = 0; - position = sci.PositionFromLine(line); - line = sci.FirstVisibleLine; - sci.SetSel(position, position); - sci.ReplaceSel(statement); - - // prepare insertion of the term as usual - startPos += statement.Length; - endPos += statement.Length; - sci.SetSel(startPos, endPos); - sci.ReplaceSel(""); - sci.LineScroll(0, line-sci.FirstVisibleLine+1); - - // create classes list - List list = new List(); - foreach(MemberModel import in cClass.InFile.Imports) - if (import.Type.StartsWith(package)) - list.Add(new MemberItem(import)); - CompletionList.Show(list, false); - return true; - } - return false; - } - - #endregion + #endregion + public virtual string ToFunctionDeclarationString(MemberModel member) => member != null + ? $"Function/*({member.ParametersString()}):{member.Type}*/" + : "Function"; } #region completion list @@ -4070,44 +5208,80 @@ static private bool CodeAutoOnChar(ScintillaControl sci, int value) /// public class MemberItem : ICompletionListItem { - private MemberModel member; - private int icon; + public MemberModel Member { get; } + readonly int icon; public MemberItem(MemberModel oMember) { - member = oMember; - icon = PluginUI.GetIcon(member.Flags, member.Access); + Member = oMember; + icon = PluginUI.GetIcon(Member.Flags, Member.Access); } - public string Label + public string Label => Member.FullName; + + public virtual string Description => ClassModel.MemberDeclaration(Member) + ASDocumentation.GetTipDetails(Member, null); + + public Bitmap Icon => (Bitmap)ASContext.Panel.GetIcon(icon); + + public string Value { - get { return member.Name; } + get + { + if (!Member.Name.Contains('<', out var p1) && p1 <= 0 || Member.Template is null) return Member.Name; + + // ActionScript3: Vector. + if (Member.Name.Contains(".<", out var p2) && p2 > 0) + return Member.Name.Substring(0, p2); + return Member.Name.Substring(0, p1); + } } - public string Description + public override string ToString() => Label; + } + + /// + /// Nonexistent member completion list item + /// + public class NonexistentMemberItem : ICompletionListItem + { + static Bitmap icon; + + public NonexistentMemberItem(string memberName) => Label = memberName; + + public string Label { get; } + + public virtual string Description => Label; + + public Bitmap Icon => icon ??= (Bitmap) PluginBase.MainForm.FindImage("197"); + + public string Value { get { - return ClassModel.MemberDeclaration(member) + ASDocumentation.GetTipDetails(member, null); + if (!Label.Contains('<', out var p1)) return Label; + return Label.Contains(".<", out var p2) && p2 > 0 + ? Label.Substring(0, p2) + : Label.Substring(0, p1); } } - public System.Drawing.Bitmap Icon - { - get { return (System.Drawing.Bitmap)ASContext.Panel.GetIcon(icon); } - } + public override string ToString() => Label; + } - public string Value + /// + /// Template completion list item + /// + public class TemplateItem : MemberItem + { + public TemplateItem(MemberModel oMember) : base(oMember) { } + + public override string Description { - get + get { - if (member.Name.IndexOf('<') > 0) - { - if (member.Name.IndexOf(".<") > 0) - return member.Name.Substring(0, member.Name.IndexOf(".<")); - else return member.Name.Substring(0, member.Name.IndexOf('<')); - } - return member.Name; + if (ASComplete.HasSnippet(Member.Name)) + Member.Comments = "[i](" + TextHelper.GetString("Info.InsertKeywordSnippet") + ")[/i]"; + return base.Description; } } } @@ -4117,31 +5291,15 @@ public string Value /// public class DeclarationItem : ICompletionListItem { - private string label; + public DeclarationItem(string label) => Label = label; - public DeclarationItem(string label) - { - this.label = label; - } + public string Label { get; } - public string Label - { - get { return label; } - } - public string Description - { - get { return TextHelper.GetString("Info.DeclarationTemplate"); } - } + public string Description => TextHelper.GetString("Info.DeclarationTemplate"); - public System.Drawing.Bitmap Icon - { - get { return (System.Drawing.Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_DECLARATION); } - } + public Bitmap Icon => (Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_DECLARATION); - public string Value - { - get { return label; } - } + public string Value => Label; } /// @@ -4149,55 +5307,50 @@ public string Value /// public class EventItem : ICompletionListItem { - private string name; - private string comments; - private CommentBlock cb; - public ClassModel EventType; + readonly string comments; + public readonly ClassModel EventType; + CommentBlock cb; public EventItem(string name, ClassModel type, string comments) { - this.name = name; + Label = name; EventType = type; this.comments = comments; } - public string Label - { - get { return name; } - } + public string Label { get; } + public string Description { get { if (!ASContext.CommonSettings.SmartTipsEnabled) return TextHelper.GetString("Info.EventConstant"); - if (cb == null) cb = ASDocumentation.ParseComment(comments ?? name); - string tip = (UITools.Manager.ShowDetails) ? ASDocumentation.GetTipFullDetails(cb, null) : ASDocumentation.GetTipShortDetails(cb, null); + cb ??= ASDocumentation.ParseComment(comments ?? Label); + var tip = UITools.Manager.ShowDetails + ? ASDocumentation.GetTipFullDetails(cb, null) + : ASDocumentation.GetTipShortDetails(cb, null); // remove paragraphs from comments return ASDocumentation.RemoveHTMLTags(tip).Trim(); } } - public System.Drawing.Bitmap Icon - { - get { return (System.Drawing.Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_CONST); } - } + public Bitmap Icon => (Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_CONST); - public string Value - { - get { return name; } - } + public string Value => Label; } public class CompletionItemComparer : IComparer { - public int Compare(ICompletionListItem a, ICompletionListItem b) - { - return a.Label.CompareTo(b.Label); - } + public int Compare(ICompletionListItem a, ICompletionListItem b) => a.Label.CompareTo(b.Label); + } + + public class CompletionItemCaseSensitiveImportComparer : IComparer + { + public int Compare(ICompletionListItem x, ICompletionListItem y) => CaseSensitiveImportComparer.CompareImports(x.Label, y.Label); } #endregion - #region expressions_structures + #region expressions_structures public enum ComaExpression { None, @@ -4210,25 +5363,39 @@ public enum ComaExpression GenericIndexType } - /// - /// Parsed expression with it's function context - /// - sealed public class ASExpr - { - public int Position; + /// + /// Parsed expression with it's function context + /// + public sealed class ASExpr + { + /// + /// End position of expression + /// + public int Position; + + /// + /// Start position of expression + /// + public int PositionExpression; + public MemberModel ContextMember; public MemberList LocalVars; public MemberModel ContextFunction; public string FunctionBody; public int FunctionOffset; public bool BeforeBody; - - public int PositionExpression; - public string Value; + public string Value; public List SubExpressions; - public char Separator; - public string WordBefore; + public List SubExpressionPositions; + public string Separator; + public int SeparatorPosition; + public string WordBefore; + public int WordBeforePosition; public ComaExpression coma; + public string RightOperator = string.Empty; + + internal int LineFrom; + internal int LineTo; public ASExpr() { } @@ -4239,49 +5406,32 @@ public ASExpr(ASExpr inContext) LocalVars = inContext.LocalVars; FunctionBody = inContext.FunctionBody; } - } - - /// - /// Expressions/tokens evaluation result - /// - sealed public class ASResult - { - public ClassModel Type; + } + + /// + /// Expressions/tokens evaluation result + /// + public sealed class ASResult + { + public ClassModel Type; public ClassModel InClass; public ClassModel RelClass; public FileModel InFile; - public MemberModel Member; + public MemberModel Member; public bool IsStatic; public bool IsPackage; public ASExpr Context; - public String Path; - - public bool IsNull() - { - return (Type == null && Member == null && !IsPackage); - } - } + public string Path; - sealed class LastCharData - { - public int Value; - public int Position; - - public LastCharData(int val, int pos) - { - this.Value = val; - this.Position = pos; - } + public bool IsNull() => Type is null && Member is null && !IsPackage; } public sealed class ResolvedContext { + public readonly Hashtable Arguments = new Hashtable(); public int Position = -1; - public Hashtable Arguments = new Hashtable(); public ASResult Result; public ClassModel TokenType; } - #endregion -} - - + #endregion +} \ No newline at end of file diff --git a/External/Plugins/ASCompletion/Completion/ASDocumentation.cs b/External/Plugins/ASCompletion/Completion/ASDocumentation.cs index bb8b17bbe1..bf34a0e8e1 100644 --- a/External/Plugins/ASCompletion/Completion/ASDocumentation.cs +++ b/External/Plugins/ASCompletion/Completion/ASDocumentation.cs @@ -1,472 +1,296 @@ -/* - * Documentation completion/generation - */ - using System; -using System.Text; -using System.Collections; using System.Collections.Generic; +using System.Drawing; using System.Text.RegularExpressions; -using System.Diagnostics; +using ASCompletion.Context; +using ASCompletion.Model; using PluginCore; -using PluginCore.Managers; using PluginCore.Controls; -using ASCompletion.Model; -using ASCompletion.Context; using PluginCore.Localization; +using PluginCore.Managers; using PluginCore.Utilities; using ScintillaNet; namespace ASCompletion.Completion { - public class CommentBlock - { - public string Description; - public string InfoTip; - public string Return; - public ArrayList ParamName; // TODO: change ArrayList for List - public ArrayList ParamDesc; - public ArrayList TagName; - public ArrayList TagDesc; - } - - public class ASDocumentation - { - static private List docVariables; - static private BoxItem boxSimpleClose; - static private BoxItem boxMethodParams; - - #region regular_expressions - static private Regex re_splitFunction = new Regex("(?[\\w\\s]*)[\\s]function[\\s]*(?[^(]*)\\((?[^()]*)\\)(?.*)", - ASFileParserRegexOptions.SinglelineComment); - static private Regex re_property = new Regex("^(get|set)\\s", RegexOptions.Compiled); - static private Regex re_variableType = new Regex("[\\s]*:[\\s]*(?[\\w.?*]+)", ASFileParserRegexOptions.SinglelineComment); - static private Regex re_functionDeclaration = new Regex("[\\s\\w]*[\\s]function[\\s][\\s\\w$]+\\($", ASFileParserRegexOptions.SinglelineComment); - static private Regex re_tags = new Regex("<[/]?(p|br)[/]?>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - #endregion - - #region Comment generation - static ASDocumentation() - { - boxSimpleClose = new BoxItem(TextHelper.GetString("Label.CompleteDocEmpty")); - boxMethodParams = new BoxItem(TextHelper.GetString("Label.CompleteDocDetails")); - } - - static public bool OnChar(ScintillaControl Sci, int Value, int position, int style) - { - if (style == 3 || style == 124) - { - switch (Value) - { - // documentation tag - case '@': - return HandleDocTagCompletion(Sci); - - // documentation bloc - case '*': - if ((position > 2) && (Sci.CharAt(position-3) == '/') && (Sci.CharAt(position-2) == '*') - && ((position == 3) || (Sci.BaseStyleAt(position-4) != 3))) - HandleBoxCompletion(Sci, position); - break; - } - } - return false; - } - - static private void CompleteTemplate(string Context) - { - // get indentation - ScintillaControl Sci = ASContext.CurSciControl; - if (Sci == null) return; - int position = Sci.CurrentPos; - int line = Sci.LineFromPosition(position); - int indent = Sci.LineIndentPosition(line) - Sci.PositionFromLine(line); - string tab = Sci.GetLine(line).Substring(0, indent); - // get EOL - int eolMode = Sci.EOLMode; - string newline = LineEndDetector.GetNewLineMarker(eolMode); + public class CommentBlock + { + public string Description; + public string InfoTip; + public string Return; + public bool IsFunctionWithArguments; + public List ParamName; + public List ParamDesc; + public List TagName; + public List TagDesc; + } + + public class ASDocumentation + { + static List docVariables; + + #region regular_expressions - CommentBlockStyle cbs = PluginBase.Settings.CommentBlockStyle; - string star = cbs == CommentBlockStyle.Indented ? " *" : "*"; - string parInd = cbs == CommentBlockStyle.Indented ? "\t" : " "; - if (!PluginBase.MainForm.Settings.UseTabs) parInd = " "; - - // empty box - if (Context == null) + static readonly Regex re_tags = new Regex("<[/]?(p|br)[/]?>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + #endregion + + #region Comment generation + public static bool OnChar(ScintillaControl sci, int value, int position, int style) + { + if (style != 3 && style != 124) return false; + return value switch { - Sci.ReplaceSel(newline + tab + star + " " + newline + tab + star + "/"); - position += newline.Length + tab.Length + 1 + star.Length; - Sci.SetSel(position, position); - } + // documentation tag + '@' => HandleDocTagCompletion(sci), + // documentation bloc + '*' => ASContext.Context.DocumentationGenerator.ContextualGenerator(sci, position, new List()), + _ => false, + }; + } + + static bool HandleDocTagCompletion(ScintillaControl sci) + { + if (ASContext.CommonSettings.JavadocTags.IsNullOrEmpty()) return false; - // method details - else + string txt = sci.GetLine(sci.CurrentLine).TrimStart(); + if (!Regex.IsMatch(txt, "^\\*[\\s]*\\@")) + return false; + + // build tag list + if (docVariables is null) { - string box = newline + tab + star + " "; - Match mFun = re_splitFunction.Match(Context); - if (mFun.Success && !re_property.IsMatch(mFun.Groups["fname"].Value)) + docVariables = new List(); + foreach (string tag in ASContext.CommonSettings.JavadocTags) { - // parameters - MemberList list = ParseMethodParameters(mFun.Groups["params"].Value); - foreach (MemberModel param in list) - box += newline + tab + star + " @param" + parInd + param.Name; - // return type - Match mType = re_variableType.Match(mFun.Groups["type"].Value); - if (mType.Success && !mType.Groups["type"].Value.Equals("void", StringComparison.OrdinalIgnoreCase)) - box += newline + tab + star + " @return"; //+mType.Groups["type"].Value; - } - box += newline + tab + star + "/"; - Sci.ReplaceSel(box); - position += newline.Length + tab.Length + 1 + star.Length; - Sci.SetSel(position, position); + docVariables.Add(new TagItem(tag)); + } } - } - + + // show + CompletionList.Show(docVariables, true, ""); + return true; + } + /// - /// Returns parameters string as member list + /// Documentation tag template completion list item /// - /// Method parameters - /// Member list - static private MemberList ParseMethodParameters(string parameters) + class TagItem : ICompletionListItem { - MemberList list = new MemberList(); - if (parameters == null) - return list; - int p = parameters.IndexOf('('); - if (p >= 0) - parameters = parameters.Substring(p + 1, parameters.IndexOf(')') - p - 1); - parameters = parameters.Trim(); - if (parameters.Length == 0) - return list; - string[] sparam = parameters.Split(','); - string[] parType; - MemberModel param; - foreach (string pt in sparam) + public TagItem(string label) { - parType = pt.Split(':'); - param = new MemberModel(); - param.Name = parType[0].Trim(); - if (param.Name.Length == 0) - continue; - if (parType.Length == 2) param.Type = parType[1].Trim(); - else param.Type = ASContext.Context.Features.objectKey; - param.Flags = FlagType.Variable | FlagType.Dynamic; - list.Add(param); + Label = label; } - return list; - } - - static private bool HandleDocTagCompletion(ScintillaControl Sci) - { - if (ASContext.CommonSettings.JavadocTags == null || ASContext.CommonSettings.JavadocTags.Length == 0) - return false; - string txt = Sci.GetLine(Sci.LineFromPosition(Sci.CurrentPos)).TrimStart(); - if (!Regex.IsMatch(txt, "^\\*[\\s]*\\@")) - return false; - - // build tag list - if (docVariables == null) - { - docVariables = new List(); - TagItem item; - foreach (string tag in ASContext.CommonSettings.JavadocTags) - { - item = new TagItem(tag); - docVariables.Add(item); - } - } - - // show - CompletionList.Show(docVariables, true, ""); - return true; - } - - static private bool HandleBoxCompletion(ScintillaControl Sci, int position) - { - // is the block before a function declaration? - int len = Sci.TextLength-1; - char c; - StringBuilder sb = new StringBuilder(); - while (position < len) - { - c = (char)Sci.CharAt(position); - sb.Append(c); - if (c == '(' || c == ';' || c == '{' || c == '}') break; - position++; - } - string signature = sb.ToString(); - if (re_functionDeclaration.IsMatch(signature)) - { - // get method signature - position++; - while (position < len) - { - c = (char)Sci.CharAt(position); - sb.Append(c); - if (c == ';' || c == '{') break; - position++; - } - signature = sb.ToString(); - } - else signature = null; - - // build templates list - List templates = new List(); - if (signature != null) - { - boxMethodParams.Context = signature; - templates.Add(boxMethodParams); - } - templates.Add(boxSimpleClose); - - // show - CompletionList.Show(templates, true, ""); - return true; - } - - - /// - /// Box template completion list item - /// - private class BoxItem : ICompletionListItem - { - private string label; - public string Context; - - public BoxItem(string label) - { - this.label = label; - } - - public string Label { - get { return label; } - } - public string Description { - get { return TextHelper.GetString("Label.DocBoxTemplate"); } - } - - public System.Drawing.Bitmap Icon { - get { return (System.Drawing.Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_TEMPLATE); } - } - - public string Value { - get { - ASDocumentation.CompleteTemplate(Context); - return null; - } - } - } - - /// - /// Documentation tag template completion list item - /// - private class TagItem : ICompletionListItem - { - private string label; - - public TagItem(string label) - { - this.label = label; - } - - public string Label { - get { return label; } - } - public string Description { - get { return TextHelper.GetString("Label.DocTagTemplate"); } - } - - public System.Drawing.Bitmap Icon { - get { return (System.Drawing.Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_DECLARATION); } - } - - public string Value { - get { return label; } - } - } - #endregion - - #region Tooltips + public string Label { get; } - static private Regex reNewLine = new Regex("[\r\n]+", RegexOptions.Compiled); - static private Regex reKeepTags = new Regex("<([/]?(b|i|s|u))>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - static private Regex reSpecialTags = new Regex("<([/]?)(code|small|strong|em)>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - static private Regex reStripTags = new Regex("<[/]?[a-z]+>", RegexOptions.IgnoreCase | RegexOptions.Compiled); - static private Regex reDocTags = new Regex("\n@(?[a-z]+)\\s", RegexOptions.IgnoreCase | RegexOptions.Compiled); - static private Regex reSplitParams = new Regex("(?[\\w$]+)\\s", RegexOptions.Compiled); + public string Description => TextHelper.GetString("Label.DocTagTemplate"); - static public CommentBlock ParseComment(string comment) - { - // cleanup - comment = comment.Replace("<", "<").Replace(">", ">"); + public Bitmap Icon => (Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_DECLARATION); + + public string Value => Label; + } + #endregion + + #region Tooltips + + static readonly Regex reNewLine = new Regex("[\r\n]+", RegexOptions.Compiled); + static readonly Regex reKeepTags = new Regex("<([/]?(b|i|s|u))>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + static readonly Regex reSpecialTags = new Regex("<([/]?)(code|small|strong|em)>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + static readonly Regex reStripTags = new Regex("<[/]?[a-z]+[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Compiled); + static readonly Regex reDocTags = new Regex("\n@(?[a-z]+)\\s", RegexOptions.IgnoreCase | RegexOptions.Compiled); + static readonly Regex reSplitParams = new Regex("(?[\\w$]+)\\s", RegexOptions.Compiled); + + public static CommentBlock ParseComment(string comment) + { + // cleanup + comment = comment.Replace("<", "<").Replace(">", ">").Replace(" ", " "); comment = reKeepTags.Replace(comment, "[$1]"); comment = reSpecialTags.Replace(comment, match => { string tag = match.Groups[2].Value; bool open = match.Groups[1].Length == 0; - switch (tag) + return tag switch { - case "small": return open ? "[size=-2]" : "[/size]"; - case "code": return open ? "[font=Courier New]" : "[/font]"; - case "strong": return open ? "[b]" : "[/b]"; - case "em": return open ? "[i]" : "[/i]"; - } - return ""; + "small" => open ? "[size=-2]" : "[/size]", + "code" => open ? "[font=Courier New]" : "[/font]", + "strong" => open ? "[b]" : "[/b]", + "em" => open ? "[i]" : "[/i]", + _ => "", + }; }); comment = reStripTags.Replace(comment, ""); - string[] lines = reNewLine.Split(comment); - char[] trim = new char[] { ' ', '\t', '*' }; + string[] lines = reNewLine.Split(comment); + char[] trim = { ' ', '\t', '*' }; bool addNL = false; comment = ""; foreach (string line in lines) - { + { string temp = line.Trim(trim); if (addNL) comment += '\n' + temp; - else { comment += temp; addNL = true; } - } - // extraction - CommentBlock cb = new CommentBlock(); + else + { + comment += temp; + addNL = true; + } + } + // extraction + CommentBlock cb = new CommentBlock(); MatchCollection tags = reDocTags.Matches(comment); - - if (tags.Count == 0) - { - cb.Description = comment.Trim(); - return cb; - } - - if (tags[0].Index > 0) cb.Description = comment.Substring(0, tags[0].Index).Trim(); - else cb.Description = ""; - cb.TagName = new ArrayList(); - cb.TagDesc = new ArrayList(); - - Group gTag; - for(int i=0; i 0 + ? comment.Substring(0, tags[0].Index).Trim() + : string.Empty; + cb.TagName = new List(); + cb.TagDesc = new List(); + + for(int i = 0; i < tags.Count; i++) + { + var gTag = tags[i].Groups["tag"]; + string tag = gTag.Value; + int start = gTag.Index+gTag.Length; + int end = (i(); + cb.ParamDesc = new List(); + } + cb.ParamName.Add(mVar.Value); cb.ParamDesc.Add(desc.Substring(mVar.Index + mVar.Length).TrimStart()); - } - } - else if (tag == "return") - { - cb.Return = desc; - } - else if (tag == "infotip") - { - cb.InfoTip = desc; - if (cb.Description.Length == 0) cb.Description = cb.InfoTip; - } - cb.TagName.Add(tag); - cb.TagDesc.Add(desc); - } - return cb; - - } - - static public string GetTipDetails(MemberModel member, string highlightParam) - { - try - { + } + } + else if (tag == "return") + { + cb.Return = desc; + } + else if (tag == "infotip") + { + cb.InfoTip = desc; + if (cb.Description.Length == 0) cb.Description = cb.InfoTip; + } + cb.TagName.Add(tag); + cb.TagDesc.Add(desc); + } + return cb; + + } + + public static string GetTipDetails(MemberModel member, string highlightParam) + { + try + { string tip = (UITools.Manager.ShowDetails) ? GetTipFullDetails(member, highlightParam) : GetTipShortDetails(member, highlightParam); // remove paragraphs from comments return RemoveHTMLTags(tip); - } - catch(Exception ex) - { - ErrorManager.ShowError(/*"Error while parsing comments.\n"+ex.Message,*/ ex); - return ""; - } - } + } + catch(Exception ex) + { + ErrorManager.ShowError(/*"Error while parsing comments.\n"+ex.Message,*/ ex); + return ""; + } + } + + public static string RemoveHTMLTags(string tip) => re_tags.Replace(tip, ""); - static public string RemoveHTMLTags(string tip) + /// + /// Short contextual details to display in tips + /// + /// Member data + /// Parameter to detail + /// + public static string GetTipShortDetails(MemberModel member, string highlightParam) { - return re_tags.Replace(tip, ""); - } - - /// - /// Short contextual details to display in tips - /// - /// Member data - /// Parameter to detail - /// - static public string GetTipShortDetails(MemberModel member, string highlightParam) - { - if (member == null || member.Comments == null || !ASContext.CommonSettings.SmartTipsEnabled) return ""; - CommentBlock cb = ParseComment(member.Comments); + if (member?.Comments is null || !ASContext.CommonSettings.SmartTipsEnabled) return ""; + var cb = ParseComment(member.Comments); + cb.IsFunctionWithArguments = IsFunctionWithArguments(member); return " \u2026" + GetTipShortDetails(cb, highlightParam); } + static bool IsFunctionWithArguments(MemberModel member) + { + return member != null && (member.Flags & FlagType.Function) > 0 + && !member.Parameters.IsNullOrEmpty(); + } + /// /// Short contextual details to display in tips /// /// Parsed comments /// Formated comments - static public string GetTipShortDetails(CommentBlock cb, string highlightParam) + public static string GetTipShortDetails(CommentBlock cb, string highlightParam) { - string details = ""; - - // get parameter detail - if (highlightParam != null && highlightParam.Length > 0 && cb.ParamName != null) - { - for(int i=0; i 0) details += "\n"+cb.InfoTip; - else if (cb.Description != null && cb.Description.Length > 0) - details += Get2LinesOf(cb.Description); - } - return details; - } + { + if (!string.IsNullOrEmpty(cb.InfoTip)) + details += "\n"+cb.InfoTip; + else if (!string.IsNullOrEmpty(cb.Description)) + details += Get2LinesOf(cb.Description, cb.IsFunctionWithArguments); + } + + return details; + } + + static string GetShortcutDocs() + { + Color themeForeColor = PluginBase.MainForm.GetThemeColor("MethodCallTip.InfoColor"); + string foreColorString = themeForeColor != Color.Empty ? DataConverter.ColorToHex(themeForeColor).Replace("0x", "#") : "#666666:MULTIPLY"; + return "\n[COLOR=" + foreColorString + "][i](" + TextHelper.GetString("Info.ShowDetails") + ")[/i][/COLOR]"; + } /// /// Split multiline text and return 2 lines or less of text /// - static public string Get2LinesOf(string text) + public static string Get2LinesOf(string text) => Get2LinesOf(text, false); + + public static string Get2LinesOf(string text, bool alwaysAddShortcutDocs) { string[] lines = text.Split('\n'); text = ""; int n = Math.Min(lines.Length, 2); for (int i = 0; i < n; i++) text += "\n" + lines[i]; - if (lines.Length > 2) text += " \x86"; + if (lines.Length > 2 || alwaysAddShortcutDocs) text += " \x86" + GetShortcutDocs(); return text; } - - /// - /// Extract member comments for display in the completion list - /// - /// Member data + + /// + /// Extract member comments for display in the completion list + /// + /// Member data /// Parameter to highlight - /// Formated comments - static public string GetTipFullDetails(MemberModel member, string highlightParam) - { - if (member == null || member.Comments == null || !ASContext.CommonSettings.SmartTipsEnabled) return ""; - CommentBlock cb = ParseComment(member.Comments); + /// Formatted comments + public static string GetTipFullDetails(MemberModel member, string highlightParam) + { + if (member?.Comments is null || !ASContext.CommonSettings.SmartTipsEnabled) return ""; + var cb = ParseComment(member.Comments); + cb.IsFunctionWithArguments = IsFunctionWithArguments(member); return GetTipFullDetails(cb, highlightParam); } @@ -475,56 +299,55 @@ static public string GetTipFullDetails(MemberModel member, string highlightParam /// /// Parsed comments /// Formated comments - static public string GetTipFullDetails(CommentBlock cb, string highlightParam) + public static string GetTipFullDetails(CommentBlock cb, string highlightParam) { - string details = ""; - if (cb.Description.Length > 0) - { - string[] lines = cb.Description.Split('\n'); + string details = ""; + if (cb.Description.Length > 0) + { + string[] lines = cb.Description.Split('\n'); int n = Math.Min(lines.Length, ASContext.CommonSettings.DescriptionLinesLimit); - for(int i=0; i ASContext.CommonSettings.DescriptionLinesLimit) details = details.TrimEnd() + " \u2026\n"; - } - - // @usage - if (cb.TagName != null) - { - bool hasUsage = false; - for(int i=0; i 0) - { - details += "\nParam:"; - for(int i=0; i[a-z_0-9.\\\"']+)\\s*,\\s*(this\\.)?{0}"; + + internal const string patternEvent = "Listener\\s*\\((\\s*([a-z_0-9.\\\"']+)\\s*,)?\\s*(?[a-z_0-9.\\\"']+)\\s*,\\s*(this\\.)?{0}"; const string patternAS2Delegate = @"\.\s*create\s*\(\s*[a-z_0-9.]+,\s*{0}"; const string patternVarDecl = @"\s*{0}\s*:\s*{1}"; const string patternMethod = @"{0}\s*\("; const string patternMethodDecl = @"function\s+{0}\s*\("; const string patternClass = @"new\s*{0}"; const string BlankLine = "$(Boundary)\n\n"; - const string NewLine = "$(Boundary)\n"; - static private Regex reModifiers = new Regex("^\\s*(\\$\\(Boundary\\))?([a-z ]+)(function|var|const)", RegexOptions.Compiled); - static private Regex reModifier = new Regex("(public |private |protected )", RegexOptions.Compiled); - - static private string contextToken; - static private string contextParam; - static private Match contextMatch; - static private ASResult contextResolved; - static private MemberModel contextMember; - static private bool firstVar; - static private bool isHaxe; - - static public bool HandleGeneratorCompletion(ScintillaNet.ScintillaControl Sci, bool autoHide, string word) - { - ContextFeatures features = ASContext.Context.Features; - if (features.overrideKey != null && word == features.overrideKey) - return HandleOverrideCompletion(Sci, autoHide); - return false; - } + protected internal const string NewLine = "$(Boundary)\n"; + static readonly Regex reModifiers = new Regex("^\\s*(\\$\\(Boundary\\))?([a-z ]+)(function|var|const)", RegexOptions.Compiled); + static readonly Regex reSuperCall = new Regex("^super\\s*\\(", RegexOptions.Compiled); + + protected internal static string contextToken; + internal static string contextParam; + internal static Match contextMatch; + internal static ASResult contextResolved; + internal static MemberModel contextMember; + static bool firstVar; - static public void ContextualGenerator(ScintillaNet.ScintillaControl Sci) + readonly CodeGeneratorInterfaceBehavior codeGeneratorInterfaceBehavior = new CodeGeneratorInterfaceBehavior(); + + protected virtual ICodeGeneratorBehavior GetCodeGeneratorBehavior() { - if (ASContext.Context is ASContext) - (ASContext.Context as ASContext).UpdateCurrentFile(false); // update model + return (ASContext.Context.CurrentClass.Flags & FlagType.Interface) != 0 + ? codeGeneratorInterfaceBehavior + : null; + } - if ((ASContext.Context.CurrentClass.Flags & (FlagType.Enum | FlagType.Interface | FlagType.TypeDef)) > 0) - return; + static bool IsHaxe => ASContext.Context.CurrentModel.haXe; + + public static bool HandleGeneratorCompletion(ScintillaControl sci, bool autoHide, string word) + => !string.IsNullOrEmpty(word) + && word == ASContext.Context.Features.overrideKey + && ASContext.Context.CodeGenerator is ASGenerator generator + && generator.HandleOverrideCompletion(autoHide); + + public static void ContextualGenerator(ScintillaControl sci, List options) + => ASContext.Context.CodeGenerator.ContextualGenerator(sci, sci.CurrentPos, options); + + public bool ContextualGenerator(ScintillaControl sci, int position, List options) + { + if (sci.SelTextSize != 0) return false; + if (ASContext.Context is ASContext ctx) ctx.UpdateCurrentFile(false); lookupPosition = -1; - int position = Sci.CurrentPos; - if (Sci.BaseStyleAt(position) == 19) // on keyword - return; - int line = Sci.LineFromPosition(position); - contextToken = Sci.GetWordFromPosition(position); + if (sci.PositionIsOnComment(position) + // for example: new NewClass$(EntryPoint)/*comment*/(); + && sci.PositionIsOnComment(--position)) return false; + var style = sci.BaseStyleAt(position); + if (style == 19 || style == 24) // on keyword + return false; contextMatch = null; - isHaxe = ASContext.Context.Settings.LanguageId == "HAXE"; + contextToken = sci.GetWordFromPosition(position); + var expr = ASComplete.GetExpressionType(sci, sci.WordEndPosition(position, true)); + contextResolved = expr; + ContextualGenerator(sci, position, expr, options); + return true; + } + + protected virtual void ContextualGenerator(ScintillaControl sci, int position, ASResult resolve, List options) + { + var suggestItemDeclaration = false; + var ctx = ASContext.Context; + var line = sci.LineFromPosition(position); + var found = GetDeclarationAtLine(line); + if (contextToken is not null && resolve.Member is null && sci.BaseStyleAt(position) != 5) + { + // import declaration + if ((resolve.Type is null || resolve.Type.IsVoid() || !ctx.IsImported(resolve.Type, line)) && CheckAutoImport(resolve, options)) return; + if (resolve.Type is null) + { + if (TryShowGenerateType(sci, position, resolve, found, options)) return; + suggestItemDeclaration = ASComplete.IsTextStyle(sci.BaseStyleAt(position - 1)); + } + } - FoundDeclaration found = GetDeclarationAtLine(Sci, line); - string text = Sci.GetLine(line); - bool suggestItemDeclaration = false; + var behavior = GetCodeGeneratorBehavior(); + if (behavior is not null && behavior.ContextualGenerator(sci, position, resolve, options)) return; - if (!String.IsNullOrEmpty(contextToken) && Char.IsDigit(contextToken[0])) + if (CanShowConvertToConst(sci, position, resolve, found)) { - ShowConvertToConst(found); + ShowConvertToConst(found, options); return; } - ASResult resolve = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(position, true)); - contextResolved = resolve; - // ignore automatic vars (MovieClip members) - if (resolve.Member != null && - (((resolve.Member.Flags & FlagType.AutomaticVar) > 0) - || (resolve.InClass != null && resolve.InClass.QualifiedName == "Object"))) + if (resolve.Member is not null && ((resolve.Member.Flags & FlagType.AutomaticVar) > 0 || resolve.InClass?.QualifiedName == "Object")) { resolve.Member = null; resolve.Type = null; } - if (found.inClass != ClassModel.VoidClass && contextToken != null) + if (!found.InClass.IsVoid() && contextToken is not null) { - if (resolve.Member == null && resolve.Type != null - && (resolve.Type.Flags & FlagType.Interface) > 0) // implement interface + // implement interface + if (CanShowImplementInterfaceList(sci, position, resolve, found)) { - contextParam = resolve.Type.Type; - ShowImplementInterface(found); + if (ctx.Features.hasGenerics && resolve.RelClass?.Implements is not null) + { + var name = resolve.Type.Name; + foreach (var it in resolve.RelClass.Implements) + { + string interfaceName; + if (it.IndexOf('<') is { } p && p != -1) interfaceName = it.Substring(0, p); + else interfaceName = it; + if (interfaceName != name) continue; + contextParam = it; + break; + } + } + else contextParam = resolve.Type.Type; + ShowImplementInterface(found, options); return; } - - if (resolve.Member != null && !ASContext.Context.CurrentClass.IsVoid() - && (resolve.Member.Flags & FlagType.LocalVar) > 0) // promote to class var + // promote to class var + if (!ctx.CurrentClass.IsVoid() && resolve.Member is not null && (resolve.Member.Flags & FlagType.LocalVar) > 0) { contextMember = resolve.Member; - ShowPromoteLocalAndAddParameter(found); + ShowPromoteLocalAndAddParameter(found, options); return; } } - - if (contextToken != null) - { - if (resolve.Member == null) // import declaration - { - if ((resolve.Type == null || resolve.Type.IsVoid() || !ASContext.Context.IsImported(resolve.Type, line)) && CheckAutoImport(found)) - { - return; - } - else if (resolve.Type == null) - { - int stylemask = (1 << Sci.StyleBits) - 1; - if (ASComplete.IsTextStyle(Sci.StyleAt(position - 1) & stylemask)) - { - suggestItemDeclaration = true; - } - } - } - } - - if (found.member != null) + + if (found.Member is not null) { // private var -> property - if ((found.member.Flags & FlagType.Variable) > 0 && (found.member.Flags & FlagType.LocalVar) == 0) + if ((found.Member.Flags & FlagType.Variable) > 0 && (found.Member.Flags & FlagType.LocalVar) == 0) { + var text = sci.GetLine(line); // maybe we just want to import the member's non-imported type - Match m = Regex.Match(text, String.Format(patternVarDecl, found.member.Name, contextToken)); + var m = Regex.Match(text, string.Format(patternVarDecl, found.Member.Name, contextToken)); if (m.Success) { contextMatch = m; - ClassModel type = ASContext.Context.ResolveType(contextToken, ASContext.Context.CurrentModel); - if (type.IsVoid() && CheckAutoImport(found)) - return; + var type = ctx.ResolveType(contextToken, ctx.CurrentModel); + if (type.IsVoid() && CheckAutoImport(resolve, options)) return; } - // create property - ShowGetSetList(found); + if (CanShowGetSetList(sci, position, resolve, found)) ShowGetSetList(found, options); return; } // inside a function - else if ((found.member.Flags & (FlagType.Function | FlagType.Getter | FlagType.Setter)) > 0 - && resolve.Member == null && resolve.Type == null) + if ((found.Member.Flags & (FlagType.Function | FlagType.Getter | FlagType.Setter)) > 0 + && resolve.Member is null && resolve.Type is null) { - if (contextToken != null) + if (CanShowGenerateGetter(sci, position, resolve, found)) + { + ShowGetterList(found, options); + return; + } + if (CanShowGenerateSetter(sci, position, resolve, found)) + { + ShowSetterList(found, options); + return; + } + var text = sci.GetLine(line); + if (contextToken is not null) { // "generate event handlers" suggestion - string re = String.Format(patternEvent, contextToken); - Match m = Regex.Match(text, re, RegexOptions.IgnoreCase); + var re = string.Format(patternEvent, contextToken); + var m = Regex.Match(text, re, RegexOptions.IgnoreCase); if (m.Success) { contextMatch = m; - contextParam = CheckEventType(m.Groups["event"].Value); - ShowEventList(found); + var pos = ASComplete.ExpressionEndPosition(sci, sci.PositionFromLine(line) + m.Index); + var expr = ASComplete.GetExpressionType(sci, pos, false, true); + contextParam = ((ASGenerator) ctx.CodeGenerator).CheckEventType(expr.Member, m.Groups["event"].Value); + ShowEventList(found, options); return; } - m = Regex.Match(text, String.Format(patternAS2Delegate, contextToken), RegexOptions.IgnoreCase); + m = Regex.Match(text, string.Format(patternAS2Delegate, contextToken), RegexOptions.IgnoreCase); if (m.Success) { contextMatch = m; - ShowDelegateList(found); + ShowDelegateList(found, options); return; } // suggest delegate - if (ASContext.Context.Features.hasDelegates) + if (ctx.Features.hasDelegates) { m = Regex.Match(text, @"([a-z0-9_.]+)\s*\+=\s*" + contextToken, RegexOptions.IgnoreCase); if (m.Success) { - int offset = Sci.PositionFromLine(Sci.LineFromPosition(position)) + int offset = sci.PositionFromLine(sci.LineFromPosition(position)) + m.Groups[1].Index + m.Groups[1].Length; - resolve = ASComplete.GetExpressionType(Sci, offset); - if (resolve.Member != null) + resolve = ASComplete.GetExpressionType(sci, offset); + if (resolve.Member is not null) contextMember = ResolveDelegate(resolve.Member.Type, resolve.InFile); contextMatch = m; - ShowDelegateList(found); + ShowDelegateList(found, options); return; } } @@ -185,41 +218,41 @@ static public void ContextualGenerator(ScintillaNet.ScintillaControl Sci) else { // insert a default handler name, then "generate event handlers" suggestion - Match m = Regex.Match(text, String.Format(patternEvent, ""), RegexOptions.IgnoreCase); + var m = Regex.Match(text, string.Format(patternEvent, ""), RegexOptions.IgnoreCase); if (m.Success) { - int regexIndex = m.Index + Sci.PositionFromLine(Sci.LineFromPosition(Sci.CurrentPos)); - GenerateDefaultHandlerName(Sci, position, regexIndex, m.Groups["event"].Value, true); - resolve = ASComplete.GetExpressionType(Sci, Sci.CurrentPos); - if (resolve.Member == null || (resolve.Member.Flags & FlagType.AutomaticVar) > 0) + int regexIndex = m.Index + sci.PositionFromLine(sci.CurrentLine); + GenerateDefaultHandlerName(sci, position, regexIndex, m.Groups["event"].Value, true); + resolve = ASComplete.GetExpressionType(sci, sci.CurrentPos); + if (resolve.Member is null || (resolve.Member.Flags & FlagType.AutomaticVar) > 0) { contextMatch = m; contextParam = CheckEventType(m.Groups["event"].Value); - ShowEventList(found); + ShowEventList(found, options); } return; } // insert default delegate name, then "generate delegate" suggestion - if (ASContext.Context.Features.hasDelegates) + if (ctx.Features.hasDelegates) { m = Regex.Match(text, @"([a-z0-9_.]+)\s*\+=\s*", RegexOptions.IgnoreCase); if (m.Success) { - int offset = Sci.PositionFromLine(Sci.LineFromPosition(position)) + int offset = sci.PositionFromLine(sci.LineFromPosition(position)) + m.Groups[1].Index + m.Groups[1].Length; - resolve = ASComplete.GetExpressionType(Sci, offset); - if (resolve.Member != null) + resolve = ASComplete.GetExpressionType(sci, offset); + if (resolve.Member is not null) { contextMember = ResolveDelegate(resolve.Member.Type, resolve.InFile); - string delegateName = resolve.Member.Name; - if (delegateName.StartsWith("on")) delegateName = delegateName.Substring(2); - GenerateDefaultHandlerName(Sci, position, offset, delegateName, false); - resolve = ASComplete.GetExpressionType(Sci, Sci.CurrentPos); - if (resolve.Member == null || (resolve.Member.Flags & FlagType.AutomaticVar) > 0) + var delegateName = resolve.Member.Name; + if (delegateName.StartsWithOrdinal("on")) delegateName = delegateName.Substring(2); + GenerateDefaultHandlerName(sci, position, offset, delegateName, false); + resolve = ASComplete.GetExpressionType(sci, sci.CurrentPos); + if (resolve.Member is null || (resolve.Member.Flags & FlagType.AutomaticVar) > 0) { contextMatch = m; - ShowDelegateList(found); + ShowDelegateList(found, options); } return; } @@ -229,74 +262,55 @@ static public void ContextualGenerator(ScintillaNet.ScintillaControl Sci) } // "Generate fields from parameters" suggestion - if (found.member != null - && (found.member.Flags & FlagType.Function) > 0 - && found.member.Parameters != null && (found.member.Parameters.Count > 0) - && resolve.Member != null && (resolve.Member.Flags & FlagType.ParameterVar) > 0) + if ((found.Member.Flags & FlagType.Function) > 0 + && !found.Member.Parameters.IsNullOrEmpty() + && resolve.Member is not null && (resolve.Member.Flags & FlagType.ParameterVar) > 0) { contextMember = resolve.Member; - ShowFieldFromParameter(found); + ShowFieldFromParameter(found, options); return; } // "add to interface" suggestion - if (resolve.Member != null && - resolve.Member.Name == found.member.Name && - line == found.member.LineFrom && - ((found.member.Flags & FlagType.Function) > 0 - || (found.member.Flags & FlagType.Getter) > 0 - || (found.member.Flags & FlagType.Setter) > 0) && - found.inClass != null && - found.inClass.Implements != null && - found.inClass.Implements.Count > 0) + if (CanShowAddToInterfaceList(sci, position, resolve, found)) { - string funcName = found.member.Name; - - List interfaces = new List(); - foreach (string interf in found.inClass.Implements) + var name = found.Member.Name; + var flags = found.Member.Flags & ~FlagType.Access; + var list = new List(); + foreach (var it in found.InClass.Implements) { - bool skip = false; - ClassModel cm = ASContext.Context.ResolveType(interf, ASContext.Context.CurrentModel); - MemberList members = cm.Members; - foreach (MemberModel m in members) - { - if (m.Name.Equals(funcName)) - { - skip = true; - break; - } - } - if (!skip) - { - interfaces.Add(interf); - } + var cm = ctx.ResolveType(it, ctx.CurrentModel); + if (!cm.ContainsMember(name, flags, false)) list.Add(it); } - if (interfaces.Count > 0) + if (list.Count > 0) { - ShowAddInterfaceDefList(found, interfaces); + ShowAddInterfaceDefList(found, list, options); return; } } - // "assign var to statement" suggestion - int curLine = Sci.LineFromPosition(Sci.CurrentPos); - string ln = Sci.GetLine(curLine); - if (ln.Trim().Length > 0 && ln.TrimEnd().Length <= Sci.CurrentPos - Sci.PositionFromLine(curLine) && ln.IndexOf("=") == -1) - { - ShowAssignStatementToVarList(found); + var curLine = sci.GetLine(sci.CurrentLine); + var ln = curLine.TrimEnd(); + if (ln.Length > 0 + && sci.PositionFromLine(sci.CurrentLine) is var positionFromLine + && ln.Length <= sci.CurrentPos - positionFromLine) // cursor at end of line + { + var returnType = GetStatementReturnType(sci, found.InClass, curLine, positionFromLine); + if (!CanShowAssignStatementToVariable(sci, returnType.Resolve)) return; + if (CanShowGenerateClass(sci, position, resolve, found)) ShowGenerateClassList(found, returnType.Resolve.Context, options); + else if (returnType.Resolve.Type is null && returnType.Resolve.Member is null) return; + else ShowAssignStatementToVarList(found, returnType, options); return; } } // suggest generate constructor / toString - if (found.member == null && found.inClass != ClassModel.VoidClass && contextToken == null) + if (CanShowGenerateConstructorAndToString(sci, position, resolve, found)) { - MemberList members = ASContext.Context.CurrentClass.Members; - bool hasConstructor = false; bool hasToString = false; - foreach (MemberModel m in members) + foreach (MemberModel m in ctx.CurrentClass.Members) { if (!hasConstructor && (m.Flags & FlagType.Constructor) > 0) hasConstructor = true; @@ -307,33 +321,34 @@ static public void ContextualGenerator(ScintillaNet.ScintillaControl Sci) if (!hasConstructor || !hasToString) { - ShowConstructorAndToStringList(found, hasConstructor, hasToString); + ShowConstructorAndToStringList(found, hasConstructor, hasToString, options); return; } } - if (resolve.Member != null - && resolve.Type != null - && resolve.Type.QualifiedName == "String" - && found.inClass != null) + if (resolve.Member is not null + && resolve.Type is not null + && resolve.Type.QualifiedName == ctx.Features.stringKey + && !found.InClass.IsVoid()) { - int lineStartPos = Sci.PositionFromLine(Sci.LineFromPosition(Sci.CurrentPos)); - string lineStart = text.Substring(0, Sci.CurrentPos - lineStartPos); - Match m = Regex.Match(lineStart, String.Format(@"new\s+(?\w+)\s*\(\s*\w+", lineStart)); + int lineStartPos = sci.PositionFromLine(sci.CurrentLine); + var text = sci.GetLine(line); + var lineStart = text.Substring(0, sci.CurrentPos - lineStartPos); + var m = Regex.Match(lineStart, @"new\s+(?\w+)\s*\(\s*\w+"); if (m.Success) { - Group g = m.Groups["event"]; - ASResult eventResolve = ASComplete.GetExpressionType(Sci, lineStartPos + g.Index + g.Length); - if (eventResolve != null && eventResolve.Type != null) + var g = m.Groups["event"]; + var eventResolve = ASComplete.GetExpressionType(sci, lineStartPos + g.Index + g.Length); + if (eventResolve?.Type is not null) { - ClassModel aType = eventResolve.Type; + var aType = eventResolve.Type; aType.ResolveExtends(); while (!aType.IsVoid() && aType.QualifiedName != "Object") { if (aType.QualifiedName == "flash.events.Event") { contextParam = eventResolve.Type.QualifiedName; - ShowEventMetatagList(found); + ShowEventMetatagList(found, options); return; } aType = aType.Extends; @@ -341,557 +356,748 @@ static public void ContextualGenerator(ScintillaNet.ScintillaControl Sci) } } } - + // suggest declaration - if (contextToken != null) + if (contextToken is not null) { if (suggestItemDeclaration) { - Match m = Regex.Match(text, String.Format(patternClass, contextToken)); - if (m.Success) + var text = sci.GetLine(line); + Match m; + if (CanShowGenerateClass(sci, position, resolve, found) + && (m = Regex.Match(text, string.Format(patternClass, contextToken))).Success) { contextMatch = m; - ShowNewClassList(found); + ShowGenerateClassList(found, options); } - else if (!found.inClass.IsVoid()) + else if (!found.InClass.IsVoid()) { - m = Regex.Match(text, String.Format(patternMethod, contextToken)); + m = Regex.Match(text, string.Format(patternMethod, contextToken)); if (m.Success) { - contextMatch = m; - ShowNewMethodList(found); + if (CanShowNewMethodList(sci, position, resolve, found)) + { + contextMatch = m; + ((ASGenerator) ctx.CodeGenerator).ShowNewMethodList(sci, resolve, found, options); + } + } + else + { + if (CanShowNewVarList(sci, position, resolve, found)) ((ASGenerator) ctx.CodeGenerator).ShowNewVarList(sci, resolve, found, options); + if (CanShowGenerateInterface(sci, position, resolve, found)) ShowGenerateInterfaceList(resolve, found, options); } - else ShowNewVarList(found); } } - else + else if (resolve.Member is not null + && (resolve.Member.Flags & FlagType.Function) != 0 + && resolve.InClass?.InFile.FileName is {} classFileName + && File.Exists(classFileName) + && !classFileName.StartsWithOrdinal(PathHelper.AppDir)) { - if (resolve != null - && resolve.InClass != null - && resolve.InClass.InFile != null - && resolve.Member != null - && (resolve.Member.Flags & FlagType.Function) > 0 - && File.Exists(resolve.InClass.InFile.FileName) - && !resolve.InClass.InFile.FileName.StartsWith(PathHelper.AppDir)) + var text = sci.GetLine(line); + var m1 = Regex.Match(text, string.Format(patternMethodDecl, contextToken)); + if (!m1.Success && Regex.IsMatch(text, string.Format(patternMethod, contextToken))) { - Match m = Regex.Match(text, String.Format(patternMethodDecl, contextToken)); - Match m2 = Regex.Match(text, String.Format(patternMethod, contextToken)); - if (!m.Success && m2.Success) - { - contextMatch = m; - ShowChangeMethodDeclList(found); - } + contextMatch = m1; + ShowChangeMethodDeclList(found, options); } - else if (resolve != null - && resolve.Type != null - && resolve.Type.InFile != null - && resolve.RelClass != null - && File.Exists(resolve.Type.InFile.FileName) - && !resolve.Type.InFile.FileName.StartsWith(PathHelper.AppDir)) + } + else if (resolve.RelClass is not null + && resolve.Type?.InFile.FileName is {} typeFileName + && File.Exists(typeFileName) + && !typeFileName.StartsWithOrdinal(PathHelper.AppDir)) + { + var text = sci.GetLine(line); + var m = Regex.Match(text, string.Format(patternClass, contextToken)); + if (m.Success) { - Match m = Regex.Match(text, String.Format(patternClass, contextToken)); - if (m.Success) + contextMatch = m; + var type = resolve.Type; + var constructor = type.SearchMember(FlagType.Constructor, true); + if (constructor is null) ShowConstructorAndToStringList(new FoundDeclaration {InClass = resolve.Type}, false, true, options); + else { - contextMatch = m; - ShowChangeConstructorDeclList(found); + var constructorParametersCount = constructor.Parameters?.Count ?? 0; + var wordEndPosition = sci.WordEndPosition(sci.CurrentPos, true); + var parameters = ParseFunctionParameters(sci, wordEndPosition); + if (parameters.Count != constructorParametersCount) ShowChangeConstructorDeclarationList(found, parameters, options); + else + { + for (var i = 0; i < parameters.Count; i++) + { + if (parameters[i].paramType == constructor.Parameters[i].Type) continue; + ShowChangeConstructorDeclarationList(found, parameters, options); + break; + } + } } } } } - + } + + /// + /// Check if "Assign statement to variable" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Expression at cursor position + /// true, if can show "Assign statement to variable" list + protected virtual bool CanShowAssignStatementToVariable(ScintillaControl sci, ASResult expr) + { + // for example: return expr + if (expr.Context.WordBefore == ASContext.Context.Features.ReturnKey) return false; + if (expr.Member is null) return expr.Type != ClassModel.VoidClass; + return expr.Member.Type is { } type && type != ASContext.Context.Features.voidKey; + } + + /// + /// Check if "Convert to constant" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// The declaration target at current line(can not be null) + /// true, if can show "Convert to constant" list + protected virtual bool CanShowConvertToConst(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) + { + return !ASContext.Context.CurrentClass.Flags.HasFlag(FlagType.Interface) + && ASComplete.IsLiteralStyle(sci.BaseStyleAt(position)); + } + + /// + /// Check if "Getter and Setter" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// The declaration target at current line(can not be null) + /// true, if can show "Getter and Setter" list + protected virtual bool CanShowGetSetList(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) => true; + + /// + /// Check if "Getter" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// The declaration target at current line(can not be null) + /// true, if can show "Getter" list + protected virtual bool CanShowGenerateGetter(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) => false; + + /// + /// Check if "Setter" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// The declaration target at current line(can not be null) + /// true, if can show "Setter" list + protected virtual bool CanShowGenerateSetter(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) => false; + + /// + /// Check if "Generate constructor" and "Generate toString()" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// The declaration target at current line(can not be null) + /// true, if can show "Generate constructor" and(or) "Generate toString()" list + protected virtual bool CanShowGenerateConstructorAndToString(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) + { + return contextToken is null + && found.Member is null + && !found.InClass.IsVoid() + && !found.InClass.Flags.HasFlag(FlagType.Interface) + && position < sci.LineEndPosition(found.InClass.LineTo) + && !ASContext.Context.CodeComplete.PositionIsBeforeBody(sci, position, found.InClass); + } + + /// + /// Check if "Implement Interface" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// Declaration target at current line(can not be null) + /// true, if can show "Implement Interface" list + protected virtual bool CanShowImplementInterfaceList(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) + { + if (expr.Context.ContextFunction is not null || expr.Context.ContextMember is not null + || expr.Member is not null + || expr.Type is null || (expr.Type.Flags & FlagType.Interface) == 0) return false; + var type = expr.Type; + type.ResolveExtends(); + while (!type.IsVoid()) + { + if (type.Members.Count > 0) return true; + type = type.Extends; + } + return false; + } + + /// + /// Check if "Generate public function and Generate public callback" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// Declaration target at current line(can not be null) + /// true, if can show "Generate public function and Generate public callback" list + protected virtual bool CanShowNewMethodList(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) + { + var inClass = expr.RelClass ?? found.InClass; + return (inClass.Flags & FlagType.Interface) == 0 || !expr.IsStatic; + } + + /// + /// Check if "Generate public variable" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// Declaration target at current line(can not be null) + /// true, if can show "Generate public function and Generate public callback" list + protected virtual bool CanShowNewVarList(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) + { + var inClass = expr.RelClass ?? found.InClass; + return (inClass.Flags & FlagType.Interface) == 0 || !expr.IsStatic; + } - // TODO Empty line, show generators list? + /// + /// Check if "Add to interface" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// Declaration target at current line(can not be null) + /// true, if can show "Add to interface" list + protected virtual bool CanShowAddToInterfaceList(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) + { + return expr.Member is not null + && !expr.Member.Flags.HasFlag(FlagType.Static) + && !expr.Member.Flags.HasFlag(FlagType.Constructor) + && expr.Member.Name == found.Member.Name + && sci.LineFromPosition(position) == found.Member.LineFrom + && ((found.Member.Flags & FlagType.Function) > 0 + || (found.Member.Flags & FlagType.Getter) > 0 + || (found.Member.Flags & FlagType.Setter) > 0) + && !found.InClass.IsVoid() + && found.InClass.Implements is not null + && found.InClass.Implements.Count > 0; + } + + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// Declaration target at current line(can not be null) + /// + /// + protected virtual bool TryShowGenerateType(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found, List options) + { + var result = false; + if (CanShowGenerateClass(sci, position, expr, found)) + { + ShowGenerateClassList(found, expr.Context, options); + result = true; + } + if (CanShowGenerateInterface(sci, position, expr, found)) + { + ShowGenerateInterfaceList(expr, found, options); + result = true; + } + return result; + } + + /// + /// Check if "Create new class" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// Declaration target at current line(can not be null) + /// true, if can show "Create new class" list + protected virtual bool CanShowGenerateClass(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) + { + // for example: public var foo : Foo + return expr.Context.Separator == ":" + // for example, good: new Type(), bad: new Type().value + || (expr.Context.WordBefore == "new" && !expr.Context.Value.Contains("~.")) + // for example: class Foo extends Bar + || (expr.Context.WordBefore == ASContext.Context.Features.ExtendsKey + && ASContext.Context.CurrentClass.Flags is var flags + && flags.HasFlag(FlagType.Class) + // for example: interface Foo extends Bar + && !flags.HasFlag(FlagType.Interface) + && ASContext.Context.CodeComplete.PositionIsBeforeBody(sci, position, found.InClass)); } - private static MemberModel ResolveDelegate(string type, FileModel inFile) + /// + /// Check if "Create new interface" are available at the current cursor position. + /// + /// The Scintilla control containing the document + /// Cursor position + /// Expression at cursor position + /// Declaration target at current line(can not be null) + /// true, if can show "Create new interface" list + protected virtual bool CanShowGenerateInterface(ScintillaControl sci, int position, ASResult expr, FoundDeclaration found) + { + return contextToken is not null + && ASComplete.IsTextStyle(sci.BaseStyleAt(position - 1)) + // for example: implements IFoo + && (expr.Context.WordBefore == ASContext.Context.Features.ImplementsKey && ASContext.Context.CodeComplete.PositionIsBeforeBody(sci, position, found.InClass) + // for example: public var foo : Fo|o + || (expr.Context.Separator == ":")); + } + + static MemberModel ResolveDelegate(string type, FileModel inFile) { foreach (MemberModel def in inFile.Members) if (def.Name == type && (def.Flags & FlagType.Delegate) > 0) return def; - if (type.IndexOf('.') < 0) + if (!type.Contains('.')) { - string dotType = '.' + type; - MemberList imports = ASContext.Context.ResolveImports(inFile); + var dotType = '.' + type; + var imports = ASContext.Context.ResolveImports(inFile); foreach (MemberModel import in imports) - if (import.Type.EndsWith(dotType)) + if (import.Type.EndsWithOrdinal(dotType)) { type = import.Type; break; } } - MemberList known = ASContext.Context.GetAllProjectClasses(); + var known = ASContext.Context.GetAllProjectClasses(); foreach (MemberModel def in known) if (def.Type == type && (def.Flags & FlagType.Delegate) > 0) return def; return null; } - private static void GenerateDefaultHandlerName(ScintillaNet.ScintillaControl Sci, int position, int targetPos, string eventName, bool closeBrace) + static void GenerateDefaultHandlerName(ScintillaControl sci, int position, int targetPos, string eventName, bool closeBrace) { string target = null; - int contextOwnerPos = GetContextOwnerEndPos(Sci, Sci.WordStartPosition(targetPos, true)); + var contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(targetPos, true)); if (contextOwnerPos != -1) { - ASResult contextOwnerResult = ASComplete.GetExpressionType(Sci, contextOwnerPos); - if (contextOwnerResult != null && !contextOwnerResult.IsNull() - && contextOwnerResult.Member != null) + var contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos); + if (contextOwnerResult is not null && !contextOwnerResult.IsNull() + && contextOwnerResult.Member is not null) { - if (contextOwnerResult.Member.Name == "contentLoaderInfo" && Sci.CharAt(contextOwnerPos) == '.') + if (contextOwnerResult.Member.Name == "contentLoaderInfo" && sci.CharAt(contextOwnerPos) == '.') { // we want to name the event from the loader var and not from the contentLoaderInfo parameter - contextOwnerPos = GetContextOwnerEndPos(Sci, Sci.WordStartPosition(contextOwnerPos - 1, true)); + contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(contextOwnerPos - 1, true)); if (contextOwnerPos != -1) { - contextOwnerResult = ASComplete.GetExpressionType(Sci, contextOwnerPos); - if (contextOwnerResult != null && !contextOwnerResult.IsNull() - && contextOwnerResult.Member != null) + contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos); + if (contextOwnerResult is not null && !contextOwnerResult.IsNull() + && contextOwnerResult.Member is not null) { target = contextOwnerResult.Member.Name; } } } - else - { - target = contextOwnerResult.Member.Name; - } + else target = contextOwnerResult.Member.Name; } } eventName = Camelize(eventName.Substring(eventName.LastIndexOf('.') + 1)); - if (target != null) target = target.TrimStart(new char[] { '_' }); + target = target?.TrimStart('_'); switch (ASContext.CommonSettings.HandlerNamingConvention) { case HandlerNamingConventions.handleTargetEventName: - if (target == null) contextToken = "handle" + Capitalize(eventName); + if (target is null) contextToken = "handle" + Capitalize(eventName); else contextToken = "handle" + Capitalize(target) + Capitalize(eventName); break; case HandlerNamingConventions.onTargetEventName: - if (target == null) contextToken = "on" + Capitalize(eventName); + if (target is null) contextToken = "on" + Capitalize(eventName); else contextToken = "on" + Capitalize(target) + Capitalize(eventName); break; case HandlerNamingConventions.target_eventNameHandler: - if (target == null) contextToken = eventName + "Handler"; + if (target is null) contextToken = eventName + "Handler"; else contextToken = target + "_" + eventName + "Handler"; break; default: //HandlerNamingConventions.target_eventName - if (target == null) contextToken = eventName; + if (target is null) contextToken = eventName; else contextToken = target + "_" + eventName; break; } - char c = (char)Sci.CharAt(position - 1); - if (c == ',') InsertCode(position, "$(Boundary) " + contextToken + "$(Boundary)"); - else InsertCode(position, contextToken); + var c = (char)sci.CharAt(position - 1); + if (c == ',') InsertCode(position, "$(Boundary) " + contextToken + "$(Boundary)", sci); + else InsertCode(position, contextToken, sci); - position = Sci.WordEndPosition(position + 1, true); - Sci.SetSel(position, position); - c = (char)Sci.CharAt(position); - if (c <= 32) if (closeBrace) Sci.ReplaceSel(");"); else Sci.ReplaceSel(";"); + position = sci.WordEndPosition(position + 1, true); + sci.SetSel(position, position); + c = (char)sci.CharAt(position); + if (c <= 32) sci.ReplaceSel(closeBrace ? ");" : ";"); - Sci.SetSel(position, position); + sci.SetSel(position, position); } - private static FoundDeclaration GetDeclarationAtLine(ScintillaNet.ScintillaControl Sci, int line) + public virtual FoundDeclaration GetDeclarationAtLine(int line) { - FoundDeclaration result = new FoundDeclaration(); - FileModel model = ASContext.Context.CurrentModel; - - foreach (MemberModel member in model.Members) - { - if (member.LineFrom <= line && member.LineTo >= line) - { - result.member = member; - return result; - } - } - - foreach (ClassModel aClass in model.Classes) + var result = new FoundDeclaration(); + var model = ASContext.Context.CurrentModel; + result.Member = ASComplete.FindMember(line, model.Members.Items); + if (result.Member is null) { - if (aClass.LineFrom <= line && aClass.LineTo >= line) - { - result.inClass = aClass; - foreach (MemberModel member in aClass.Members) - { - if (member.LineFrom <= line && member.LineTo >= line) - { - result.member = member; - return result; - } - } - return result; - } + result.InClass = ASComplete.FindMember(line, model.Classes); + if (result.InClass is not null) result.Member = ASComplete.FindMember(line, result.InClass.Members.Items); } + result.InClass ??= ClassModel.VoidClass; return result; } - private static bool CheckAutoImport(FoundDeclaration found) + protected bool CheckAutoImport(ASResult expr, List options) { - MemberList allClasses = ASContext.Context.GetAllProjectClasses(); - if (allClasses != null) - { - List names = new List(); - List matches = new List(); - string dotToken = "." + contextToken; - foreach (MemberModel member in allClasses) - if (member.Name.EndsWith(dotToken) && !names.Contains(member.Name)) - { - matches.Add(member); - names.Add(member.Name); - } - if (matches.Count > 0) - { - ShowImportClass(matches); - return true; - } - } - return false; + if (ASContext.Context.CurrentClass.Equals(expr.RelClass)) return false; + var allClasses = ASContext.Context.GetAllProjectClasses(); + if (allClasses is null) return false; + var names = new HashSet(); + var matches = new List(); + var dotToken = "." + contextToken; + foreach (var member in allClasses) + if (!names.Contains(member.Name) && member.Name.EndsWithOrdinal(dotToken)) + { + matches.Add(member); + names.Add(member.Name); + } + if (matches.Count == 0) return false; + ShowImportClass(matches, options); + return true; } /// /// For the Event handlers generator: /// check that the event name's const is declared in an Event type /// - private static string CheckEventType(string name) + internal static string CheckEventType(string name) { - if (name.IndexOf('"') >= 0) return "Event"; - if (name.IndexOf('.') > 0) name = name.Substring(0, name.IndexOf('.')); - ClassModel model = ASContext.Context.ResolveType(name, ASContext.Context.CurrentModel); + if (name.Contains('"')) return "Event"; + if (name.IndexOf('.') is { } index && index > 0) name = name.Substring(0, index); + var model = ASContext.Context.ResolveType(name, ASContext.Context.CurrentModel); if (model.IsVoid() || model.Name == "Event") return "Event"; model.ResolveExtends(); while (!model.IsVoid() && model.Name != "Event") model = model.Extends; - if (model.Name == "Event") return name; - else return "Event"; + return model.Name == "Event" + ? name + : "Event"; + } + + protected virtual string CheckEventType(MemberModel handler, string eventName) + { + if (handler?.Parameters is {Count: > 1} parameters) + { + var parameter = parameters[1]; + if (parameter is not null) + { + if (!parameter.Parameters.IsNullOrEmpty()) return parameter.Parameters[0].Type; + if (parameter.Type is { } type && type != "Function") return type; + } + } + return CheckEventType(eventName); } #endregion #region generators lists - private static void ShowImportClass(List matches) + static void ShowImportClass(IList matches, ICollection options) { if (matches.Count == 1) { - ASGenerator.GenerateJob(GeneratorJobType.AddImport, matches[0], null, null, null); + GenerateJob(GeneratorJobType.AddImport, matches[0], null, null, null); return; } - - List known = new List(); + foreach (MemberModel member in matches) { if ((member.Flags & FlagType.Class) > 0) - known.Add(new GeneratorItem("import " + member.Type, GeneratorJobType.AddImport, member, null)); + options.Add(new GeneratorItem("import " + member.Type, GeneratorJobType.AddImport, member, null)); else if (member.IsPackageLevel) - known.Add(new GeneratorItem("import " + member.Name, GeneratorJobType.AddImport, member, null)); + options.Add(new GeneratorItem("import " + member.Name, GeneratorJobType.AddImport, member, null)); } - CompletionList.Show(known, false); } - private static void ShowPromoteLocalAndAddParameter(FoundDeclaration found) + static void ShowPromoteLocalAndAddParameter(FoundDeclaration found, ICollection options) { - List known = new List(); string label = TextHelper.GetString("ASCompletion.Label.PromoteLocal"); string labelMove = TextHelper.GetString("ASCompletion.Label.MoveDeclarationOnTop"); string labelParam = TextHelper.GetString("ASCompletion.Label.AddAsParameter"); - known.Add(new GeneratorItem(label, GeneratorJobType.PromoteLocal, found.member, found.inClass)); - known.Add(new GeneratorItem(labelMove, GeneratorJobType.MoveLocalUp, found.member, found.inClass)); - known.Add(new GeneratorItem(labelParam, GeneratorJobType.AddAsParameter, found.member, found.inClass)); - CompletionList.Show(known, false); + options.Add(new GeneratorItem(label, GeneratorJobType.PromoteLocal, found.Member, found.InClass)); + options.Add(new GeneratorItem(labelMove, GeneratorJobType.MoveLocalUp, found.Member, found.InClass)); + options.Add(new GeneratorItem(labelParam, GeneratorJobType.AddAsParameter, found.Member, found.InClass)); } - private static void ShowConvertToConst(FoundDeclaration found) + static void ShowConvertToConst(FoundDeclaration found, ICollection options) { - List known = new List(); string label = TextHelper.GetString("ASCompletion.Label.ConvertToConst"); - known.Add(new GeneratorItem(label, GeneratorJobType.ConvertToConst, found.member, found.inClass)); - CompletionList.Show(known, false); + options.Add(new GeneratorItem(label, GeneratorJobType.ConvertToConst, found.Member, found.InClass)); } - private static void ShowImplementInterface(FoundDeclaration found) + static void ShowImplementInterface(FoundDeclaration found, ICollection options) { - List known = new List(); string label = TextHelper.GetString("ASCompletion.Label.ImplementInterface"); - known.Add(new GeneratorItem(label, GeneratorJobType.ImplementInterface, null, found.inClass)); - CompletionList.Show(known, false); + options.Add(new GeneratorItem(label, GeneratorJobType.ImplementInterface, null, found.InClass)); } - private static void ShowNewVarList(FoundDeclaration found) + protected virtual void ShowNewVarList(ScintillaControl sci, ASResult expr, FoundDeclaration found, ICollection options) { - List known = new List(); - - ScintillaNet.ScintillaControl Sci = ASContext.CurSciControl; - - ASResult result = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); - if (!(result != null && result.RelClass != null)) - { - result = null; + if (expr.InClass is null || found.InClass.QualifiedName.Equals(expr.RelClass.QualifiedName)) + expr = null; + ASResult exprLeft = null; + var currentPos = sci.CurrentPos; + var curWordStartPos = sci.WordStartPosition(currentPos, true); + if ((char)sci.CharAt(curWordStartPos - 1) == '.') exprLeft = ASComplete.GetExpressionType(sci, curWordStartPos - 1); + if (exprLeft is not null && exprLeft.Type is null) exprLeft = null; + var generateClass = true; + if (exprLeft is not null) + { + if (!File.Exists(exprLeft.Type.InFile?.FileName)) return; + generateClass = false; + var curClass = ASContext.Context.CurrentClass; + if (!IsHaxe) + { + if (exprLeft.Type.Equals(curClass)) exprLeft = null; + } + else + { + curClass.ResolveExtends(); + while (!curClass.IsVoid()) + { + if (curClass.Equals(exprLeft.Type)) + { + exprLeft = null; + break; + } + curClass = curClass.Extends; + } + } } - else if (found.inClass.QualifiedName.Equals(result.RelClass.QualifiedName)) + + var textAtCursor = sci.GetWordFromPosition(currentPos); + string label; + if (textAtCursor is not null && textAtCursor.ToUpper().Equals(textAtCursor)) { - result = null; + label = TextHelper.GetString("ASCompletion.Label.GenerateConstant"); + options.Add(new GeneratorItem(label, GeneratorJobType.Constant, found.Member, found.InClass)); } - bool isConst = false; - string textAtCursor = Sci.GetWordFromPosition(Sci.CurrentPos); - if (textAtCursor != null && textAtCursor.ToUpper().Equals(textAtCursor)) + bool genProtectedDecl = GetDefaultVisibility(found.InClass) == Visibility.Protected; + if (expr is null && exprLeft is null) { - isConst = true; + if (genProtectedDecl) label = TextHelper.GetString("ASCompletion.Label.GenerateProtectedVar"); + else label = TextHelper.GetString("ASCompletion.Label.GeneratePrivateVar"); + options.Add(new GeneratorItem(label, GeneratorJobType.Variable, found.Member, found.InClass)); } - ClassModel inClass = result != null ? result.RelClass : found.inClass; - bool isInterface = ClassIsInterface(inClass); + label = TextHelper.GetString("ASCompletion.Label.GeneratePublicVar"); + options.Add(new GeneratorItem(label, GeneratorJobType.VariablePublic, found.Member, found.InClass)); - if (!isInterface) + if (expr is null && exprLeft is null) { - if (isConst) - { - string labelConst = TextHelper.GetString("ASCompletion.Label.GenerateConstant"); - known.Add(new GeneratorItem(labelConst, GeneratorJobType.Constant, found.member, found.inClass)); - } - - if (result == null) - { - string labelVar = TextHelper.GetString("ASCompletion.Label.GeneratePrivateVar"); - known.Add(new GeneratorItem(labelVar, GeneratorJobType.Variable, found.member, found.inClass)); - } - - string labelVarPublic = TextHelper.GetString("ASCompletion.Label.GeneratePublicVar"); - known.Add(new GeneratorItem(labelVarPublic, GeneratorJobType.VariablePublic, found.member, found.inClass)); - - if (result == null) - { - string labelFun = TextHelper.GetString("ASCompletion.Label.GeneratePrivateFunction"); - known.Add(new GeneratorItem(labelFun, GeneratorJobType.Function, found.member, found.inClass)); - } + if (genProtectedDecl) label = TextHelper.GetString("ASCompletion.Label.GenerateProtectedFunction"); + else label = TextHelper.GetString("ASCompletion.Label.GeneratePrivateFunction"); + options.Add(new GeneratorItem(label, GeneratorJobType.Function, found.Member, found.InClass)); } - string labelFunPublic = TextHelper.GetString("ASCompletion.Label.GenerateFunctionPublic"); - if (isInterface) - { - labelFunPublic = TextHelper.GetString("ASCompletion.Label.GenerateFunctionInterface"); - } - known.Add(new GeneratorItem(labelFunPublic, GeneratorJobType.FunctionPublic, found.member, found.inClass)); + label = TextHelper.GetString("ASCompletion.Label.GenerateFunctionPublic"); + options.Add(new GeneratorItem(label, GeneratorJobType.FunctionPublic, found.Member, found.InClass)); - if (GetLangIsValid()) + if (generateClass) { - string labelClass = TextHelper.GetString("ASCompletion.Label.GenerateClass"); - known.Add(new GeneratorItem(labelClass, GeneratorJobType.Class, found.member, found.inClass)); + label = TextHelper.GetString("ASCompletion.Label.GenerateClass"); + options.Add(new GeneratorItem(label, GeneratorJobType.Class, found.Member, found.InClass)); } - CompletionList.Show(known, false); } - private static void ShowChangeMethodDeclList(FoundDeclaration found) + static void ShowChangeMethodDeclList(FoundDeclaration found, ICollection options) { - List known = new List(); - string label = TextHelper.GetString("ASCompletion.Label.ChangeMethodDecl"); - known.Add(new GeneratorItem(label, GeneratorJobType.ChangeMethodDecl, found.member, found.inClass)); - CompletionList.Show(known, false); + var label = TextHelper.GetString("ASCompletion.Label.ChangeMethodDecl"); + options.Add(new GeneratorItem(label, GeneratorJobType.ChangeMethodDecl, found.Member, found.InClass)); } - private static void ShowChangeConstructorDeclList(FoundDeclaration found) + static void ShowChangeConstructorDeclarationList(FoundDeclaration found, IList parameters, ICollection options) { - List known = new List(); - string label = TextHelper.GetString("ASCompletion.Label.ChangeConstructorDecl"); - known.Add(new GeneratorItem(label, GeneratorJobType.ChangeConstructorDecl, found.member, found.inClass)); - CompletionList.Show(known, false); + var label = TextHelper.GetString("ASCompletion.Label.ChangeConstructorDecl"); + options.Add(new GeneratorItem(label, GeneratorJobType.ChangeConstructorDecl, found.Member, found.InClass, parameters)); } - private static void ShowNewMethodList(FoundDeclaration found) + protected virtual void ShowNewMethodList(ScintillaControl sci, ASResult expr, FoundDeclaration found, ICollection options) { - List known = new List(); + if (expr.RelClass is null || found.InClass.QualifiedName.Equals(expr.RelClass.QualifiedName)) + expr = null; + string label; + var inClass = expr is not null ? expr.RelClass : found.InClass; + var isInterface = (inClass.Flags & FlagType.Interface) > 0; + if (!isInterface && expr is null) + { + if (GetDefaultVisibility(found.InClass) == Visibility.Protected) + label = TextHelper.GetString("ASCompletion.Label.GenerateProtectedFunction"); + else label = TextHelper.GetString("ASCompletion.Label.GeneratePrivateFunction"); + options.Add(new GeneratorItem(label, GeneratorJobType.Function, found.Member, found.InClass)); + } + if (isInterface) label = TextHelper.GetString("ASCompletion.Label.GenerateFunctionInterface"); + else label = TextHelper.GetString("ASCompletion.Label.GenerateFunctionPublic"); + options.Add(new GeneratorItem(label, GeneratorJobType.FunctionPublic, found.Member, found.InClass)); + label = TextHelper.GetString("ASCompletion.Label.GeneratePublicCallback"); + options.Add(new GeneratorItem(label, GeneratorJobType.VariablePublic, found.Member, found.InClass)); + } - ScintillaNet.ScintillaControl Sci = ASContext.CurSciControl; + static void ShowAssignStatementToVarList(FoundDeclaration found, StatementReturnType data, ICollection options) + { + var label = TextHelper.GetString("ASCompletion.Label.AssignStatementToVar"); + options.Add(new GeneratorItem(label, GeneratorJobType.AssignStatementToVar, found.Member, found.InClass, data)); + } - string autoSelect = ""; + static void ShowGenerateClassList(FoundDeclaration found, ICollection options) => ShowGenerateClassList(found, null, options); - ASResult result = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); - if (!(result != null && result.RelClass != null)) - { - result = null; - } - else if (found.inClass.QualifiedName.Equals(result.RelClass.QualifiedName)) - { - result = null; - } + static void ShowGenerateClassList(FoundDeclaration found, ASExpr expr, ICollection options) + { + var label = TextHelper.GetString("ASCompletion.Label.GenerateClass"); + options.Add(new GeneratorItem(label, GeneratorJobType.Class, found.Member, found.InClass, expr)); + } - ClassModel inClass = result != null ? result.RelClass : found.inClass; - bool isInterface = ClassIsInterface(inClass); + static void ShowGenerateInterfaceList(ASResult expr, FoundDeclaration found, ICollection options) + { + var label = TextHelper.GetString("ASCompletion.Label.GenerateInterface"); + options.Add(new GeneratorItem(label, GeneratorJobType.Interface, found.Member, found.InClass, expr)); + } - if (!isInterface && result == null) + static void ShowConstructorAndToStringList(FoundDeclaration found, bool hasConstructor, bool hasToString, ICollection options) + { + if (!hasConstructor) { - string label = TextHelper.GetString("ASCompletion.Label.GeneratePrivateFunction"); - known.Add(new GeneratorItem(label, GeneratorJobType.Function, found.member, found.inClass)); + var label = TextHelper.GetString("ASCompletion.Label.GenerateConstructor"); + options.Add(new GeneratorItem(label, GeneratorJobType.Constructor, found.Member, found.InClass)); } - string labelFunPublic = TextHelper.GetString("ASCompletion.Label.GenerateFunctionPublic"); - if (isInterface) + if (!hasToString) { - labelFunPublic = TextHelper.GetString("ASCompletion.Label.GenerateFunctionInterface"); - autoSelect = labelFunPublic; + var label = TextHelper.GetString("ASCompletion.Label.GenerateToString"); + options.Add(new GeneratorItem(label, GeneratorJobType.ToString, found.Member, found.InClass)); } - known.Add(new GeneratorItem(labelFunPublic, GeneratorJobType.FunctionPublic, found.member, found.inClass)); + } - string labelCallback = TextHelper.GetString("ASCompletion.Label.GeneratePublicCallback"); - known.Add(new GeneratorItem(labelCallback, GeneratorJobType.VariablePublic, found.member, found.inClass)); + static void ShowEventMetatagList(FoundDeclaration found, ICollection options) + { + string label = TextHelper.GetString("ASCompletion.Label.GenerateEventMetatag"); + options.Add(new GeneratorItem(label, GeneratorJobType.EventMetatag, found.Member, found.InClass)); + } - CompletionList.Show(known, false); + static void ShowFieldFromParameter(FoundDeclaration found, ICollection options) + { + var parameters = new Hashtable {["scope"] = GetDefaultVisibility(found.InClass)}; + string label; + if (GetDefaultVisibility(found.InClass) == Visibility.Protected) + label = TextHelper.GetString("ASCompletion.Label.GenerateProtectedFieldFromParameter"); + else label = TextHelper.GetString("ASCompletion.Label.GeneratePrivateFieldFromParameter"); + options.Add(new GeneratorItem(label, GeneratorJobType.FieldFromParameter, found.Member, found.InClass, parameters)); + parameters = new Hashtable {["scope"] = Visibility.Public}; + label = TextHelper.GetString("ASCompletion.Label.GeneratePublicFieldFromParameter"); + options.Add(new GeneratorItem(label, GeneratorJobType.FieldFromParameter, found.Member, found.InClass, parameters)); } - private static void ShowAssignStatementToVarList(FoundDeclaration found) + static void ShowAddInterfaceDefList(FoundDeclaration found, IEnumerable interfaces, ICollection options) { - if (GetLangIsValid()) + var label = TextHelper.GetString("ASCompletion.Label.AddInterfaceDef"); + foreach (var interf in interfaces) { - List known = new List(); - - string labelClass = TextHelper.GetString("ASCompletion.Label.AssignStatementToVar"); - known.Add(new GeneratorItem(labelClass, GeneratorJobType.AssignStatementToVar, found.member, found.inClass)); - - CompletionList.Show(known, false); + options.Add(new GeneratorItem(string.Format(label, interf), GeneratorJobType.AddInterfaceDef, found.Member, found.InClass, interf)); } } - private static void ShowNewClassList(FoundDeclaration found) + static void ShowDelegateList(FoundDeclaration found, ICollection options) { - if (GetLangIsValid()) - { - List known = new List(); - - string labelClass = TextHelper.GetString("ASCompletion.Label.GenerateClass"); - known.Add(new GeneratorItem(labelClass, GeneratorJobType.Class, found.member, found.inClass)); - - CompletionList.Show(known, false); - } + string label = string.Format(TextHelper.GetString("ASCompletion.Label.GenerateHandler"), "Delegate"); + options.Add(new GeneratorItem(label, GeneratorJobType.Delegate, found.Member, found.InClass)); } - private static void ShowConstructorAndToStringList(FoundDeclaration found, bool hasConstructor, bool hasToString) + internal static void ShowEventList(FoundDeclaration found, List options) { - - if (GetLangIsValid()) + var tmp = TextHelper.GetString("ASCompletion.Label.GenerateHandler"); + var labelEvent = string.Format(tmp, "Event"); + var labelContext = string.Format(tmp, contextParam); + string[] choices = null; + if (contextParam != "Event") { - List known = new List(); - - if (!hasConstructor) - { - string labelClass = TextHelper.GetString("ASCompletion.Label.GenerateConstructor"); - known.Add(new GeneratorItem(labelClass, GeneratorJobType.Constructor, found.member, found.inClass)); - } - - if (!hasToString) + var type = ASContext.Context.ResolveType(contextParam, ASContext.Context.CurrentModel); + type.ResolveExtends(); + while (!type.IsVoid()) { - string labelClass = TextHelper.GetString("ASCompletion.Label.GenerateToString"); - known.Add(new GeneratorItem(labelClass, GeneratorJobType.ToString, found.member, found.inClass)); + if (type.Name == "Event") + { + choices = new[] { labelContext, labelEvent }; + break; + } + type = type.Extends; } + choices ??= new[] {labelContext}; + } + else if (HasDataEvent()) + { + var labelDataEvent = string.Format(tmp, "DataEvent"); + choices = new[] { labelEvent, labelDataEvent }; + } + else choices = new[] { labelEvent }; - CompletionList.Show(known, false); + foreach (var choice in choices) + { + options.Add(new GeneratorItem(choice, + choice == labelContext ? GeneratorJobType.ComplexEvent : GeneratorJobType.BasicEvent, + found.Member, found.InClass)); } } - private static void ShowEventMetatagList(FoundDeclaration found) - { - List known = new List(); - - string label = TextHelper.GetString("ASCompletion.Label.GenerateEventMetatag"); - known.Add(new GeneratorItem(label, GeneratorJobType.EventMetatag, found.member, found.inClass)); + static bool HasDataEvent() => !ASContext.Context.ResolveType("flash.events.DataEvent", ASContext.Context.CurrentModel).IsVoid(); - CompletionList.Show(known, false); + static void ShowGetSetList(FoundDeclaration found, ICollection options) + { + var name = GetPropertyNameFor(found.Member); + var result = new ASResult(); + var curClass = ASContext.Context.CurrentClass; + ASComplete.FindMember(name, curClass, result, FlagType.Getter, 0); + var hasGetter = !result.IsNull(); + ASComplete.FindMember(name, curClass, result, FlagType.Setter, 0); + var hasSetter = !result.IsNull(); + if (hasGetter && hasSetter) return; + if (!hasGetter && !hasSetter) + { + string label = TextHelper.GetString("ASCompletion.Label.GenerateGetSet"); + options.Add(new GeneratorItem(label, GeneratorJobType.GetterSetter, found.Member, found.InClass)); + } + ShowGetterList(found, options); + ShowSetterList(found, options); } - private static void ShowFieldFromParameter(FoundDeclaration found) + static void ShowGetterList(FoundDeclaration found, ICollection options) { - List known = new List(); + var name = GetPropertyNameFor(found.Member); + var result = new ASResult(); + ASComplete.FindMember(name, ASContext.Context.CurrentClass, result, FlagType.Getter, 0); + if (!result.IsNull()) return; + var label = TextHelper.GetString("ASCompletion.Label.GenerateGet"); + options.Add(new GeneratorItem(label, GeneratorJobType.Getter, found.Member, found.InClass)); + } - if (GetLangIsValid()) - { - Hashtable parameters = new Hashtable(); - parameters["scope"] = GetDefaultVisibility(); - string labelClass = TextHelper.GetString("ASCompletion.Label.GeneratePrivateFieldFromPatameter"); - known.Add(new GeneratorItem(labelClass, GeneratorJobType.FieldFromPatameter, found.member, found.inClass, parameters)); + static void ShowSetterList(FoundDeclaration found, ICollection options) + { + var name = GetPropertyNameFor(found.Member); + var result = new ASResult(); + ASComplete.FindMember(name, ASContext.Context.CurrentClass, result, FlagType.Setter, 0); + if (!result.IsNull()) return; + var label = TextHelper.GetString("ASCompletion.Label.GenerateSet"); + options.Add(new GeneratorItem(label, GeneratorJobType.Setter, found.Member, found.InClass)); + } - parameters = new Hashtable(); - parameters["scope"] = Visibility.Public; - labelClass = TextHelper.GetString("ASCompletion.Label.GeneratePublicFieldFromPatameter"); - known.Add(new GeneratorItem(labelClass, GeneratorJobType.FieldFromPatameter, found.member, found.inClass, parameters)); + #endregion - CompletionList.Show(known, false); - } - } + #region code generation - private static void ShowAddInterfaceDefList(FoundDeclaration found, List interfaces) - { - if (GetLangIsValid()) - { - List known = new List(); - - string labelClass = TextHelper.GetString("ASCompletion.Label.AddInterfaceDef"); - foreach (String interf in interfaces) - { - known.Add(new GeneratorItem(String.Format(labelClass, interf), GeneratorJobType.AddInterfaceDef, found.member, found.inClass, interf)); - } - CompletionList.Show(known, false); - } - } - - private static void ShowDelegateList(FoundDeclaration found) - { - List known = new List(); - string label = String.Format(TextHelper.GetString("ASCompletion.Label.GenerateHandler"), "Delegate"); - known.Add(new GeneratorItem(label, GeneratorJobType.Delegate, found.member, found.inClass)); - CompletionList.Show(known, false); - } - - private static void ShowEventList(FoundDeclaration found) - { - List known = new List(); - string tmp = TextHelper.GetString("ASCompletion.Label.GenerateHandler"); - string labelEvent = String.Format(tmp, "Event"); - string labelDataEvent = String.Format(tmp, "DataEvent"); - string labelContext = String.Format(tmp, contextParam); - string[] choices = (contextParam != "Event") ? - new string[] { labelContext, labelEvent } : - new string[] { labelEvent, labelDataEvent }; - for (int i = 0; i < choices.Length; i++) - { - known.Add(new GeneratorItem(choices[i], - choices[i] == labelContext ? GeneratorJobType.ComplexEvent : GeneratorJobType.BasicEvent, - found.member, found.inClass)); - } - CompletionList.Show(known, false); - } - - private static void ShowGetSetList(FoundDeclaration found) - { - List known = new List(); - string labelGetSet = TextHelper.GetString("ASCompletion.Label.GenerateGetSet"); - string labelGet = TextHelper.GetString("ASCompletion.Label.GenerateGet"); - string labelSet = TextHelper.GetString("ASCompletion.Label.GenerateSet"); - string[] choices = new string[] { labelGetSet, labelGet, labelSet }; - for (int i = 0; i < choices.Length; i++) - { - known.Add(new GeneratorItem(choices[i], (GeneratorJobType)i, found.member, found.inClass)); - } - CompletionList.Show(known, false); - } - - private static bool GetLangIsValid() - { - IProject project = PluginBase.CurrentProject; - if (project == null) - return false; - - return project.Language.StartsWith("as") - || project.Language.StartsWith("haxe") - || project.Language.StartsWith("loom"); - } - - #endregion - - #region code generation - - static private Regex reInsert = new Regex("\\s*([a-z])", RegexOptions.Compiled); - - static public void SetJobContext(String contextToken, String contextParam, MemberModel contextMember, Match contextMatch) + public static void SetJobContext(string contextToken, string contextParam, MemberModel contextMember, Match contextMatch) { ASGenerator.contextToken = contextToken; ASGenerator.contextParam = contextParam; @@ -899,590 +1105,644 @@ static public void SetJobContext(String contextToken, String contextParam, Membe ASGenerator.contextMatch = contextMatch; } - static public void GenerateJob(GeneratorJobType job, MemberModel member, ClassModel inClass, string itemLabel, Object data) + public static void GenerateJob(GeneratorJobType job, MemberModel member, ClassModel inClass, string itemLabel, object data) { - ScintillaNet.ScintillaControl Sci = ASContext.CurSciControl; - lookupPosition = Sci.CurrentPos; + var sci = PluginBase.MainForm.CurrentDocument?.SciControl; + if (sci is null) return; + lookupPosition = sci.CurrentPos; int position; - MemberModel latest = null; + MemberModel latest; bool detach = true; switch (job) { case GeneratorJobType.Getter: case GeneratorJobType.Setter: case GeneratorJobType.GetterSetter: - GenerateProperty(job, member, inClass, Sci); + var generator = (ASGenerator) ASContext.Context.CodeGenerator; + var customBehavior = generator.GetCodeGeneratorBehavior(); + if (customBehavior is not null && ((CodeGeneratorDefaultBehavior) customBehavior).GenerateProperty(job, sci, member, inClass)) return; + // default behavior + generator.GenerateProperty(job, sci, inClass, member); break; case GeneratorJobType.BasicEvent: case GeneratorJobType.ComplexEvent: - - latest = TemplateUtils.GetTemplateBlockMember(Sci, - TemplateUtils.GetBoundary("EventHandlers")); - if (latest == null) + latest = TemplateUtils.GetTemplateBlockMember(sci, TemplateUtils.GetBoundary("EventHandlers")); + if (latest is null) { if (ASContext.CommonSettings.MethodsGenerationLocations == MethodsGenerationLocations.AfterSimilarAccessorMethod) - latest = GetLatestMemberForFunction(inClass, GetDefaultVisibility(), member); - if (latest == null) - latest = member; + latest = GetLatestMemberForFunction(inClass, GetDefaultVisibility(inClass), member); + latest ??= member; } - position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); - Sci.SetSel(position, position); - string type = contextParam; + position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); + sci.SetSel(position, position); + var type = contextParam; if (job == GeneratorJobType.BasicEvent) - if (itemLabel.IndexOf("DataEvent") >= 0) type = "DataEvent"; else type = "Event"; - GenerateEventHandler(contextToken, type, member, position); + type = itemLabel.Contains("DataEvent") ? "DataEvent" : "Event"; + GenerateEventHandler(contextToken, type, member, position, inClass); break; case GeneratorJobType.Delegate: - position = Sci.PositionFromLine(member.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); - Sci.SetSel(position, position); - GenerateDelegateMethod(contextToken, member, position); + position = sci.PositionFromLine(member.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1); + sci.SetSel(position, position); + GenerateDelegateMethod(contextToken, member, position, inClass); break; case GeneratorJobType.Constant: case GeneratorJobType.Variable: case GeneratorJobType.VariablePublic: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - GenerateVariableJob(job, Sci, member, detach, inClass); + GenerateVariableJob(job, sci, member, detach, inClass); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); + } + break; + + case GeneratorJobType.Constructor: + sci.BeginUndoAction(); + try + { + GenerateConstructorJob(sci, inClass); + } + finally + { + sci.EndUndoAction(); + } + break; + + case GeneratorJobType.ChangeConstructorDecl: + sci.BeginUndoAction(); + try + { + if (data is IList parameters) + ChangeConstructorDecl(sci, inClass, parameters); + else ChangeConstructorDecl(sci, inClass); + } + finally + { + sci.EndUndoAction(); } break; case GeneratorJobType.Function: case GeneratorJobType.FunctionPublic: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - GenerateFunctionJob(job, Sci, member, detach, inClass); + GenerateFunctionJob(job, sci, member, true, inClass); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.ImplementInterface: - ClassModel aType = ASContext.Context.ResolveType(contextParam, ASContext.Context.CurrentModel); - if (aType.IsVoid()) return; - - latest = GetLatestMemberForFunction(inClass, Visibility.Public, null); - if (latest == null) - latest = FindLatest(0, 0, inClass, false, false); - - if (latest == null) return; - - position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); - Sci.SetSel(position, position); - GenerateImplementation(aType, position); + var iType = ASContext.Context.ResolveType(contextParam, inClass.InFile ?? ASContext.Context.CurrentModel); + if (iType.IsVoid()) return; + latest = GetLatestMemberForFunction(inClass, Visibility.Public, null) ?? FindLatest(0, 0, inClass, false, false); + if (latest is null) + { + position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci); + detach = false; + } + else position = sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1); + sci.SetSel(position, position); + GenerateImplementation(iType, inClass, sci, detach); break; case GeneratorJobType.MoveLocalUp: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - if (!RemoveLocalDeclaration(Sci, contextMember)) return; + if (!RemoveLocalDeclaration(sci, contextMember)) return; - position = GetBodyStart(member.LineFrom, member.LineTo, Sci); - Sci.SetSel(position, position); + position = GetBodyStart(member.LineFrom, member.LineTo, sci); + sci.SetSel(position, position); - string varType = contextMember.Type; + var varType = contextMember.Type; if (varType == "") varType = null; - string template = TemplateUtils.GetTemplate("Variable"); + var template = TemplateUtils.GetTemplate("Variable"); template = TemplateUtils.ReplaceTemplateVariable(template, "Name", contextMember.Name); template = TemplateUtils.ReplaceTemplateVariable(template, "Type", varType); template = TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", null); template = TemplateUtils.ReplaceTemplateVariable(template, "Value", null); template += "\n$(Boundary)"; - lookupPosition += SnippetHelper.InsertSnippetText(Sci, position, template); + lookupPosition += SnippetHelper.InsertSnippetText(sci, position, template); - Sci.SetSel(lookupPosition, lookupPosition); + sci.SetSel(lookupPosition, lookupPosition); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.PromoteLocal: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - if (!RemoveLocalDeclaration(Sci, contextMember)) return; - - latest = GetLatestMemberForVariable(GeneratorJobType.Variable, inClass, GetDefaultVisibility(), member); - if (latest == null) return; - - position = FindNewVarPosition(Sci, inClass, latest); + if (!RemoveLocalDeclaration(sci, contextMember)) return; + latest = GetLatestMemberForVariable(GeneratorJobType.Variable, inClass, GetDefaultVisibility(inClass), member); + if (latest is null) return; + position = FindNewVarPosition(sci, inClass, latest); if (position <= 0) return; - Sci.SetSel(position, position); - - contextMember.Flags -= FlagType.LocalVar; - if ((member.Flags & FlagType.Static) > 0) - contextMember.Flags |= FlagType.Static; - contextMember.Access = GetDefaultVisibility(); - GenerateVariable(contextMember, position, detach); - - Sci.SetSel(lookupPosition, lookupPosition); + sci.SetSel(position, position); + var newMember = new MemberModel + { + Name = contextMember.Name, + Type = contextMember.Type, + Access = GetDefaultVisibility(inClass) + }; + if ((member.Flags & FlagType.Static) > 0) newMember.Flags |= FlagType.Access; + // for example: var f:Function/*(v1:Type):void*/ + if ((contextMember.Flags & FlagType.Function) != 0) + { + newMember.Type = ASContext.Context.CodeComplete.ToFunctionDeclarationString(new MemberModel {Parameters = contextMember.Parameters, Type = newMember.Type}); + } + GenerateVariable(newMember, position, detach); + sci.SetSel(lookupPosition, lookupPosition); + if (ASContext.Context.Settings.GenerateImports) + { + var imports = new List {newMember.Type}; + var types = GetQualifiedTypes(imports, inClass.InFile); + lookupPosition += AddImportsByName(types, sci.LineFromPosition(lookupPosition)); + sci.SetSel(lookupPosition, lookupPosition); + } } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.AddAsParameter: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - AddAsParameter(inClass, Sci, member, detach); + AddAsParameter(sci, member); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } - break; case GeneratorJobType.AddImport: - position = Sci.CurrentPos; + position = sci.CurrentPos; if ((member.Flags & (FlagType.Class | FlagType.Enum | FlagType.Struct | FlagType.TypeDef)) == 0) { - if (member.InFile == null) break; + if (member.InFile is null) break; member.Type = member.Name; } - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - int offset = InsertImport(member, true); - position += offset; - Sci.SetSel(position, position); + position += InsertImport(member, true); + sci.SetSel(position, position); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.Class: - String clasName = Sci.GetWordFromPosition(Sci.CurrentPos); - GenerateClass(Sci, clasName, inClass); + if (data is ASExpr) GenerateClass(sci, inClass, (ASExpr) data); + else GenerateClass(sci, inClass, sci.GetWordFromPosition(sci.CurrentPos)); break; - case GeneratorJobType.Constructor: - member = new MemberModel(inClass.Name, inClass.QualifiedName, FlagType.Constructor | FlagType.Function, Visibility.Public); - GenerateFunction( - member, - Sci.CurrentPos, false, inClass); + case GeneratorJobType.Interface: + GenerateInterface(sci, inClass, contextToken); break; case GeneratorJobType.ToString: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - GenerateToString(inClass, Sci, member); + GenerateToString(sci, inClass); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; - case GeneratorJobType.FieldFromPatameter: - Sci.BeginUndoAction(); + case GeneratorJobType.FieldFromParameter: + sci.BeginUndoAction(); try { - GenerateFieldFromParameter(Sci, member, inClass, (Visibility)(((Hashtable)data)["scope"])); + GenerateFieldFromParameter(sci, member, inClass, (Visibility) (((Hashtable) data)["scope"])); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.AddInterfaceDef: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - AddInterfaceDefJob(inClass, Sci, member, (String)data); + AddInterfaceDefJob(member, inClass, (string)data); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.ConvertToConst: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - ConvertToConst(inClass, Sci, member, detach); + ConvertToConst(sci, member, inClass, detach); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.ChangeMethodDecl: - Sci.BeginUndoAction(); - try - { - ChangeMethodDecl(Sci, member, inClass); - } - finally - { - Sci.EndUndoAction(); - } - break; - - case GeneratorJobType.ChangeConstructorDecl: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - ChangeConstructorDecl(Sci, member, inClass); + ChangeMethodDecl(sci, inClass); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.EventMetatag: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - EventMetatag(inClass, Sci, member); + EventMetatag(sci, inClass); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; case GeneratorJobType.AssignStatementToVar: - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - AssignStatementToVar(inClass, Sci, member); + if (data is StatementReturnType returnType) AssignStatementToVar(sci, inClass, returnType); + else AssignStatementToVar(sci, inClass); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } break; } - } - - private static void GenerateProperty(GeneratorJobType job, MemberModel member, ClassModel inClass, ScintillaNet.ScintillaControl Sci) - { - MemberModel latest; - string name = GetPropertyNameFor(member); - PropertiesGenerationLocations location = ASContext.CommonSettings.PropertiesGenerationLocation; - - latest = TemplateUtils.GetTemplateBlockMember(Sci, TemplateUtils.GetBoundary("AccessorsMethods")); - if (latest != null) - { - location = PropertiesGenerationLocations.AfterLastPropertyDeclaration; - } - else - { - if (location == PropertiesGenerationLocations.AfterLastPropertyDeclaration) - { - latest = FindLatest(FlagType.Getter | FlagType.Setter, 0, inClass, false, false); - } - else latest = member; - } - if (latest == null) return; - - Sci.BeginUndoAction(); - try - { - if (isHaxe) - { - if (name == null) name = member.Name; - string args = "(default, default)"; - if (job == GeneratorJobType.GetterSetter) args = "(get, set)"; - else if (job == GeneratorJobType.Getter) args = "(get, null)"; - else if (job == GeneratorJobType.Setter) args = "(default, set)"; - MakeHaxeProperty(Sci, member, args); - } - else - { - if ((member.Access & Visibility.Public) > 0) // hide member - { - MakePrivate(Sci, member); - } - if (name == null) // rename var with starting underscore - { - name = member.Name; - string newName = GetNewPropertyNameFor(member); - if (RenameMember(Sci, member, newName)) member.Name = newName; - } - } - - int atLine = latest.LineTo + 1; - if (location == PropertiesGenerationLocations.BeforeVariableDeclaration) - atLine = latest.LineTo; - int position = Sci.PositionFromLine(atLine) - ((Sci.EOLMode == 0) ? 2 : 1); - - if (job == GeneratorJobType.GetterSetter) - { - Sci.SetSel(position, position); - GenerateGetterSetter(name, member, position); - } - else - { - if (job != GeneratorJobType.Getter) - { - Sci.SetSel(position, position); - GenerateSetter(name, member, position); - } - if (job != GeneratorJobType.Setter) - { - Sci.SetSel(position, position); - GenerateGetter(name, member, position); - } - } - } - finally - { - Sci.EndUndoAction(); - } - } - - private static void AssignStatementToVar(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member) - { - int lineNum = Sci.LineFromPosition(Sci.CurrentPos); - string line = Sci.GetLine(lineNum); - StatementReturnType returnType = GetStatementReturnType(Sci, inClass, line, Sci.PositionFromLine(lineNum)); - - if (returnType == null) + } + + protected virtual void GenerateProperty(GeneratorJobType job, ScintillaControl sci, ClassModel inClass, MemberModel member) + { + var name = GetPropertyNameFor(member); + PropertiesGenerationLocations location; + var latest = TemplateUtils.GetTemplateBlockMember(sci, TemplateUtils.GetBoundary("AccessorsMethods")); + if (latest != null) location = PropertiesGenerationLocations.AfterLastPropertyDeclaration; + else { - return; + location = ASContext.CommonSettings.PropertiesGenerationLocation; + if (location == PropertiesGenerationLocations.AfterLastPropertyDeclaration) + { + if (job == GeneratorJobType.Getter || job == GeneratorJobType.Setter) + latest = ASComplete.FindMember(name ?? member.Name, inClass); + latest ??= FindLatest(FlagType.Getter | FlagType.Setter, 0, inClass, false, false); + } + else latest = member; } - - string type = null; - string varname = null; - ASResult resolve = returnType.resolve; - string word = returnType.word; - - if (resolve != null && !resolve.IsNull()) + if (latest is null) return; + sci.BeginUndoAction(); + try { - if (resolve.Member != null && resolve.Member.Type != null) + if ((member.Access & Visibility.Public) > 0) MakePrivate(sci, member, inClass); + if (name is null) // rename var with starting underscore { - type = resolve.Member.Type; + name = member.Name; + var newName = GetNewPropertyNameFor(member); + if (RenameMember(sci, member, newName)) member.Name = newName; } - else if (resolve.Type != null && resolve.Type.Name != null) + var startsWithNewLine = true; + var endsWithNewLine = false; + int atLine; + if (location == PropertiesGenerationLocations.BeforeVariableDeclaration) atLine = latest.LineTo; + else if (job == GeneratorJobType.Getter && (latest.Flags & (FlagType.Dynamic | FlagType.Function)) != 0) { - type = resolve.Type.QualifiedName; + atLine = latest.LineFrom; + var declaration = GetDeclarationAtLine(atLine - 1); + startsWithNewLine = declaration.Member != null; + endsWithNewLine = true; } - - if (resolve.Member != null && resolve.Member.Name != null) + else atLine = latest.LineTo + 1; + var position = sci.PositionFromLine(atLine) - ((sci.EOLMode == 0) ? 2 : 1); + sci.SetSel(position, position); + // for example: private var foo:Function/*(v1:*):void*/ + if ((member.Flags & FlagType.Function) != 0) { - varname = GuessVarName(resolve.Member.Name, type); + member = member.Clone(); + member.Type = ASContext.Context.CodeComplete.ToFunctionDeclarationString(member); } + if (job == GeneratorJobType.GetterSetter) GenerateGetterSetter(name, member, position); + else if (job == GeneratorJobType.Setter) GenerateSetter(name, member, position); + else if (job == GeneratorJobType.Getter) GenerateGetter(name, member, position, startsWithNewLine, endsWithNewLine); } - - if (word != null && Char.IsDigit(word[0])) word = null; - - if (!string.IsNullOrEmpty(word) && (string.IsNullOrEmpty(type) || Regex.IsMatch(type, "(<[^]]+>)"))) - word = null; - - if (!string.IsNullOrEmpty(type) && type.Equals("void", StringComparison.OrdinalIgnoreCase)) - type = null; - - if (varname == null) varname = GuessVarName(word, type); - - if (varname != null && varname == word) - varname = varname.Length == 1 ? varname + "1" : varname[0] + ""; - - string cleanType = null; - if (type != null) cleanType = FormatType(GetShortType(type)); - - string template = TemplateUtils.GetTemplate("AssignVariable"); - template = TemplateUtils.ReplaceTemplateVariable(template, "Name", varname); - template = TemplateUtils.ReplaceTemplateVariable(template, "Type", cleanType); - - int indent = Sci.GetLineIndentation(lineNum); - int pos = Sci.PositionFromLine(lineNum) + indent / Sci.Indent; - - Sci.CurrentPos = pos; - Sci.SetSel(pos, pos); - InsertCode(pos, template); - - if (type != null) + finally { - ClassModel inClassForImport = null; - if (resolve.InClass != null) - { - inClassForImport = resolve.InClass; + sci.EndUndoAction(); + } + } + + static void AssignStatementToVar(ScintillaControl sci, ClassModel inClass) + { + var currentLine = sci.CurrentLine; + var returnType = GetStatementReturnType(sci, inClass, sci.GetLine(currentLine), sci.PositionFromLine(currentLine)); + AssignStatementToVar(sci, inClass, returnType); + } + + static void AssignStatementToVar(ScintillaControl sci, ClassModel inClass, StatementReturnType returnType) + { + var ctx = inClass.InFile.Context; + var resolve = returnType.Resolve; + string type = null; + List expressions = null; + var context = resolve.Context; + if (context != null) + { + // for example: typeof v, delete o[k], ... + if (((ASGenerator) ctx.CodeGenerator).AssignStatementToVar(sci, inClass, context)) return; + // for example: 1 + 1, 1 << 1, ... + var operators = Enumerable.ToHashSet(ctx.Features.ArithmeticOperators + .Select(static it => it.ToString()) + .Concat(ctx.Features.IncrementDecrementOperators) + .Concat(ctx.Features.BitwiseOperators) + .Concat(ctx.Features.BooleanOperators) + .Concat(ctx.Features.TernaryOperators)); + var sep = new[] {' '}; + var isValid = new Func(c => c.Separator.Contains(' ') + && c.Separator.Split(sep, StringSplitOptions.RemoveEmptyEntries).Any(it => operators.Contains(it.Trim()))); + if (operators.Contains(context.Separator) || operators.Contains(context.RightOperator) || isValid(context)) + { + if (context.Separator == "/" || context.Separator == "%") type = ctx.Features.numberKey; + var current = resolve; + context = current.Context; + expressions = new List {current}; + var rop = false; + while (operators.Contains(context.Separator) || (rop = operators.Contains(context.RightOperator)) || isValid(context)) + { + if (type is null && (context.Separator == "/" || context.Separator == "%")) type = ctx.Features.numberKey; + var position = rop ? context.PositionExpression : context.SeparatorPosition; + current = ASComplete.GetExpressionType(sci, position, false, true); + if (current is null || current.IsNull()) break; + expressions.Add(current); + context = current.Context; + rop = false; + } } - else if (resolve.RelClass != null) + } + int pos; + if (expressions is null) pos = GetStartOfStatement(resolve); + else + { + var last = expressions.Last(); + pos = last.Context.Separator != ";" ? last.Context.SeparatorPosition : last.Context.PositionExpression; + var first = expressions.First(); + if (ctx.Features.BooleanOperators.Contains(first.Context.Separator)) type = ctx.Features.booleanKey; + } + if (type is null + && resolve.Member is null && resolve.Type.Flags.HasFlag(FlagType.Class) + && resolve.Type.Name != ctx.Features.booleanKey + && resolve.Type.Name != "Function" + && !string.IsNullOrEmpty(resolve.Path) && !char.IsDigit(resolve.Path[0])) + { + var expr = ASComplete.GetExpression(sci, returnType.Position); + if (string.IsNullOrEmpty(expr.WordBefore)) { - inClassForImport = resolve.RelClass; + var characters = ScintillaControl.Configuration.GetLanguage(ctx.Settings.LanguageId.ToLower()).characterclass.Characters; + if (resolve.Path.All(it => characters.Contains(it))) + { + type = inClass.InFile.haXe + ? "Class" + : ctx.ResolveType("Class", resolve.InFile).QualifiedName; + } } - else + } + + var word = returnType.Word; + if (!string.IsNullOrEmpty(word) && char.IsDigit(word[0])) word = null; + string varname = null; + if (string.IsNullOrEmpty(type) && !resolve.IsNull()) + { + if (resolve.Member?.Type != null) type = resolve.Member.Type; + else if (resolve.Type?.Name != null) { - inClassForImport = inClass; + type = resolve.Type.QualifiedName; + if (resolve.Type.IndexType == "*") type += ".<*>"; + else if (resolve.Type.FullName.Contains(".")) type = resolve.Type.FullName.Replace(".", ".>"); } - List l = new List(); - l.Add(getQualifiedType(type, inClassForImport)); - pos += AddImportsByName(l, Sci.LineFromPosition(pos)); + + if (resolve.Member?.Name != null) varname = GuessVarName(resolve.Member.Name, type); + } + if (!string.IsNullOrEmpty(word) && (string.IsNullOrEmpty(type) || Regex.IsMatch(type, "(<[^]]+>)"))) word = null; + if (type == ctx.Features.voidKey) type = null; + varname ??= GuessVarName(word, type); + if (varname != null && varname == word) varname = varname.Length == 1 ? varname + "1" : varname[0] + ""; + ((ASGenerator) ctx.CodeGenerator).AssignStatementToVar(sci, pos, varname, type); + } + + protected virtual void AssignStatementToVar(ScintillaControl sci, int position, string name, string type) + { + var template = TemplateUtils.GetTemplate("AssignVariable"); + template = TemplateUtils.ReplaceTemplateVariable(template, "Name", AvoidKeyword(name)); + template = TemplateUtils.ReplaceTemplateVariable(template, "Type", GetShortType(type)); + sci.SetSel(position, position); + InsertCode(position, template, sci); + if (ASContext.Context.Settings.GenerateImports && type != null) + { + var types = GetQualifiedTypes(new [] {type}, ASContext.Context.CurrentModel); + position += AddImportsByName(types, sci.LineFromPosition(position)); + sci.SetSel(position, position); } } - private static void EventMetatag(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member) + protected virtual bool AssignStatementToVar(ScintillaControl sci, ClassModel inClass, ASExpr expr) + { + var ctx = inClass.InFile.Context; + ClassModel type; + switch (expr.WordBefore) + { + case "typeof": + type = ctx.ResolveType(ctx.Features.stringKey, inClass.InFile); + break; + case "delete": + type = ctx.ResolveType(ctx.Features.booleanKey, inClass.InFile); + break; + default: + return false; + } + var varName = GuessVarName(type.Name, type.Type); + varName = AvoidKeyword(varName); + var template = TemplateUtils.GetTemplate("AssignVariable"); + template = TemplateUtils.ReplaceTemplateVariable(template, "Name", varName); + template = TemplateUtils.ReplaceTemplateVariable(template, "Type", type.Name); + var pos = expr.WordBeforePosition; + sci.SetSel(pos, pos); + InsertCode(pos, template, sci); + return true; + } + + protected internal static string AvoidKeyword(string word) { - ASResult resolve = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); - string line = Sci.GetLine(inClass.LineFrom); - int position = Sci.PositionFromLine(inClass.LineFrom) + (line.Length - line.TrimStart().Length); + var features = ASContext.Context.Features; + return features.accessKeywords.Contains(word) + || features.codeKeywords.Contains(word) + || features.declKeywords.Contains(word) + || features.typesKeywords.Contains(word) + || features.typesPreKeys.Contains(word) + || features.Literals.Contains(word) + ? $"{word}Value" + : word; + } - string value = resolve.Member.Value; + static void EventMetatag(ScintillaControl sci, MemberModel inClass) + { + var resolve = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true)); + var line = sci.GetLine(inClass.LineFrom); + var position = sci.PositionFromLine(inClass.LineFrom) + (line.Length - line.TrimStart().Length); + var value = resolve.Member.Value; if (value != null) { - if (value.StartsWith("\"")) - { - value = value.Trim(new char[] { '"' }); - } - else if (value.StartsWith("'")) - { - value = value.Trim(new char[] { '\'' }); - } + if (value.StartsWith('\"')) value = value.Trim('"'); + else if (value.StartsWith('\'')) value = value.Trim('\''); } else value = resolve.Member.Type; + if (string.IsNullOrEmpty(value)) return; - if (value == "" || value == null) - return; - - Regex re1 = new Regex("'(?:[^'\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*'"); - Regex re2 = new Regex("\"(?:[^\"\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*\""); - Match m1 = re1.Match(value); - Match m2 = re2.Match(value); + var re1 = new Regex("'(?:[^'\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*'"); + var re2 = new Regex("\"(?:[^\"\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*\""); + var m1 = re1.Match(value); + var m2 = re2.Match(value); if (m1.Success || m2.Success) { - Match m = null; - if (m1.Success && m2.Success) m = m1.Index > m2.Index ? m2 : m1; - else if (m1.Success) m = m1; - else m = m2; + Match m = m1.Success switch + { + true when m2.Success => m1.Index > m2.Index ? m2 : m1, + true => m1, + _ => m2 + }; value = value.Substring(m.Index + 1, m.Length - 2); } - string template = TemplateUtils.GetTemplate("EventMetatag"); + var template = TemplateUtils.GetTemplate("EventMetatag"); template = TemplateUtils.ReplaceTemplateVariable(template, "Name", value); template = TemplateUtils.ReplaceTemplateVariable(template, "Type", contextParam); template += "\n$(Boundary)"; AddLookupPosition(); - Sci.CurrentPos = position; - Sci.SetSel(position, position); - InsertCode(position, template); + sci.SetSel(position, position); + InsertCode(position, template, sci); } - private static void ConvertToConst(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member, bool detach) + static void ConvertToConst(ScintillaControl sci, MemberModel member, ClassModel inClass, bool detach) { - String suggestion = "NEW_CONST"; - String label = TextHelper.GetString("ASCompletion.Label.ConstName"); - String title = TextHelper.GetString("ASCompletion.Title.ConvertToConst"); + var suggestion = "NEW_CONST"; + var label = TextHelper.GetString("ASCompletion.Label.ConstName"); + var title = TextHelper.GetString("ASCompletion.Title.ConvertToConst"); - Hashtable info = new Hashtable(); - info["suggestion"] = suggestion; - info["label"] = label; - info["title"] = title; - DataEvent de = new DataEvent(EventType.Command, "ProjectManager.LineEntryDialog", info); + var info = new Hashtable {["suggestion"] = suggestion, ["label"] = label, ["title"] = title}; + var de = new DataEvent(EventType.Command, "ProjectManager.LineEntryDialog", info); EventManager.DispatchEvent(null, de); - if (!de.Handled) - return; - - suggestion = (string)info["suggestion"]; + if (!de.Handled) return; - int position = Sci.CurrentPos; - MemberModel latest = null; + int position = sci.CurrentPos; + int style = sci.BaseStyleAt(position); - int wordPosEnd = Sci.WordEndPosition(position, true); - int wordPosStart = Sci.WordStartPosition(position, true); - char cr = (char)Sci.CharAt(wordPosEnd); - if (cr == '.') - { - wordPosEnd = Sci.WordEndPosition(wordPosEnd + 1, true); - } - else - { - cr = (char)Sci.CharAt(wordPosStart - 1); - if (cr == '.') - { - wordPosStart = Sci.WordStartPosition(wordPosStart - 1, true); - } - } - Sci.SetSel(wordPosStart, wordPosEnd); - string word = Sci.SelText; - Sci.ReplaceSel(suggestion); + int wordPosEnd = position + 1; + int wordPosStart = position; + + while (sci.BaseStyleAt(wordPosEnd) == style) wordPosEnd++; + while (sci.BaseStyleAt(wordPosStart - 1) == style) wordPosStart--; + + sci.SetSel(wordPosStart, wordPosEnd); + var word = sci.SelText; + suggestion = (string)info["suggestion"]; + sci.ReplaceSel(suggestion); - if (member == null) + if (member is null) { detach = false; lookupPosition = -1; - position = Sci.WordStartPosition(Sci.CurrentPos, true); - Sci.SetSel(position, Sci.WordEndPosition(position, true)); + position = sci.WordStartPosition(sci.CurrentPos, true); + sci.SetSel(position, sci.WordEndPosition(position, true)); } else { - latest = GetLatestMemberForVariable(GeneratorJobType.Constant, inClass, - Visibility.Private, new MemberModel("", "", FlagType.Static, 0)); + var latest = GetLatestMemberForVariable(GeneratorJobType.Constant, inClass, Visibility.Private, new MemberModel("", "", FlagType.Static, 0)); if (latest != null) { - position = FindNewVarPosition(Sci, inClass, latest); + if (!member.Flags.HasFlag(FlagType.Function) && sci.LineFromPosition(wordPosStart) is { } line && latest.LineFrom >= line) + { + position = sci.LineIndentPosition(line); + sci.SetSel(position, position); + sci.NewLine(); + detach = false; + } + else position = FindNewVarPosition(sci, inClass, latest); } else { - position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci); + position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci); detach = false; } if (position <= 0) return; - Sci.SetSel(position, position); + sci.SetSel(position, position); } - MemberModel m = NewMember(suggestion, member, FlagType.Variable | FlagType.Constant | FlagType.Static); - m.Type = "Number"; + var m = NewMember(suggestion, member, FlagType.Variable | FlagType.Constant | FlagType.Static, GetDefaultVisibility(inClass)); + m.Type = style switch + { + 4 => ASContext.Context.Features.numberKey, + 6 => ASContext.Context.Features.stringKey, + 7 => ASContext.Context.Features.stringKey, + _ => m.Type + }; + m.Value = word; GenerateVariable(m, position, detach); } - private static void ChangeMethodDecl(ScintillaNet.ScintillaControl Sci, MemberModel member, ClassModel inClass) + static void ChangeMethodDecl(ScintillaControl sci, ClassModel inClass) { - int wordPos = Sci.WordEndPosition(Sci.CurrentPos, true); - List functionParameters = ParseFunctionParameters(Sci, wordPos); - - ASResult funcResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); - if (funcResult.Member == null) - { - return; - } - if (funcResult != null && funcResult.InClass != null && !funcResult.InClass.Equals(inClass)) + var wordPos = sci.WordEndPosition(sci.CurrentPos, true); + var parameters = ParseFunctionParameters(sci, wordPos); + var funcResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true)); + if (funcResult?.Member is null) return; + if (funcResult.InClass != null && !funcResult.InClass.Equals(inClass)) { AddLookupPosition(); lookupPosition = -1; - DockContent dc = ASContext.MainForm.OpenEditableDocument(funcResult.InClass.InFile.FileName, true); - Sci = ASContext.CurSciControl; - - FileModel fileModel = new FileModel(); - fileModel.Context = ASContext.Context; - ASFileParser parser = new ASFileParser(); - parser.ParseSrc(fileModel, Sci.Text); - - foreach (ClassModel cm in fileModel.Classes) + sci = ((ITabbedDocument) PluginBase.MainForm.OpenEditableDocument(funcResult.InClass.InFile.FileName, true)).SciControl; + var fileModel = ASContext.Context.GetCodeModel(sci.Text); + foreach (var cm in fileModel.Classes) { if (cm.QualifiedName.Equals(funcResult.InClass.QualifiedName)) { @@ -1491,43 +1751,40 @@ private static void ChangeMethodDecl(ScintillaNet.ScintillaControl Sci, MemberMo } } inClass = funcResult.InClass; - ASContext.Context.UpdateContext(inClass.LineFrom); } - MemberList members = inClass.Members; - foreach (MemberModel m in members) + foreach (var m in inClass.Members) { - if (m.Name == funcResult.Member.Name) + if (m.Equals(funcResult.Member)) { funcResult.Member = m; + break; } } - ChangeDecl(Sci, funcResult.Member, functionParameters); + ChangeDecl(sci, inClass, funcResult.Member, parameters); } - private static void ChangeConstructorDecl(ScintillaNet.ScintillaControl Sci, MemberModel member, ClassModel inClass) + static void ChangeConstructorDecl(ScintillaControl sci, ClassModel inClass) { - int wordPos = Sci.WordEndPosition(Sci.CurrentPos, true); - List functionParameters = ParseFunctionParameters(Sci, wordPos); - ASResult funcResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); + var position = sci.WordEndPosition(sci.CurrentPos, true); + var parameters = ParseFunctionParameters(sci, position); + ChangeConstructorDecl(sci, inClass, parameters); + } - if (funcResult == null || funcResult.Type == null) return; - if (funcResult.Type != null && !funcResult.Type.Equals(inClass)) + static void ChangeConstructorDecl(ScintillaControl sci, ClassModel inClass, IList parameters) + { + var funcResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true)); + if (funcResult?.Type is null) return; + if (!funcResult.Type.Equals(inClass)) { AddLookupPosition(); lookupPosition = -1; - - DockContent dc = ASContext.MainForm.OpenEditableDocument(funcResult.Type.InFile.FileName, true); - Sci = ASContext.CurSciControl; - - FileModel fileModel = new FileModel(funcResult.Type.InFile.FileName); - fileModel.Context = ASContext.Context; - ASFileParser parser = new ASFileParser(); - parser.ParseSrc(fileModel, Sci.Text); - - foreach (ClassModel cm in fileModel.Classes) + PluginBase.MainForm.OpenEditableDocument(funcResult.Type.InFile.FileName, true); + sci = PluginBase.MainForm.CurrentDocument?.SciControl; + var fileModel = ASContext.Context.GetFileModel(funcResult.Type.InFile.FileName); + foreach (var cm in fileModel.Classes) { if (cm.QualifiedName.Equals(funcResult.Type.QualifiedName)) { @@ -1535,27 +1792,16 @@ private static void ChangeConstructorDecl(ScintillaNet.ScintillaControl Sci, Mem break; } } - inClass = funcResult.Type; ASContext.Context.UpdateContext(inClass.LineFrom); } - - foreach (MemberModel m in inClass.Members) - { - if ((m.Flags & FlagType.Constructor) > 0) - { - funcResult.Member = m; - break; - } - } - - if (funcResult.Member == null) return; - if (isHaxe) funcResult.Member.Name = "new"; - - ChangeDecl(Sci, funcResult.Member, functionParameters); + funcResult.Member = inClass.SearchMember(FlagType.Constructor, false); + if (funcResult.Member is null) return; + if (!string.IsNullOrEmpty(ASContext.Context.Features.ConstructorKey)) funcResult.Member.Name = ASContext.Context.Features.ConstructorKey; + ChangeDecl(sci, inClass, funcResult.Member, parameters); } - private static void ChangeDecl(ScintillaNet.ScintillaControl Sci, MemberModel memberModel, List functionParameters) + static void ChangeDecl(ScintillaControl sci, MemberModel inClass, MemberModel memberModel, IList functionParameters) { bool paramsDiffer = false; if (memberModel.Parameters != null) @@ -1565,10 +1811,10 @@ private static void ChangeDecl(ScintillaNet.ScintillaControl Sci, MemberModel me { if (functionParameters.Count > 0) { - List parameters = memberModel.Parameters; + var parameters = memberModel.Parameters; for (int i = 0; i < parameters.Count; i++) { - MemberModel p = parameters[i]; + var p = parameters[i]; if (p.Type != functionParameters[i].paramType) { paramsDiffer = true; @@ -1588,383 +1834,481 @@ private static void ChangeDecl(ScintillaNet.ScintillaControl Sci, MemberModel me paramsDiffer = true; } - if (paramsDiffer) + if (!paramsDiffer) return; + int app = 0; + var newParameters = new List(); + var existingParameters = memberModel.Parameters; + for (int i = 0; i < functionParameters.Count; i++) { - int app = 0; - List newParameters = new List(); - List existingParameters = memberModel.Parameters; - for (int i = 0; i < functionParameters.Count; i++) + var p = functionParameters[i]; + if (existingParameters != null + && existingParameters.Count > (i - app) + && existingParameters[i - app].Type == p.paramType) { - FunctionParameter p = functionParameters[i]; - if (existingParameters != null - && existingParameters.Count > (i - app) - && existingParameters[i - app].Type == p.paramType) - { - newParameters.Add(existingParameters[i - app]); - } - else - { - if (existingParameters != null && existingParameters.Count < functionParameters.Count) - { - app++; - } - newParameters.Add(new MemberModel(p.paramName, p.paramType, FlagType.ParameterVar, 0)); - } - } - memberModel.Parameters = newParameters; - - int posStart = Sci.PositionFromLine(memberModel.LineFrom); - int posEnd = Sci.LineEndPosition(memberModel.LineTo); - Sci.SetSel(posStart, posEnd); - string selectedText = Sci.SelText; - Regex rStart = new Regex(@"\s{1}" + memberModel.Name + @"\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?"); - Match mStart = rStart.Match(selectedText); - if (!mStart.Success) - { - return; + newParameters.Add(existingParameters[i - app]); } - - int start = mStart.Index + posStart; - int end = start + mStart.Length; - - Sci.SetSel(start, end); - - string decl = TemplateUtils.ToDeclarationString(memberModel, TemplateUtils.GetTemplate("MethodDeclaration")); - InsertCode(Sci.CurrentPos, "$(Boundary) " + decl); - - // add imports to function argument types - if (functionParameters.Count > 0) + else { - List l = new List(); - foreach (FunctionParameter fp in functionParameters) - { - try - { - l.Add(fp.paramQualType); - } - catch (Exception) - { - } - } - start += AddImportsByName(l, Sci.LineFromPosition(end)); + if (existingParameters != null && existingParameters.Count < functionParameters.Count) app++; + newParameters.Add(new MemberModel(AvoidKeyword(p.paramName), GetShortType(p.paramQualType), FlagType.ParameterVar, 0)); } - - Sci.SetSel(start, start); } - } - - private static void AddAsParameter(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member, bool detach) - { - if (!RemoveLocalDeclaration(Sci, contextMember)) return; - - int currLine = Sci.LineFromPosition(Sci.CurrentPos); - - int posStart = Sci.PositionFromLine(member.LineFrom); - int posEnd = Sci.LineEndPosition(member.LineTo); - Sci.SetSel(posStart, posEnd); - string selectedText = Sci.SelText; - Regex rStart = new Regex(@"\s{1}" + member.Name + @"\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?"); - Match mStart = rStart.Match(selectedText); - if (!mStart.Success) - return; - int start = mStart.Index + posStart + 1; - int end = mStart.Index + posStart + mStart.Length; + memberModel.Parameters = newParameters; - Sci.SetSel(start, end); + var posStart = sci.PositionFromLine(memberModel.LineFrom); + var posEnd = sci.LineEndPosition(memberModel.LineTo); + sci.SetSel(posStart, posEnd); + var selectedText = sci.SelText; + var rStart = new Regex(@"\s{1}" + memberModel.Name + @"\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?"); + var mStart = rStart.Match(selectedText); + if (!mStart.Success) return; - MemberModel memberCopy = (MemberModel) member.Clone(); + var start = mStart.Index + posStart; + var end = start + mStart.Length; - if (memberCopy.Parameters == null) - memberCopy.Parameters = new List(); + sci.SetSel(start, end); - memberCopy.Parameters.Add(contextMember); - - string template = TemplateUtils.ToDeclarationString(memberCopy, TemplateUtils.GetTemplate("MethodDeclaration")); - InsertCode(start, template); - - int currPos = Sci.LineEndPosition(currLine); - - Sci.SetSel(currPos, currPos); - Sci.CurrentPos = currPos; - } + var decl = TemplateUtils.ToDeclarationString(memberModel, TemplateUtils.GetTemplate("MethodDeclaration")); + InsertCode(sci.CurrentPos, "$(Boundary) " + decl, sci); - private static void AddInterfaceDefJob(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member, string interf) - { - ClassModel aType = ASContext.Context.ResolveType(interf, ASContext.Context.CurrentModel); - if (aType.IsVoid()) return; - - FileModel fileModel = ASFileParser.ParseFile(ASContext.Context.CreateFileModel(aType.InFile.FileName)); - foreach (ClassModel cm in fileModel.Classes) + // add imports to function argument types + if (ASContext.Context.Settings.GenerateImports && functionParameters.Count > 0) { - if (cm.QualifiedName.Equals(aType.QualifiedName)) - { - aType = cm; - break; - } + var list = functionParameters.Select(static it => it.paramQualType).ToArray(); + var types = GetQualifiedTypes(list, inClass.InFile); + start += AddImportsByName(types, sci.LineFromPosition(end)); } + sci.SetSel(start, start); + } - string template = TemplateUtils.GetTemplate("IFunction"); - if ((member.Flags & FlagType.Getter) > 0) - { - template = TemplateUtils.GetTemplate("IGetter"); - } - else if ((member.Flags & FlagType.Setter) > 0) + static void AddAsParameter(ScintillaControl sci, MemberModel member) + { + if (!RemoveLocalDeclaration(sci, contextMember)) return; + var posStart = sci.PositionFromLine(member.LineFrom); + var posEnd = sci.LineEndPosition(member.LineTo); + sci.SetSel(posStart, posEnd); + var rStart = new Regex(@"\s{1}" + member.Name + @"\s*\(([^\)]*)\)(\s*:\s*([^({{|\n|\r|\s|;)]+))?"); + var mStart = rStart.Match(sci.SelText); + if (!mStart.Success) return; + var start = mStart.Index + posStart + 1; + var end = mStart.Index + posStart + mStart.Length; + sci.SetSel(start, end); + var memberCopy = member.Clone(); + memberCopy.Parameters ??= new List(); + if ((contextMember.Flags & FlagType.Function) != 0 && contextMember.Parameters != null) + { + var parameter = contextMember.Clone(); + parameter.Type = ASContext.Context.CodeComplete.ToFunctionDeclarationString(parameter); + memberCopy.Parameters.Add(parameter); + } + else memberCopy.Parameters.Add(contextMember); + var template = TemplateUtils.ToDeclarationString(memberCopy, TemplateUtils.GetTemplate("MethodDeclaration")); + InsertCode(start, template, sci); + var position = sci.LineEndPosition(sci.CurrentLine); + sci.SetSel(position, position); + if (ASContext.Context.Settings.GenerateImports) { - template = TemplateUtils.GetTemplate("ISetter"); + var imports = new List {contextMember.Type}; + var types = GetQualifiedTypes(imports, ASContext.Context.CurrentModel); + position += AddImportsByName(types, sci.LineFromPosition(position)); + sci.SetSel(position, position); } + } - DockContent dc = ASContext.MainForm.OpenEditableDocument(aType.InFile.FileName, true); - Sci = ASContext.CurSciControl; - - MemberModel latest = GetLatestMemberForFunction(aType, Visibility.Default, new MemberModel()); + static void AddInterfaceDefJob(MemberModel member, MemberModel inClass, string interf) + { + var ctx = ASContext.Context; + var aType = ctx.ResolveType(interf, ctx.CurrentModel); + if (aType.IsVoid()) return; + var fileModel = ctx.GetFileModel(aType.InFile.FileName); + foreach (var cm in fileModel.Classes) + { + if (!cm.QualifiedName.Equals(aType.QualifiedName)) continue; + aType = cm; + break; + } + var sci = ((ITabbedDocument)PluginBase.MainForm.OpenEditableDocument(aType.InFile.FileName, true))?.SciControl; + if (sci is null) return; + var template = ((ASGenerator) ctx.CodeGenerator).GetAddInterfaceDefTemplate(member); + var latest = GetLatestMemberForFunction(aType, Visibility.Default, new MemberModel()); int position; - if (latest == null) - { - position = GetBodyStart(aType.LineFrom, aType.LineTo, Sci); - } + if (latest is null) position = GetBodyStart(aType.LineFrom, aType.LineTo, sci); else { - position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); + position = sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1); template = NewLine + template; } - Sci.SetSel(position, position); - Sci.CurrentPos = position; - - IASContext context = ASContext.Context; - ContextFeatures features = context.Features; - - template = TemplateUtils.ToDeclarationString(member, template); - template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); - template = TemplateUtils.ReplaceTemplateVariable(template, "Void", features.voidKey); - - List importsList = new List(); - string t; - List parms = member.Parameters; - if (parms != null && parms.Count > 0) + string type = null; + if ((member.Flags & FlagType.Setter) != 0) { - for (int i = 0; i < parms.Count; i++) + if (!member.Parameters.IsNullOrEmpty()) { - if (parms[i].Type != null) - { - t = getQualifiedType(parms[i].Type, inClass); - importsList.Add(t); - } + var parameter = member.Parameters[0]; + type = (parameter.Flags & FlagType.Function) != 0 + ? ctx.CodeComplete.ToFunctionDeclarationString(parameter) + : parameter.Type; } + type ??= member.Type; + if (type == ctx.Features.voidKey) type = ctx.Features.dynamicKey; } - - if (member.Type != null) + else type = member.Type ?? ctx.Features.voidKey; + sci.SetSel(position, position); + template = TemplateUtils.ReplaceTemplateVariable(template, "Type", type); + template = TemplateUtils.ToDeclarationString(member, template); + template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); + template = TemplateUtils.ReplaceTemplateVariable(template, "Void", ctx.Features.voidKey); + if (ctx.Settings.GenerateImports) { - t = getQualifiedType(member.Type, inClass); - importsList.Add(t); + var imports = new List(); + var parameters = member.Parameters; + if (!parameters.IsNullOrEmpty()) imports.AddRange(from t in parameters where t.Type != null select t.Type); + if (member.Type != null) imports.Add(member.Type); + if (imports.Count > 0) + { + var types = GetQualifiedTypes(imports, inClass.InFile); + position += AddImportsByName(types, sci.LineFromPosition(position)); + } } + sci.SetSel(position, position); + InsertCode(position, template, sci); + } - if (importsList.Count > 0) - { - int o = AddImportsByName(importsList, Sci.LineFromPosition(position)); - position += o; - - } - - Sci.SetSel(position, position); - Sci.CurrentPos = position; - - InsertCode(position, template); + protected virtual string GetAddInterfaceDefTemplate(MemberModel member) + { + if ((member.Flags & FlagType.Getter) > 0) return TemplateUtils.GetTemplate("IGetter"); + if ((member.Flags & FlagType.Setter) > 0) return TemplateUtils.GetTemplate("ISetter"); + return TemplateUtils.GetTemplate("IFunction"); } - private static void GenerateFieldFromParameter(ScintillaNet.ScintillaControl Sci, MemberModel member, ClassModel inClass, - Visibility scope) + static void GenerateFieldFromParameter(ScintillaControl sci, MemberModel member, ClassModel inClass, Visibility scope) { - int funcBodyStart = GetBodyStart(member.LineFrom, member.LineTo, Sci); + var bodyStart = GetBodyStart(member.LineFrom, member.LineTo, sci, false); + var fbsLine = sci.LineFromPosition(bodyStart); + var endPos = sci.LineEndPosition(member.LineTo); - Sci.SetSel(funcBodyStart, Sci.LineEndPosition(member.LineTo)); - string body = Sci.SelText; - string trimmed = body.TrimStart(); + sci.SetSel(bodyStart, endPos); + var body = sci.SelText; + var trimmed = body.TrimStart(); - Regex re = new Regex("^super\\s*[\\(|\\.]"); - Match m = re.Match(trimmed); - if (m.Success) - { - if (m.Index == 0) - { - int p = funcBodyStart + (body.Length - trimmed.Length); - int l = Sci.LineFromPosition(p); - p = Sci.PositionFromLine(l + 1); - funcBodyStart = GetBodyStart(member.LineFrom, member.LineTo, Sci, p); - } - } + var m = reSuperCall.Match(trimmed); + if (m.Success && m.Index == 0) bodyStart = GetEndOfStatement(bodyStart + (body.Length - trimmed.Length), endPos, sci); - Sci.SetSel(funcBodyStart, funcBodyStart); - Sci.CurrentPos = funcBodyStart; + bodyStart = GetOrSetPointOfInsertion(bodyStart, endPos, fbsLine, sci); - bool isVararg = false; - string paramName = contextMember.Name; - if (paramName.StartsWith("...")) - { - paramName = paramName.TrimStart(new char[] { ' ', '.' }); - isVararg = true; - } - string varName = paramName; - string scopedVarName = varName; + sci.SetSel(bodyStart, bodyStart); + + var paramName = contextMember.Name; + var paramType = contextMember.Type; + paramType = ((ASGenerator) ASContext.Context.CodeGenerator).GetFieldTypeFromParameter(paramType, ref paramName); + + var varName = paramName; + var scopedVarName = varName; if ((scope & Visibility.Public) > 0) { - if ((member.Flags & FlagType.Static) > 0) - scopedVarName = inClass.Name + "." + varName; - else - scopedVarName = "this." + varName; + scopedVarName = (member.Flags & FlagType.Static) > 0 + ? inClass.Name + "." + varName + : "this." + varName; } else { - if (ASContext.CommonSettings.PrefixFields.Length > 0 && !paramName.StartsWith(ASContext.CommonSettings.PrefixFields)) + var prefixFields = ASContext.CommonSettings.PrefixFields; + if (prefixFields.Length > 0 && !varName.StartsWithOrdinal(prefixFields)) { - scopedVarName = varName = ASContext.CommonSettings.PrefixFields + varName; + scopedVarName = varName = prefixFields + varName; } - if (ASContext.CommonSettings.GenerateScope || ASContext.CommonSettings.PrefixFields == "") + if (ASContext.CommonSettings.GenerateScope || prefixFields == "") { - if ((member.Flags & FlagType.Static) > 0) - scopedVarName = inClass.Name + "." + varName; - else - scopedVarName = "this." + varName; + scopedVarName = (member.Flags & FlagType.Static) > 0 + ? inClass.Name + "." + varName + : "this." + varName; } } - - - string template = TemplateUtils.GetTemplate("FieldFromParameter"); + var template = TemplateUtils.GetTemplate("FieldFromParameter"); template = TemplateUtils.ReplaceTemplateVariable(template, "Name", scopedVarName); template = TemplateUtils.ReplaceTemplateVariable(template, "Value", paramName); template += "\n$(Boundary)"; - SnippetHelper.InsertSnippetText(Sci, funcBodyStart, template); + SnippetHelper.InsertSnippetText(sci, bodyStart, template); - MemberList classMembers = inClass.Members; - foreach (MemberModel classMember in classMembers) - if (classMember.Name.Equals(varName)) - return; + if (inClass.ContainsMember(varName, true)) + { + ASContext.Panel.RestoreLastLookupPosition(); + return; + } - MemberModel latest = GetLatestMemberForVariable(GeneratorJobType.Variable, inClass, GetDefaultVisibility(), new MemberModel()); - if (latest == null) return; + var latest = GetLatestMemberForVariable(GeneratorJobType.Variable, inClass, GetDefaultVisibility(inClass), new MemberModel()); + if (latest is null) return; - int position = FindNewVarPosition(Sci, inClass, latest); + var position = FindNewVarPosition(sci, inClass, latest); if (position <= 0) return; - Sci.SetSel(position, position); - Sci.CurrentPos = position; + sci.SetSel(position, position); - MemberModel mem = NewMember(varName, member, FlagType.Variable, scope); - if (isVararg) mem.Type = "Array"; - else mem.Type = contextMember.Type; + var newMember = NewMember(varName, member, FlagType.Variable, scope); + newMember.Type = paramType; - GenerateVariable(mem, position, true); + GenerateVariable(newMember, position, true); ASContext.Panel.RestoreLastLookupPosition(); + if (ASContext.Context.Settings.GenerateImports) + { + var imports = new List {paramType}; + var types = GetQualifiedTypes(imports, inClass.InFile); + position += AddImportsByName(types, sci.LineFromPosition(position)); + sci.SetSel(position, position); + } } - public static int GetBodyStart(int lineFrom, int lineTo, ScintillaNet.ScintillaControl Sci) + protected virtual string GetFieldTypeFromParameter(string paramType, ref string paramName) { - return GetBodyStart(lineFrom, lineTo, Sci, -1); + //for example: foo(v1:Function/*(v1:Type):void*/) + if ((contextMember.Flags & FlagType.Function) != 0) return ASContext.Context.CodeComplete.ToFunctionDeclarationString(new MemberModel {Parameters = contextMember.Parameters, Type = paramType}); + if (paramName.StartsWithOrdinal("...")) + { + paramName = paramName.TrimStart('.'); + return "Array"; + } + return paramType; } - public static int GetBodyStart(int lineFrom, int lineTo, ScintillaNet.ScintillaControl Sci, int pos) + /// + /// Tries to get the best position inside a code block, delimited by { and }, to add new code, inserting new lines if needed. + /// + /// The line inside the Scintilla document where the owner member of the body starts + /// The line inside the Scintilla document where the owner member of the body ends + /// The Scintilla control containing the document + /// The position inside the scintilla document, or -1 if not suitable position was found + public static int GetBodyStart(int lineFrom, int lineTo, ScintillaControl sci) => GetBodyStart(lineFrom, lineTo, sci, true); + + /// + /// Tries to get the start position of a code block, delimited by { and } + /// + /// The line inside the Scintilla document where the owner member of the body starts + /// The line inside the Scintilla document where the owner member of the body ends + /// The Scintilla control containing the document + /// If true looks for the position to add new code, inserting new lines if needed + /// The position inside the Scintilla document, or -1 if not suitable position was found + public static int GetBodyStart(int lineFrom, int lineTo, ScintillaControl sci, bool needsPointOfInsertion) { - int posStart = Sci.PositionFromLine(lineFrom); - int posEnd = Sci.LineEndPosition(lineTo); + int posStart = sci.PositionFromLine(lineFrom); + int posEnd = sci.LineEndPosition(lineTo); + int funcBodyStart = -1; + int genCount = 0, parCount = 0; + for (int i = posStart; i <= posEnd; i++) + { + var c = (char)sci.CharAt(i); + if (c == '{') + { + int style = sci.BaseStyleAt(i); + if (ASComplete.IsCommentStyle(style) || ASComplete.IsLiteralStyle(style) || genCount > 0 || parCount > 0) + continue; + funcBodyStart = i; + break; + } + if (c == '<') + { + int style = sci.BaseStyleAt(i); + if (style == 10) + genCount++; + } + else if (c == '>') + { + int style = sci.BaseStyleAt(i); + if (style == 10 && genCount > 0) + genCount--; + } + else if (c == '(') + { + int style = sci.BaseStyleAt(i); + if (style == 10) + parCount++; + } + else if (c == ')') + { + int style = sci.BaseStyleAt(i); + if (style == 10) + parCount--; + } + } - Sci.SetSel(posStart, posEnd); + if (funcBodyStart == -1) + return -1; - List characterClass = new List(new char[] { ' ', '\r', '\n', '\t' }); - string currentMethodBody = Sci.SelText; - int nCount = 0; - int funcBodyStart = pos; - int extraLine = 0; - if (pos == -1) + if (needsPointOfInsertion) { - funcBodyStart = posStart + currentMethodBody.IndexOf('{'); - extraLine = 1; + int ln = sci.LineFromPosition(funcBodyStart); + + funcBodyStart++; + return GetOrSetPointOfInsertion(funcBodyStart, posEnd, ln, sci); + } + + return funcBodyStart + 1; + } + + [Obsolete(message: "Please use ASGenerator.GetStartOfStatement(expr) instead of ASGenerator.GetStartOfStatement(sci, statementEnd, expr)")] + public static int GetStartOfStatement(ScintillaControl sci, int statementEnd, ASResult expr) => GetStartOfStatement(expr); + + public static int GetStartOfStatement(ASResult expr) + { + if (expr.Type != null) + { + var wordBefore = expr.Context.WordBefore; + if (!string.IsNullOrEmpty(wordBefore) && ASContext.Context.Features.codeKeywords.Contains(wordBefore)) return expr.Context.WordBeforePosition; } - while (funcBodyStart <= posEnd) + return expr.Context.PositionExpression; + } + + /// + /// Tries to get the best position after a statement, to add new code, inserting new lines if needed. + /// + /// The position inside the Scintilla document where the statement starts + /// The position inside the Scintilla document where the owner member of the statement ends + /// The Scintilla control containing the document + /// The position inside the Scintilla document + /// For now internal because for the current use we don't need to detect a lot of cases! use with caution! + public static int GetEndOfStatement(int startPos, int endPos, ScintillaControl sci) + { + var groupCount = 0; + var brCount = 0; + var statementEnd = startPos; + while (statementEnd < endPos) { - char c = (char)Sci.CharAt(++funcBodyStart); - if (c == '}') + if (sci.PositionIsOnComment(statementEnd) || sci.PositionIsInString(statementEnd)) { - int ln = Sci.LineFromPosition(funcBodyStart); - int indent = Sci.GetLineIndentation(ln); - if (lineFrom == lineTo || lineFrom == ln) - { - Sci.InsertText(funcBodyStart, Sci.NewLineMarker); - Sci.SetLineIndentation(ln + 1, indent); - ln++; - } - Sci.SetLineIndentation(ln, indent + Sci.Indent); - Sci.InsertText(funcBodyStart, Sci.NewLineMarker); - Sci.SetLineIndentation(ln + 1, indent); - Sci.SetLineIndentation(ln, indent + Sci.Indent); - funcBodyStart = Sci.LineEndPosition(ln); - break; + statementEnd++; + continue; + } + var endOfStatement = false; + var c = (char)sci.CharAt(statementEnd++); + switch (c) + { + case '\r': + case '\n': + case ',': + endOfStatement = groupCount == 0 && brCount == 0; + break; + case ';': + endOfStatement = brCount == 0; // valid or invalid end of statement + break; + case '(': + case '[': + groupCount++; + break; + case '{': + brCount++; + break; + case ')': + case ']': + groupCount--; + endOfStatement = groupCount < 0; + break; + case '}': + brCount--; + endOfStatement = brCount < 0; + break; } - else if (!characterClass.Contains(c)) + if (endOfStatement) break; + } + return statementEnd; + } + + /// + /// Looks for the best next position to insert new code, inserting new lines if needed + /// + /// The position inside the Scintilla document to start looking for the insertion position + /// The end position inside the Scintilla document + /// The line inside the document to use as the base for the indentation level and detect if the desired point + /// matches the end line + /// The ScintillaControl where our document resides + /// The insertion point position + static int GetOrSetPointOfInsertion(int startPos, int endPos, int baseLine, ScintillaControl sci) + { + char[] characterClass = { ' ', '\r', '\n', '\t' }; + int nCount = 0; + int extraLine = 1; + + int initialLn = sci.LineFromPosition(startPos); + int baseIndent = sci.GetLineIndentation(baseLine); + + bool found = false; + while (startPos <= endPos) + { + char c = (char)sci.CharAt(startPos); + if (!characterClass.Contains(c)) { + int endLn = sci.LineFromPosition(startPos); + if (endLn == baseLine || endLn == initialLn) + { + sci.InsertText(startPos, sci.NewLineMarker); + // Do we want to set the line indentation no matter what? {\r\t\t\t\r} -> {\r\t\r} + // Better results in most cases, but maybe highly unwanted in others? + sci.SetLineIndentation(++endLn, baseIndent + sci.Indent); + startPos = sci.LineIndentPosition(endLn); + } + if (c == '}') + { + sci.InsertText(startPos, sci.NewLineMarker); + sci.SetLineIndentation(endLn + 1, baseIndent); + // In relation with previous comment... we'll reinden this one: {\r} -> {\r\t\r} + if (sci.GetLineIndentation(endLn) <= baseIndent) + { + sci.SetLineIndentation(endLn, baseIndent + sci.Indent); + startPos = sci.LineIndentPosition(endLn); + } + } + found = true; break; } - else if (Sci.EOLMode == 1 && c == '\r' && (++nCount) > extraLine) + if (sci.EOLMode == 1 && c == '\r' && (++nCount) > extraLine) { + found = true; break; } - else if (c == '\n' && (++nCount) > extraLine) + if (c == '\n' && (++nCount) > extraLine) { - if (Sci.EOLMode != 2) + if (sci.EOLMode != 2) { - funcBodyStart--; + startPos--; } + found = true; break; } + startPos++; } - return funcBodyStart; + + if (!found) startPos--; + + return startPos; } - private static void GenerateToString(ClassModel inClass, ScintillaNet.ScintillaControl Sci, MemberModel member) + static void GenerateToString(ScintillaControl sci, ClassModel inClass) { - MemberModel resultMember = new MemberModel("toString", "String", FlagType.Function, Visibility.Public); - - bool isOverride = false; + var resultMember = new MemberModel("toString", ASContext.Context.Features.stringKey, FlagType.Function, Visibility.Public); inClass.ResolveExtends(); - if (inClass.Extends != null) + var extends = inClass.Extends; + while (!extends.IsVoid() && extends.QualifiedName != "Object") { - ClassModel aType = inClass.Extends; - while (!aType.IsVoid() && aType.QualifiedName != "Object") + if (extends.Members.Contains("toString")) { - foreach (MemberModel method in aType.Members) - { - if (method.Name == "toString") - { - isOverride = true; - break; - } - } - if (isOverride) - { - resultMember.Flags |= FlagType.Override; - break; - } - // interface inheritance - aType = aType.Extends; + resultMember.Flags |= FlagType.Override; + break; } + extends = extends.Extends; } - MemberList members = inClass.Members; - StringBuilder membersString = new StringBuilder(); - StringBuilder oneMembersString; - int len = 0; - int indent = Sci.GetLineIndentation(Sci.LineFromPosition(Sci.CurrentPos)); - foreach (MemberModel m in members) + var membersString = new StringBuilder(); + var len = 0; + foreach (var m in inClass.Members) { if (((m.Flags & FlagType.Variable) > 0 || (m.Flags & FlagType.Getter) > 0) && (m.Access & Visibility.Public) > 0 && (m.Flags & FlagType.Constant) == 0) { - oneMembersString = new StringBuilder(); - oneMembersString.Append(" ").Append(m.Name).Append("=\" + ").Append(m.Name).Append(" + "); - membersString.Append(oneMembersString); - len += oneMembersString.Length; + var sb = new StringBuilder(); + sb.Append(" ").Append(m.Name).Append("=\" + ").Append(m.Name).Append(" + "); + membersString.Append(sb); + len += sb.Length; if (len > 80) { len = 0; @@ -1973,39 +2317,29 @@ private static void GenerateToString(ClassModel inClass, ScintillaNet.ScintillaC membersString.Append("\""); } } - - - string template = TemplateUtils.GetTemplate("ToString"); - string result = TemplateUtils.ToDeclarationWithModifiersString(resultMember, template); - result = TemplateUtils.ReplaceTemplateVariable(result, "Body", "\"[" + inClass.Name + membersString.ToString() + "]\""); - - InsertCode(Sci.CurrentPos, result); + var template = TemplateUtils.GetTemplate("ToString"); + var result = ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(resultMember, template); + result = TemplateUtils.ReplaceTemplateVariable(result, "Body", "\"[" + inClass.Name + membersString + "]\""); + InsertCode(sci.CurrentPos, result, sci); } - private static void GenerateVariableJob(GeneratorJobType job, ScintillaNet.ScintillaControl Sci, MemberModel member, - bool detach, ClassModel inClass) + static void GenerateVariableJob(GeneratorJobType job, ScintillaControl sci, MemberModel member, bool detach, ClassModel inClass) { - int position = 0; - MemberModel latest = null; - bool isOtherClass = false; - - Visibility varVisi = job.Equals(GeneratorJobType.Variable) ? GetDefaultVisibility() : Visibility.Public; - FlagType ft = job.Equals(GeneratorJobType.Constant) ? FlagType.Constant : FlagType.Variable; - + var wordStartPos = sci.WordStartPosition(sci.CurrentPos, true); + var visibility = job.Equals(GeneratorJobType.Variable) ? GetDefaultVisibility(inClass) : Visibility.Public; // evaluate, if the variable (or constant) should be generated in other class - ASResult varResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); - - int contextOwnerPos = GetContextOwnerEndPos(Sci, Sci.WordStartPosition(Sci.CurrentPos, true)); - MemberModel isStatic = new MemberModel(); + var varResult = ASComplete.GetExpressionType(sci, sci.WordEndPosition(sci.CurrentPos, true)); + if (member != null && ASContext.CommonSettings.GenerateScope && !varResult.Context.Value.Contains(ASContext.Context.Features.dot)) AddExplicitScopeReference(sci, inClass, member); + var contextOwnerPos = GetContextOwnerEndPos(sci, sci.WordStartPosition(sci.CurrentPos, true)); + var isStatic = new MemberModel(); if (contextOwnerPos != -1) { - ASResult contextOwnerResult = ASComplete.GetExpressionType(Sci, contextOwnerPos); - if (contextOwnerResult != null) + var contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos); + if (contextOwnerResult != null + && (contextOwnerResult.Member is null || (contextOwnerResult.Member.Flags & FlagType.Constructor) > 0) + && contextOwnerResult.Type != null) { - if (contextOwnerResult.Member == null && contextOwnerResult.Type != null) - { - isStatic.Flags |= FlagType.Static; - } + isStatic.Flags |= FlagType.Static; } } else if (member != null && (member.Flags & FlagType.Static) > 0) @@ -2014,413 +2348,287 @@ private static void GenerateVariableJob(GeneratorJobType job, ScintillaNet.Scint } ASResult returnType = null; - int lineNum = Sci.LineFromPosition(Sci.CurrentPos); - string line = Sci.GetLine(lineNum); + var lineNum = sci.CurrentLine; + var line = sci.GetLine(lineNum); - Match m = Regex.Match(line, "\\b" + Regex.Escape(contextToken) + "\\("); - if (m.Success) + if (Regex.IsMatch(line, "\\b" + Regex.Escape(contextToken) + "\\(")) { - returnType = new ASResult(); - returnType.Type = ASContext.Context.ResolveType("Function", null); + returnType = new ASResult {Type = ASContext.Context.ResolveType("Function", null)}; } else { - m = Regex.Match(line, @"=\s*[^;\n\r}}]+"); - if (m.Success) + for (int i = sci.WordEndPosition(sci.CurrentPos, true), length = sci.Length; i < length; i++) { - int posLineStart = Sci.PositionFromLine(lineNum); - if (posLineStart + m.Index >= Sci.CurrentPos) + if (sci.PositionIsOnComment(i)) continue; + var c = sci.CharAt(i); + if (c <= ' ') continue; + if (c == '=') { - line = line.Substring(m.Index); - StatementReturnType rType = GetStatementReturnType(Sci, inClass, line, posLineStart + m.Index); - if (rType != null) - { - returnType = rType.resolve; - } + i = GetEndOfStatement(i, sci.Length, sci) - 1; + returnType = ASComplete.GetExpressionType(sci, i, false, true); } + break; } } - + var isOtherClass = false; if (varResult.RelClass != null && !varResult.RelClass.IsVoid() && !varResult.RelClass.Equals(inClass)) { AddLookupPosition(); lookupPosition = -1; - - ASContext.MainForm.OpenEditableDocument(varResult.RelClass.InFile.FileName, false); - Sci = ASContext.CurSciControl; - isOtherClass = true; - - FileModel fileModel = new FileModel(); - fileModel.Context = ASContext.Context; - ASFileParser parser = new ASFileParser(); - parser.ParseSrc(fileModel, Sci.Text); - - foreach (ClassModel cm in fileModel.Classes) + sci = ((ITabbedDocument)PluginBase.MainForm.OpenEditableDocument(varResult.RelClass.InFile.FileName, false))?.SciControl; + if (sci is null) return; + var fileModel = ASContext.Context.GetCodeModel(sci.Text); + foreach (var cm in fileModel.Classes) { - if (cm.QualifiedName.Equals(varResult.RelClass.QualifiedName)) - { - varResult.RelClass = cm; - break; - } + if (!cm.QualifiedName.Equals(varResult.RelClass.QualifiedName)) continue; + varResult.RelClass = cm; + break; } inClass = varResult.RelClass; - ASContext.Context.UpdateContext(inClass.LineFrom); + isOtherClass = true; } - latest = GetLatestMemberForVariable(job, inClass, varVisi, isStatic); - + var latest = GetLatestMemberForVariable(job, inClass, visibility, isStatic); + int position; // if we generate variable in current class.. - if (!isOtherClass && member == null) + if (!isOtherClass && (member is null + // TODO slavara: temporary solution for #2477 + || (member.Name is null && member.Type is null && member.Access == 0 && member.Flags == FlagType.Static))) { detach = false; lookupPosition = -1; - position = Sci.WordStartPosition(Sci.CurrentPos, true); - Sci.SetSel(position, Sci.WordEndPosition(position, true)); + position = sci.WordStartPosition(sci.CurrentPos, true); + sci.SetSel(position, sci.WordEndPosition(position, true)); } else // if we generate variable in another class { if (latest != null) { - position = FindNewVarPosition(Sci, inClass, latest); + position = FindNewVarPosition(sci, inClass, latest); } else { - position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci); + position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci); detach = false; } if (position <= 0) return; - Sci.SetSel(position, position); + sci.SetSel(position, position); } // if this is a constant, we assign a value to constant string returnTypeStr = null; - string eventValue = null; - if (job == GeneratorJobType.Constant && returnType == null) - { - isStatic.Flags |= FlagType.Static; - eventValue = "String = \"" + Camelize(contextToken) + "\""; - } + if (job == GeneratorJobType.Constant && returnType is null) isStatic.Flags |= FlagType.Static; else if (returnType != null) { - ClassModel inClassForImport = null; - if (returnType.InClass != null) - { - inClassForImport = returnType.InClass; - } - else if (returnType.RelClass != null) - { - inClassForImport = returnType.RelClass; - } - else + if (returnType.Member != null) { - inClassForImport = inClass; + if ((returnType.Member.Flags & FlagType.Function) != 0 && returnType.Context.Value[returnType.Context.Value.Length - 1] != '~') + returnTypeStr = ASContext.Context.CodeComplete.ToFunctionDeclarationString(returnType.Member); + else if (returnType.Member.Type != ASContext.Context.Features.voidKey) + returnTypeStr = returnType.Member.Type; } - List imports = new List(); - if (returnType.Member != null) + else if (returnType.Type != null) returnTypeStr = GetShortType(returnType.Type.QualifiedName); + if (ASContext.Context.Settings.GenerateImports) { - if (returnType.Member.Type != ASContext.Context.Features.voidKey) + ClassModel inClassForImport; + if (returnType.InClass != null) inClassForImport = returnType.InClass; + else if (returnType.RelClass != null) inClassForImport = returnType.RelClass; + else inClassForImport = inClass; + List imports = null; + if (returnType.Member != null) { - returnTypeStr = FormatType(GetShortType(returnType.Member.Type)); - imports.Add(getQualifiedType(returnType.Member.Type, inClassForImport)); + if (returnTypeStr != ASContext.Context.Features.voidKey) imports = new List {returnTypeStr}; + } + else if (returnType.Type != null) imports = new List {returnType.Type.QualifiedName}; + if (imports != null) + { + var types = GetQualifiedTypes(imports, inClassForImport.InFile); + position += AddImportsByName(types, sci.LineFromPosition(position)); + sci.SetSel(position, position); } - } - else if (returnType != null && returnType.Type != null) - { - returnTypeStr = FormatType(GetShortType(returnType.Type.QualifiedName)); - imports.Add(getQualifiedType(returnType.Type.QualifiedName, inClassForImport)); - } - if (imports.Count > 0) - { - position += AddImportsByName(imports, Sci.LineFromPosition(position)); - Sci.SetSel(position, position); } } - MemberModel newMember = NewMember(contextToken, isStatic, ft, varVisi); - if (returnTypeStr != null) + + var kind = job.Equals(GeneratorJobType.Constant) ? FlagType.Constant : FlagType.Variable; + var newMember = NewMember(contextToken, isStatic, kind, visibility); + if (returnTypeStr != null) newMember.Type = returnTypeStr; + else { - newMember.Type = returnTypeStr; + var pos = wordStartPos; + var index = ASComplete.FindParameterIndex(sci, ref pos); + if (pos != -1) + { + var expr = ASComplete.GetExpressionType(sci, pos); + if (expr?.Member?.Parameters.Count > 0) newMember.Type = expr.Member.Parameters[index].Type; + } } - else if (eventValue != null) + if (job == GeneratorJobType.Constant && returnType is null) { - newMember.Type = eventValue; + if (string.IsNullOrEmpty(newMember.Type)) newMember.Type = "String = \"" + Camelize(contextToken) + "\""; + else + { + var value = ASContext.Context.GetDefaultValue(newMember.Type); + if (!string.IsNullOrEmpty(value)) newMember.Type += " = " + value; + } } GenerateVariable(newMember, position, detach); } - private static int GetContextOwnerEndPos(ScintillaNet.ScintillaControl Sci, int worsStartPos) + static int GetContextOwnerEndPos(ScintillaControl sci, int wordStartPos) { - int pos = worsStartPos - 1; - bool dotFound = false; - while (pos > 0) + var result = wordStartPos - 1; + var dotFound = false; + while (result > 0) { - char c = (char) Sci.CharAt(pos); + var c = (char) sci.CharAt(result); if (c == '.' && !dotFound) dotFound = true; else if (c == '\t' || c == '\n' || c == '\r' || c == ' ') { /* skip */ } - else return dotFound ? pos + 1 : -1; - pos--; + else return dotFound ? result + 1 : -1; + result--; } - return pos; + return result; } - static public string Capitalize(string name) - { - return name != null && name.Length > 0 ? Char.ToUpper(name[0]) + name.Substring(1) : name; - } + public static string Capitalize(string name) => !string.IsNullOrEmpty(name) ? char.ToUpper(name[0]) + name.Substring(1) : name; - static public string Camelize(string name) + public static string Camelize(string name) { - name = name.Trim(new char[] { '\'', '"' }); - string[] parts = name.ToLower().Split('_'); - string result = ""; - foreach (string part in parts) + name = name.Trim('\'', '"'); + var parts = name.ToLower().Split('_'); + var result = ""; + foreach (var part in parts) { - if (result.Length > 0) - result += Capitalize(part); + if (result.Length > 0) result += Capitalize(part); else result = part; } return result; } - private static List ParseFunctionParameters(ScintillaNet.ScintillaControl Sci, int p) - { - List prms = new List(); - StringBuilder sb = new StringBuilder(); - List types = new List(); - bool isFuncStarted = false; - bool isDoubleQuote = false; - bool isSingleQuote = false; - bool wasEscapeChar = false; - bool doBreak = false; - bool writeParam = false; - int subClosuresCount = 0; - ASResult result = null; - IASContext ctx = ASContext.Context; - char[] charsToTrim = new char[] { ' ', '\t', '\r', '\n' }; - int counter = Sci.TextLength; // max number of chars in parameters line (to avoid infinitive loop) - string characterClass = ScintillaNet.ScintillaControl.Configuration.GetLanguage(Sci.ConfigurationLanguage).characterclass.Characters; - int lastMemberPos = p; - - // add [] and <> + public static List ParseFunctionParameters(ScintillaControl sci, int p) + { + var prms = new List(); + var sb = new StringBuilder(); + var types = new List(); + var isFuncStarted = false; + var doBreak = false; + var writeParam = false; + var subClosuresCount = 0; + var arrCount = 0; + var ctx = ASContext.Context; + char[] charsToTrim = {' ', '\t', '\r', '\n'}; + var counter = sci.TextLength; // max number of chars in parameters line (to avoid infinitive loop) + var characterClass = ScintillaControl.Configuration.GetLanguage(sci.ConfigurationLanguage).characterclass.Characters; + while (p < counter && !doBreak) { - char c = (char)Sci.CharAt(p++); - if (c == '(' && !isFuncStarted) + if (sci.PositionIsOnComment(p)) { - if (sb.ToString().Trim(charsToTrim).Length == 0) - { - isFuncStarted = true; - } - else - { - break; - } + p++; + continue; } - else if (c == ';' && !isFuncStarted) + if (sci.PositionIsInString(p)) { - break; + sb.Append((char)sci.CharAt(p++)); + continue; + } + var c = (char) sci.CharAt(p++); + if (c == '(' && !isFuncStarted) + { + if (sb.ToString().Trim(charsToTrim).Length == 0) isFuncStarted = true; + else break; } - else if (c == ')' && isFuncStarted && !wasEscapeChar && !isDoubleQuote && !isSingleQuote && subClosuresCount == 0) + else if (c == ';' && !isFuncStarted) break; + else if (c == ')' && isFuncStarted && subClosuresCount == 0) { isFuncStarted = false; writeParam = true; doBreak = true; } - else if ((c == '(' || c == '[' || c == '<' || c == '{') && !wasEscapeChar && !isDoubleQuote && !isSingleQuote) + else if (c == '(' || c == '[' || c == '{') { - if (subClosuresCount == 0) - { - if (c == '[') - { - result = new ASResult(); - result.Type = ctx.ResolveType(ctx.Features.arrayKey, null); - types.Insert(0, result); - } - else if (c == '{') - { - if (sb.ToString().TrimStart().Length > 0) - { - result = new ASResult(); - result.Type = ctx.ResolveType("Function", null); - types.Insert(0, result); - } - else - { - result = new ASResult(); - result.Type = ctx.ResolveType(ctx.Features.objectKey, null); - types.Insert(0, result); - } - } - else if (c == '(') - { - result = ASComplete.GetExpressionType(Sci, lastMemberPos + 1); - if (!result.IsNull()) - { - types.Insert(0, result); - } - } - else if (c == '<') - { - if (sb.ToString().TrimStart().Length == 0) - { - result = new ASResult(); - result.Type = ctx.ResolveType("XML", null); - types.Insert(0, result); - } - } - } + if (c == '[') arrCount++; subClosuresCount++; sb.Append(c); - wasEscapeChar = false; } - else if ((c == ')' || c == ']' || c == '>' || c == '}') && !wasEscapeChar && !isDoubleQuote && !isSingleQuote) + else if (c == ')' || c == ']' || c == '}') { + if (c == ']') arrCount--; subClosuresCount--; sb.Append(c); - wasEscapeChar = false; - } - else if (c == '\\') - { - wasEscapeChar = !wasEscapeChar; - sb.Append(c); - } - else if (c == '"' && !wasEscapeChar && !isSingleQuote) - { - isDoubleQuote = !isDoubleQuote; - if (subClosuresCount == 0) - { - if (isDoubleQuote) - { - result = new ASResult(); - result.Type = ctx.ResolveType("String", null); - types.Add(result); - } - } - sb.Append(c); - wasEscapeChar = false; - } - else if (c == '\'' && !wasEscapeChar && !isDoubleQuote) - { - isSingleQuote = !isSingleQuote; if (subClosuresCount == 0) { - if (isSingleQuote) + if (c == ']' && arrCount == 0) { - result = new ASResult(); - result.Type = ctx.ResolveType("String", null); - types.Add(result); + var cNext = sci.CharAt(p); + if (cNext != '[' && cNext != '.' && cNext != '(') + { + if (!sb.ToString().Contains("<")) + { + var result = ASComplete.GetExpressionType(sci, p); + if (result.Type != null) result.Member = null; + else result.Type = ctx.ResolveType(ctx.Features.arrayKey, null); + types.Insert(0, result); + } + } } } - sb.Append(c); - wasEscapeChar = false; - } - else if (c == ',' && subClosuresCount == 0) - { - if (!isSingleQuote && !isDoubleQuote && subClosuresCount == 0) - { - writeParam = true; - } - else - { - sb.Append(c); - } - wasEscapeChar = false; - } - else if (isFuncStarted) - { - sb.Append(c); - if (!isSingleQuote && !isDoubleQuote && subClosuresCount == 0 && characterClass.IndexOf(c) > -1) - { - lastMemberPos = p - 1; - } - wasEscapeChar = false; - } - else if (characterClass.IndexOf(c) > -1) - { - doBreak = true; } + else if (c == ',' && subClosuresCount == 0) writeParam = true; + else if (isFuncStarted) sb.Append(c); + else if (characterClass.Contains(c)) doBreak = true; if (writeParam) { writeParam = false; - string trimmed = sb.ToString().Trim(charsToTrim); - if (trimmed.Length > 0) + var trimmed = sb.ToString().Trim(charsToTrim); + var trimmedLength = trimmed.Length; + if (trimmedLength > 0) { - result = ASComplete.GetExpressionType(Sci, lastMemberPos + 1); + var last = trimmed[trimmedLength - 1]; + var type = last == '}' && trimmed.StartsWith(ctx.Features.functionKey) + ? ctx.ResolveType("Function", null) + : ctx.ResolveToken(trimmed, ctx.CurrentModel); + var result = type.IsVoid() + ? ASComplete.GetExpressionType(sci, p - 1, false, true) + : new ASResult {Type = type, Context = new ASExpr {Value = trimmed}}; if (result != null && !result.IsNull()) { - if (characterClass.IndexOf(trimmed[trimmed.Length - 1]) > -1) - { - types.Insert(0, result); - } - else - { - types.Add(result); - } - } - else - { - double d = double.MaxValue; - try - { - d = double.Parse(trimmed, System.Globalization.CultureInfo.InvariantCulture); - } - catch (Exception) - { - } - if (d != double.MaxValue && d.ToString().Length == trimmed.Length) - { - result = new ASResult(); - result.Type = ctx.ResolveType(ctx.Features.numberKey, null); - types.Insert(0, result); - } - else if (trimmed.Equals("true") || trimmed.Equals("false")) - { - result = new ASResult(); - result.Type = ctx.ResolveType(ctx.Features.booleanKey, null); - types.Insert(0, result); - } - } - - if (types.Count == 0) - { - result = new ASResult(); - result.Type = ctx.ResolveType(ctx.Features.objectKey, null); - types.Add(result); + if (characterClass.Contains(last)) types.Insert(0, result); + else types.Add(result); } + if (types.Count == 0) types.Add(new ASResult {Type = ctx.ResolveType(ctx.Features.objectKey, null)}); result = types[0]; string paramName = null; - string paramType = null; - string paramQualType = null; + string paramType; + string paramQualType; - if (result.Member == null) + if (result.Member is null) { paramType = result.Type.Name; paramQualType = result.Type.QualifiedName; } else { - if (result.Member.Name != null) - { - paramName = result.Member.Name.Trim('@'); - } - if (result.Member.Type == null || result.Member.Type.Equals("void", StringComparison.OrdinalIgnoreCase)) + if (result.Member.Name != null) paramName = result.Member.Name.Trim('@'); + if (result.Member.Type is null) { - paramType = result.Type.Name; - paramQualType = result.Type.QualifiedName; + paramType = ctx.Features.dynamicKey; + paramQualType = ctx.Features.dynamicKey; } else { - paramType = FormatType(GetShortType(result.Member.Type)); - if (result.InClass == null) - { - paramQualType = result.Type.QualifiedName; - } - else + var flags = result.Member.Flags; + if ((flags & FlagType.Function) != 0 && (flags & FlagType.Getter) == 0 && (flags & FlagType.Setter) == 0 + && !result.Path.EndsWith('~')) { - paramQualType = getQualifiedType(result.Member.Type, result.InClass); + paramType = ctx.CodeComplete.ToFunctionDeclarationString(result.Member); } + else paramType = MemberModel.FormatType(GetShortType(result.Member.Type)); + paramQualType = result.InClass is null + ? result.Type.QualifiedName + : GetQualifiedType(paramType, result.InClass); } } prms.Add(new FunctionParameter(paramName, paramType, paramQualType, result)); @@ -2429,17 +2637,15 @@ private static List ParseFunctionParameters(ScintillaNet.Scin sb = new StringBuilder(); } } - - for (int i = 0; i < prms.Count; i++) + foreach (var parameter in prms) { - if (prms[i].paramType == "void") + if (parameter.paramType == "void") { - prms[i].paramName = "object"; - prms[i].paramType = null; + parameter.paramName = "object"; + parameter.paramType = null; } - else prms[i].paramName = GuessVarName(prms[i].paramName, FormatType(GetShortType(prms[i].paramType))); + else parameter.paramName = GuessVarName(parameter.paramName, MemberModel.FormatType(GetShortType(parameter.paramType))); } - for (int i = 0; i < prms.Count; i++) { int iterator = -1; @@ -2453,8 +2659,7 @@ private static List ParseFunctionParameters(ScintillaNet.Scin bool gotMatch = false; for (int j = 0; j < i; j++) { - if (prms[j] != prms[i] - && prms[j].paramName == suggestedName) + if (prms[j] != prms[i] && prms[j].paramName == suggestedName) { gotMatch = true; break; @@ -2467,54 +2672,67 @@ private static List ParseFunctionParameters(ScintillaNet.Scin return prms; } - private static void GenerateFunctionJob(GeneratorJobType job, ScintillaNet.ScintillaControl Sci, MemberModel member, - bool detach, ClassModel inClass) + static void GenerateConstructorJob(ScintillaControl sci, ClassModel inClass) { - int position = 0; - MemberModel latest = null; - bool isOtherClass = false; - - Visibility funcVisi = job.Equals(GeneratorJobType.FunctionPublic) ? Visibility.Public : GetDefaultVisibility(); - int wordPos = Sci.WordEndPosition(Sci.CurrentPos, true); - List functionParameters = ParseFunctionParameters(Sci, wordPos); - - // evaluate, if the function should be generated in other class - ASResult funcResult = ASComplete.GetExpressionType(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); + const FlagType flags = FlagType.Function | FlagType.Constructor; + var member = new MemberModel(inClass.Name, inClass.QualifiedName, flags, Visibility.Public) + { + Parameters = inClass.SearchMembers(flags, true)?[0].Parameters + // for example: new Type(value); + ?? ParseFunctionParameters(sci, sci.WordEndPosition(sci.CurrentPos, true)) + .Select(static it => new MemberModel(it.paramName, it.paramQualType, FlagType.ParameterVar, 0)) + .ToList() + }; + var currentClass = ASContext.Context.CurrentClass; + if (currentClass != inClass) + { + AddLookupPosition(); + lookupPosition = -1; + if (currentClass.InFile != inClass.InFile) sci = ((ITabbedDocument)PluginBase.MainForm.OpenEditableDocument(inClass.InFile.FileName, false))?.SciControl; + if (sci is null) return; + ASContext.Context.UpdateContext(inClass.LineFrom); + } + var position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci); + sci.SetSel(position, position); + ((ASGenerator) ASContext.Context.CodeGenerator).GenerateFunction(sci, position, inClass, member, false); + } - int contextOwnerPos = GetContextOwnerEndPos(Sci, Sci.WordStartPosition(Sci.CurrentPos, true)); - MemberModel isStatic = new MemberModel(); + static void GenerateFunctionJob(GeneratorJobType job, ScintillaControl sci, MemberModel member, bool detach, ClassModel inClass) + { + var visibility = job.Equals(GeneratorJobType.FunctionPublic) ? Visibility.Public : GetDefaultVisibility(inClass); + var wordStartPos = sci.WordStartPosition(sci.CurrentPos, true); + var wordPos = sci.WordEndPosition(sci.CurrentPos, true); + var parameters = ParseFunctionParameters(sci, wordPos); + // evaluate, if the function should be generated in other class + var funcResult = ASComplete.GetExpressionType(sci, wordPos); + if (member != null && ASContext.CommonSettings.GenerateScope && !funcResult.Context.Value.Contains(ASContext.Context.Features.dot)) AddExplicitScopeReference(sci, inClass, member); + var contextOwnerPos = GetContextOwnerEndPos(sci, wordStartPos); + var isStatic = new MemberModel(); if (contextOwnerPos != -1) { - ASResult contextOwnerResult = ASComplete.GetExpressionType(Sci, contextOwnerPos); - if (contextOwnerResult != null) + var contextOwnerResult = ASComplete.GetExpressionType(sci, contextOwnerPos); + if (contextOwnerResult is not null + && (contextOwnerResult.Member is null || (contextOwnerResult.Member.Flags & FlagType.Constructor) > 0) + && contextOwnerResult.Type is not null) { - if (contextOwnerResult.Member == null && contextOwnerResult.Type != null) - { - isStatic.Flags |= FlagType.Static; - } + isStatic.Flags |= FlagType.Static; } } - else if (member != null && (member.Flags & FlagType.Static) > 0) + else if (member is not null && (member.Flags & FlagType.Static) > 0) { isStatic.Flags |= FlagType.Static; } - - - if (funcResult.RelClass != null && !funcResult.RelClass.IsVoid() && !funcResult.RelClass.Equals(inClass)) + var isOtherClass = false; + if (funcResult.RelClass is not null && !funcResult.RelClass.IsVoid() && !funcResult.RelClass.Equals(inClass)) { AddLookupPosition(); lookupPosition = -1; - DockContent dc = ASContext.MainForm.OpenEditableDocument(funcResult.RelClass.InFile.FileName, true); - Sci = ASContext.CurSciControl; + sci = ((ITabbedDocument)PluginBase.MainForm.OpenEditableDocument(funcResult.RelClass.InFile.FileName, true))?.SciControl; + if (sci is null) return; isOtherClass = true; - - FileModel fileModel = new FileModel(); - fileModel.Context = ASContext.Context; - ASFileParser parser = new ASFileParser(); - parser.ParseSrc(fileModel, Sci.Text); - - foreach (ClassModel cm in fileModel.Classes) + var fileModel = ASContext.Context.GetCodeModel(sci.Text); + foreach (var cm in fileModel.Classes) { if (cm.QualifiedName.Equals(funcResult.RelClass.QualifiedName)) { @@ -2523,321 +2741,320 @@ private static void GenerateFunctionJob(GeneratorJobType job, ScintillaNet.Scint } } inClass = funcResult.RelClass; - ASContext.Context.UpdateContext(inClass.LineFrom); } - string blockTmpl = null; - if ((isStatic.Flags & FlagType.Static) > 0) - { - blockTmpl = TemplateUtils.GetBoundary("StaticMethods"); - } - else if ((funcVisi & Visibility.Public) > 0) - { - blockTmpl = TemplateUtils.GetBoundary("PublicMethods"); - } - else - { - blockTmpl = TemplateUtils.GetBoundary("PrivateMethods"); - } - latest = TemplateUtils.GetTemplateBlockMember(Sci, blockTmpl); - if (latest == null || (!isOtherClass && member == null)) - { - latest = GetLatestMemberForFunction(inClass, funcVisi, isStatic); + string blockTmpl; + if ((isStatic.Flags & FlagType.Static) > 0) blockTmpl = TemplateUtils.GetBoundary("StaticMethods"); + else if ((visibility & Visibility.Public) > 0) blockTmpl = TemplateUtils.GetBoundary("PublicMethods"); + else blockTmpl = TemplateUtils.GetBoundary("PrivateMethods"); + var position = 0; + var latest = TemplateUtils.GetTemplateBlockMember(sci, blockTmpl); + if (latest is null || (!isOtherClass && member is null)) + { + latest = GetLatestMemberForFunction(inClass, visibility, isStatic); // if we generate function in current class.. if (!isOtherClass) { - MethodsGenerationLocations location = ASContext.CommonSettings.MethodsGenerationLocations; - if (member == null) + var location = ASContext.CommonSettings.MethodsGenerationLocations; + if (member is null) { detach = false; lookupPosition = -1; - position = Sci.WordStartPosition(Sci.CurrentPos, true); - Sci.SetSel(position, Sci.WordEndPosition(position, true)); + position = sci.WordStartPosition(sci.CurrentPos, true); + sci.SetSel(position, sci.WordEndPosition(position, true)); } - else if (latest != null && location == MethodsGenerationLocations.AfterSimilarAccessorMethod) + else if (latest is not null && location == MethodsGenerationLocations.AfterSimilarAccessorMethod) { - position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); - Sci.SetSel(position, position); + position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); + sci.SetSel(position, position); } else { - position = Sci.PositionFromLine(member.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); - Sci.SetSel(position, position); + position = sci.PositionFromLine(member.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); + sci.SetSel(position, position); } } else // if we generate function in another class.. { - if (latest != null) + if (latest is not null) { - position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); + position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); } else { - position = GetBodyStart(inClass.LineFrom, inClass.LineTo, Sci); + position = GetBodyStart(inClass.LineFrom, inClass.LineTo, sci); detach = false; } - Sci.SetSel(position, position); + sci.SetSel(position, position); } } else { - position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); - Sci.SetSel(position, position); - } - - // add imports to function argument types - if (functionParameters.Count > 0) - { - List l = new List(); - foreach (FunctionParameter fp in functionParameters) - { - try - { - l.Add(fp.paramQualType); - } - catch (Exception) { } - } - int o = AddImportsByName(l, Sci.LineFromPosition(position)); - position += o; - if (latest == null) - Sci.SetSel(position, Sci.WordEndPosition(position, true)); - else - Sci.SetSel(position, position); - } - - List parameters = new List(); - for (int i = 0; i < functionParameters.Count; i++) - { - string name = functionParameters[i].paramName; - string type = functionParameters[i].paramType; - parameters.Add(new MemberModel(name, type, FlagType.ParameterVar, 0)); + position = sci.PositionFromLine(latest.LineTo + 1) - (sci.EOLMode == 0 ? 2 : 1); + sci.SetSel(position, position); } - MemberModel newMember = NewMember(contextToken, isStatic, FlagType.Function, funcVisi); - newMember.Parameters = parameters; - GenerateFunction(newMember, position, detach, inClass); - } - - private static void GenerateClass(ScintillaNet.ScintillaControl Sci, String className, ClassModel inClass) - { - AddLookupPosition(); // remember last cursor position for Shift+F4 - - List parameters = ParseFunctionParameters(Sci, Sci.WordEndPosition(Sci.CurrentPos, true)); - List constructorArgs = new List(); - List constructorArgTypes = new List(); - MemberModel paramMember = new MemberModel(); - for (int i = 0; i < parameters.Count; i++) + var newMemberType = ASContext.Context.Features.voidKey; + ASResult callerExpr = null; + MemberModel caller = null; + var pos = wordStartPos; + var parameterIndex = ASComplete.FindParameterIndex(sci, ref pos); + if (pos != -1) { - FunctionParameter p = parameters[i]; - constructorArgs.Add(new MemberModel(p.paramName, p.paramType, FlagType.ParameterVar, 0)); - constructorArgTypes.Add(CleanType(getQualifiedType(p.paramQualType, inClass))); + callerExpr = ASComplete.GetExpressionType(sci, pos); + if (callerExpr is not null) caller = callerExpr.Member; } - - paramMember.Parameters = constructorArgs; - - IProject project = PluginBase.CurrentProject; - if (String.IsNullOrEmpty(className)) className = "Class"; - string projFilesDir = Path.Combine(PathHelper.TemplateDir, "ProjectFiles"); - string projTemplateDir = Path.Combine(projFilesDir, project.GetType().Name); - string paramsString = TemplateUtils.ParametersString(paramMember, true); - Hashtable info = new Hashtable(); - info["className"] = className; - if (project.Language.StartsWith("as")) info["templatePath"] = Path.Combine(projTemplateDir, "Class.as.fdt"); - else if (project.Language.StartsWith("haxe")) info["templatePath"] = Path.Combine(projTemplateDir, "Class.hx.fdt"); - else if (project.Language.StartsWith("loom")) info["templatePath"] = Path.Combine(projTemplateDir, "Class.ls.fdt"); - info["inDirectory"] = Path.GetDirectoryName(inClass.InFile.FileName); - info["constructorArgs"] = paramsString.Length > 0 ? paramsString : null; - info["constructorArgTypes"] = constructorArgTypes; - DataEvent de = new DataEvent(EventType.Command, "ProjectManager.CreateNewFile", info); - EventManager.DispatchEvent(null, de); - if (de.Handled) return; - } - - public static void GenerateExtractVariable(ScintillaNet.ScintillaControl Sci, string NewName) - { - FileModel cFile; - IASContext context = ASContext.Context; - Int32 pos = Sci.CurrentPos; - - string expression = Sci.SelText.Trim(new char[] { '=', ' ', '\t', '\n', '\r', ';', '.' }); - expression = expression.TrimEnd(new char[] { '(', '[', '{', '<' }); - expression = expression.TrimStart(new char[] { ')', ']', '}', '>' }); - - cFile = ASContext.Context.CurrentModel; - ASFileParser parser = new ASFileParser(); - parser.ParseSrc(cFile, Sci.Text); - - MemberModel current = cFile.Context.CurrentMember; - - string characterClass = ScintillaNet.ScintillaControl.Configuration.GetLanguage(Sci.ConfigurationLanguage).characterclass.Characters; - - int funcBodyStart = ASGenerator.GetBodyStart(current.LineFrom, current.LineTo, Sci); - Sci.SetSel(funcBodyStart, Sci.LineEndPosition(current.LineTo)); - string currentMethodBody = Sci.SelText; - - bool isExprInSingleQuotes = (expression.StartsWith("'") && expression.EndsWith("'")); - bool isExprInDoubleQuotes = (expression.StartsWith("\"") && expression.EndsWith("\"")); - int stylemask = (1 << Sci.StyleBits) - 1; - int lastPos = -1; - char prevOrNextChar; - Sci.Colourise(0, -1); - while (true) + if (caller is not null && !caller.Parameters.IsNullOrEmpty()) { - lastPos = currentMethodBody.IndexOf(expression, lastPos + 1); - if (lastPos > -1) + static string CleanType(string s) { - if (lastPos > 0) + while (true) { - prevOrNextChar = currentMethodBody[lastPos - 1]; - if (characterClass.IndexOf(prevOrNextChar) > -1) + if (s.StartsWith('(') && s.EndsWith(')')) { + s = s.Trim('(', ')'); continue; } + return s; } - if (lastPos + expression.Length < currentMethodBody.Length) + } + + var param = caller.Parameters[parameterIndex]; + var parameterType = param.Type; + if ((char) sci.CharAt(wordPos) == '(') newMemberType = parameterType; + else + { + var model = ASContext.Context.CodeComplete.FunctionTypeToMemberModel(parameterType, callerExpr.InFile); + if (model != null) { - prevOrNextChar = currentMethodBody[lastPos + expression.Length]; - if (characterClass.IndexOf(prevOrNextChar) > -1) + newMemberType = model.Type; + if (model.Parameters != null) { - continue; + foreach (var it in model.Parameters) + { + var type = CleanType(it.Type); + parameters.Add(new FunctionParameter(it.Name, type, type, null)); + } } } + } + newMemberType = CleanType(newMemberType); + // for example: + // foo(v1) + // function foo(v1:Function/*(v1:Type):void*/) + if ((param.Flags & FlagType.Function) != 0 && parameters.Count != param.Parameters.Count) + { + parameters.Clear(); + parameters.AddRange(param.Parameters.Select(static it => new FunctionParameter(it.Name, it.Type, it.Type, null))); + } + } + // add imports to function argument types + if (ASContext.Context.Settings.GenerateImports && parameters.Count > 0) + { + var types = GetQualifiedTypes(parameters.Select(static it => it.paramQualType), inClass.InFile); + position += AddImportsByName(types, sci.LineFromPosition(position)); + if (latest is null) sci.SetSel(position, sci.WordEndPosition(position, true)); + else sci.SetSel(position, position); + } + var generator = (ASGenerator) ASContext.Context.CodeGenerator; + var newMember = NewMember(contextToken, isStatic, FlagType.Function, visibility); + newMember.Parameters = parameters.Select(generator.ToParameterVar).ToList(); + if (newMemberType != null) newMember.Type = newMemberType; + generator.GenerateFunction(sci, position, inClass, newMember, detach); + } - int style = Sci.StyleAt(funcBodyStart + lastPos) & stylemask; - if (ASComplete.IsCommentStyle(style)) - { - continue; - } - else if ((isExprInDoubleQuotes && currentMethodBody[lastPos] == '"' && currentMethodBody[lastPos + expression.Length - 1] == '"') - || (isExprInSingleQuotes && currentMethodBody[lastPos] == '\'' && currentMethodBody[lastPos + expression.Length - 1] == '\'')) - { - - } - else if (!ASComplete.IsTextStyle(style)) + protected virtual void GenerateFunction(ScintillaControl sci, int position, ClassModel inClass, MemberModel member, bool detach) + { + string template; + if ((inClass.Flags & FlagType.Interface) > 0) + { + template = TemplateUtils.GetTemplate("IFunction"); + template = TemplateUtils.ToDeclarationString(member, template); + } + else if ((member.Flags & FlagType.Constructor) > 0) + { + template = TemplateUtils.GetTemplate("Constructor"); + template = ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(member, template); + string super = null; + if (inClass.ContainsMember(FlagType.Function | FlagType.Constructor, true)) + { + var value = new StringBuilder(); + foreach (var parameter in member.Parameters) { - continue; + if (value.Length != 0) value.Append(", "); + value.Append(parameter.Name); } - - Sci.SetSel(funcBodyStart + lastPos, funcBodyStart + lastPos + expression.Length); - Sci.ReplaceSel(NewName); - currentMethodBody = currentMethodBody.Substring(0, lastPos) + NewName + currentMethodBody.Substring(lastPos + expression.Length); - lastPos += NewName.Length; + value.Insert(0, "super("); + value.Append(");"); + super = value.ToString(); } - else - { + template = TemplateUtils.ReplaceTemplateVariable(template, "Super", super); + var line = sci.LineFromPosition(position); + if (GetDeclarationAtLine(line).Member != null) template += $"{NewLine}{NewLine}{NewLine}"; + else if (GetDeclarationAtLine(line + 1).Member != null) template += $"{NewLine}{NewLine}"; + } + else + { + var body = GetFunctionBody(member, inClass); + template = TemplateUtils.GetTemplate("Function"); + template = ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(member, template); + template = TemplateUtils.ReplaceTemplateVariable(template, "Body", body); + } + GenerateFunction(position, template, detach); + } + + protected virtual string GetFunctionBody(MemberModel member, ClassModel inClass) + { + switch (ASContext.CommonSettings.GeneratedMemberDefaultBodyStyle) + { + case GeneratedMemberBodyStyle.ReturnDefaultValue: + var defaultValue = ASContext.Context.GetDefaultValue(member.Type); + if (!string.IsNullOrEmpty(defaultValue)) return $"return {defaultValue};"; break; - } } + return null; + } - Sci.CurrentPos = funcBodyStart; - Sci.SetSel(Sci.CurrentPos, Sci.CurrentPos); + protected void GenerateFunction(int position, string declaration, bool detach) + { + if (detach) declaration = NewLine + TemplateUtils.ReplaceTemplateVariable(declaration, "BlankLine", NewLine); + else declaration = TemplateUtils.ReplaceTemplateVariable(declaration, "BlankLine", null); + InsertCode(position, declaration); + } - MemberModel m = new MemberModel(NewName, "", FlagType.LocalVar, 0); - m.Value = expression; + static void GenerateClass(ScintillaControl sci, MemberModel inClass, ASExpr data) + { + var position = sci.WordEndPosition(data.PositionExpression, false); + ((ASGenerator) ASContext.Context.CodeGenerator).GenerateClass(sci, position, inClass, data.Value); + } - string snippet = TemplateUtils.GetTemplate("Variable"); - snippet = TemplateUtils.ReplaceTemplateVariable(snippet, "Modifiers", null); - snippet = TemplateUtils.ToDeclarationString(m, snippet); - snippet += NewLine + "$(Boundary)"; - SnippetHelper.InsertSnippetText(Sci, Sci.CurrentPos, snippet); + static void GenerateClass(ScintillaControl sci, MemberModel inClass, string name) + { + var position = sci.WordEndPosition(sci.CurrentPos, true); + ((ASGenerator) ASContext.Context.CodeGenerator).GenerateClass(sci, position, inClass, name); } - public static void GenerateExtractMethod(ScintillaNet.ScintillaControl Sci, string NewName) + protected void GenerateClass(ScintillaControl sci, int position, MemberModel inClass, string name) + => GenerateClass(sci, position, inClass, name, new Hashtable()); + + protected virtual void GenerateClass(ScintillaControl sci, int position, MemberModel inClass, string name, Hashtable info) { - FileModel cFile; - IASContext context = ASContext.Context; + AddLookupPosition(); // remember last cursor position for Shift+F4 + var parameters = ParseFunctionParameters(sci, position); + var constructorArgs = new List(parameters.Count); + var constructorArgTypes = new List(parameters.Count); + foreach (var p in parameters) + { + constructorArgs.Add(new MemberModel(AvoidKeyword(p.paramName), p.paramType, FlagType.ParameterVar, 0)); + constructorArgTypes.Add(CleanType(GetQualifiedType(p.paramQualType, inClass))); + } + var paramMember = new MemberModel {Parameters = constructorArgs}; + var paramsString = TemplateUtils.ParametersString(paramMember, true); + info["className"] = string.IsNullOrEmpty(name) ? "Class" : name; + info["templatePath"] = Path.Combine(PathHelper.TemplateDir, "ProjectFiles", PluginBase.CurrentProject.GetType().Name, $"Class{ASContext.Context.Settings.DefaultExtension}.fdt"); + info["inDirectory"] = Path.GetDirectoryName(inClass.InFile.FileName); + info["constructorArgs"] = paramsString.Length > 0 ? paramsString : null; + info["constructorArgTypes"] = constructorArgTypes; + var de = new DataEvent(EventType.Command, "ProjectManager.CreateNewFile", info); + EventManager.DispatchEvent(null, de); + } - string selection = Sci.SelText; - if (selection == null || selection.Length == 0) - { - return; - } + static void GenerateInterface(ScintillaControl sci, MemberModel inClass, string name) + => ((ASGenerator)ASContext.Context.CodeGenerator).GenerateInterface(sci, inClass, name, new Hashtable()); - if (selection.TrimStart().Length == 0) - { - return; - } + protected virtual void GenerateInterface(ScintillaControl sci, MemberModel inClass, string name, Hashtable info) + { + AddLookupPosition(); // remember last cursor position for Shift+F4 + info["interfaceName"] = string.IsNullOrEmpty(name) ? "IInterface" : name; + info["templatePath"] = Path.Combine(PathHelper.TemplateDir, "ProjectFiles", PluginBase.CurrentProject.GetType().Name, $"Interface{ASContext.Context.Settings.DefaultExtension}.fdt"); + info["inDirectory"] = Path.GetDirectoryName(inClass.InFile.FileName); + var de = new DataEvent(EventType.Command, "ProjectManager.CreateNewFile", info); + EventManager.DispatchEvent(null, de); + } + + public static void GenerateExtractMethod(ScintillaControl sci, string newName) + { + var selection = sci.SelText; + if (string.IsNullOrEmpty(selection)) return; - Sci.SetSel(Sci.SelectionStart + selection.Length - selection.TrimStart().Length, - Sci.SelectionEnd); - Sci.CurrentPos = Sci.SelectionEnd; + var trimmedLength = selection.TrimStart().Length; + if (trimmedLength == 0) return; - Int32 pos = Sci.CurrentPos; + sci.SetSel(sci.SelectionStart + selection.Length - trimmedLength, sci.SelectionEnd); + sci.CurrentPos = sci.SelectionEnd; - int lineStart = Sci.LineFromPosition(Sci.SelectionStart); - int lineEnd = Sci.LineFromPosition(Sci.SelectionEnd); - int firstLineIndent = Sci.GetLineIndentation(lineStart); - int entryPointIndent = Sci.Indent; + int lineStart = sci.LineFromPosition(sci.SelectionStart); + int lineEnd = sci.LineFromPosition(sci.SelectionEnd); + int firstLineIndent = sci.GetLineIndentation(lineStart); + int entryPointIndent = sci.Indent; for (int i = lineStart; i <= lineEnd; i++) { - int indent = Sci.GetLineIndentation(i); + int indent = sci.GetLineIndentation(i); if (i > lineStart) { - Sci.SetLineIndentation(i, indent - firstLineIndent + entryPointIndent); + sci.SetLineIndentation(i, indent - firstLineIndent + entryPointIndent); } } - string selText = Sci.SelText; + string selText = sci.SelText; string template = TemplateUtils.GetTemplate("CallFunction"); - template = TemplateUtils.ReplaceTemplateVariable(template, "Name", NewName); + template = TemplateUtils.ReplaceTemplateVariable(template, "Name", newName); template = TemplateUtils.ReplaceTemplateVariable(template, "Arguments", ""); - - ASGenerator.InsertCode(Sci.CurrentPos, template + ";"); - - cFile = ASContext.Context.CurrentModel; - ASFileParser parser = new ASFileParser(); - parser.ParseSrc(cFile, Sci.Text); - - bool isAs3 = cFile.Context.Settings.LanguageId == "AS3"; - - FoundDeclaration found = GetDeclarationAtLine(Sci, lineStart); - if (found == null || found.member == null) + sci.Colourise(0, -1); + var pos = sci.SelectionEnd - 1; + var endPos = sci.TextLength; + while (pos++ < endPos) { - return; + var style = sci.StyleAt(pos); + if (ASComplete.IsCommentStyle(style)) continue; + var c = (char) sci.CharAt(pos); + if (c == '\n' || c == '\r') + { + template += ";"; + break; + } + if ((c == ';' || c == ',' || c == '.' || c == ')' || c == '}' || c == '{') && !ASComplete.IsStringStyle(style)) break; } + InsertCode(sci.CurrentPos, template, sci); - lookupPosition = Sci.CurrentPos; - AddLookupPosition(); - - MemberModel latest = TemplateUtils.GetTemplateBlockMember(Sci, TemplateUtils.GetBoundary("PrivateMethods")); - - if (latest == null) - latest = GetLatestMemberForFunction(found.inClass, ASGenerator.GetDefaultVisibility(), found.member); + var ctx = ASContext.Context; + ctx.GetCodeModel(ctx.CurrentModel, sci.Text); + var found = ((ASGenerator) ctx.CodeGenerator).GetDeclarationAtLine(lineStart); + if (found.Member is null) return; - if (latest == null) - latest = found.member; + lookupPosition = sci.CurrentPos; + AddLookupPosition(); - int position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); - Sci.SetSel(position, position); + var latest = TemplateUtils.GetTemplateBlockMember(sci, TemplateUtils.GetBoundary("PrivateMethods")) + ?? GetLatestMemberForFunction(found.InClass, GetDefaultVisibility(found.InClass), found.Member) + ?? found.Member; - FlagType flags = FlagType.Function; - if ((found.member.Flags & FlagType.Static) > 0) - { - flags |= FlagType.Static; - } - - MemberModel m = new MemberModel(NewName, context.Features.voidKey, flags, ASGenerator.GetDefaultVisibility()); + var position = sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1); + sci.SetSel(position, position); + var flags = FlagType.Function; + if ((found.Member.Flags & FlagType.Static) > 0) flags |= FlagType.Static; + var member = new MemberModel(newName, ctx.Features.voidKey, flags, GetDefaultVisibility(found.InClass)); template = NewLine + TemplateUtils.GetTemplate("Function"); - template = TemplateUtils.ToDeclarationWithModifiersString(m, template); + template = ((ASGenerator) ctx.CodeGenerator).ToDeclarationWithModifiersString(member, template); template = TemplateUtils.ReplaceTemplateVariable(template, "Body", selText); template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); - InsertCode(position, template); + InsertCode(position, template, sci); } - private static int FindNewVarPosition(ScintillaNet.ScintillaControl Sci, ClassModel inClass, MemberModel latest) + static int FindNewVarPosition(ScintillaControl sci, MemberModel inClass, MemberModel latest) { firstVar = false; // found a var? if ((latest.Flags & FlagType.Variable) > 0) - return Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); + return sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1); // add as first member int line = 0; - int maxLine = Sci.LineCount; - if (inClass != null) + int maxLine = sci.LineCount; + if (inClass is not null) { line = inClass.LineFrom; maxLine = inClass.LineTo; @@ -2846,453 +3063,320 @@ private static int FindNewVarPosition(ScintillaNet.ScintillaControl Sci, ClassMo else maxLine = ASContext.Context.CurrentModel.PrivateSectionIndex; while (line < maxLine) { - string text = Sci.GetLine(line++); - if (text.IndexOf('{') >= 0) + var text = sci.GetLine(line++); + if (text.Contains('{')) { firstVar = true; - return Sci.PositionFromLine(line) - ((Sci.EOLMode == 0) ? 2 : 1); + return sci.PositionFromLine(line) - ((sci.EOLMode == 0) ? 2 : 1); } } return -1; } - private static bool RemoveLocalDeclaration(ScintillaNet.ScintillaControl Sci, MemberModel contextMember) + static bool RemoveLocalDeclaration(ScintillaControl sci, MemberModel contextMember) { int removed = 0; - if (contextResolved != null) + if (contextResolved is not null) { - contextResolved.Context.LocalVars.Items.Sort(new ByDeclarationPositionMemberComparer()); + contextResolved.Context.LocalVars.Items.Sort(ByDeclarationPositionMemberComparer.Instance); contextResolved.Context.LocalVars.Items.Reverse(); - foreach (MemberModel member in contextResolved.Context.LocalVars) + foreach (var member in contextResolved.Context.LocalVars) { if (member.Name == contextMember.Name) { - RemoveOneLocalDeclaration(Sci, member); + RemoveOneLocalDeclaration(sci, member); removed++; } } } - if (removed == 0) return RemoveOneLocalDeclaration(Sci, contextMember); - else return true; + return removed != 0 || RemoveOneLocalDeclaration(sci, contextMember); } - private static bool RemoveOneLocalDeclaration(ScintillaNet.ScintillaControl Sci, MemberModel contextMember) + static bool RemoveOneLocalDeclaration(ScintillaControl sci, MemberModel contextMember) { string type = ""; - if (contextMember.Type != null && (contextMember.Flags & FlagType.Inferred) == 0) + if (contextMember.Type is not null && (contextMember.Flags & FlagType.Inferred) == 0) { - type = FormatType(contextMember.Type); - if (type.IndexOf('*') > 0) - type = type.Replace("/*", @"/\*\s*").Replace("*/", @"\s*\*/"); - type = @":\s*" + type; - } - Regex reDecl = new Regex(String.Format(@"[\s\(]((var|const)\s+{0}\s*{1})\s*", contextMember.Name, type)); - for (int i = contextMember.LineFrom; i <= contextMember.LineTo + 10; i++) - { - string text = Sci.GetLine(i); - Match m = reDecl.Match(text); - if (m.Success) + // for example: var f:Function/*(v1:Type):void*/ + if ((contextMember.Flags & FlagType.Function) != 0) type = ":\\s*Function\\/\\*.*\\*\\/"; + else { - int index = Sci.MBSafeTextLength(text.Substring(0, m.Groups[1].Index)); - int position = Sci.PositionFromLine(i) + index; - int len = Sci.MBSafeTextLength(m.Groups[1].Value); - Sci.SetSel(position, position + len); - if (contextMember.Type == null || (contextMember.Flags & FlagType.Inferred) != 0) Sci.ReplaceSel(contextMember.Name + " "); - else Sci.ReplaceSel(contextMember.Name); - UpdateLookupPosition(position, contextMember.Name.Length - len); - return true; - } + type = MemberModel.FormatType(contextMember.Type); + if (type.IndexOf('*') > 0) + type = type.Replace("/*", @"/\*\s*").Replace("*/", @"\s*\*/"); + type = @":\s*" + type; + } + } + var name = contextMember.Name; + var reDecl = new Regex($@"[\s\(]((var|const)\s+{name}\s*{type})\s*"); + for (var i = contextMember.LineFrom; i <= contextMember.LineTo + 10; i++) + { + var text = sci.GetLine(i); + var m = reDecl.Match(text); + if (!m.Success) continue; + var index = sci.MBSafeTextLength(text.Substring(0, m.Groups[1].Index)); + var position = sci.PositionFromLine(i) + index; + var len = sci.MBSafeTextLength(m.Groups[1].Value); + sci.SetSel(position, position + len); + if (ASContext.CommonSettings.GenerateScope) name = "this." + name; + if (contextMember.Type is null || (contextMember.Flags & FlagType.Inferred) != 0) name += " "; + sci.ReplaceSel(name); + UpdateLookupPosition(position, name.Length - len); + return true; } return false; } - private static StatementReturnType GetStatementReturnType(ScintillaNet.ScintillaControl Sci, ClassModel inClass, string line, int startPos) + internal static StatementReturnType GetStatementReturnType(ScintillaControl sci, ClassModel inClass, string line, int startPos) { - Regex target = new Regex(@"[;\s\n\r]*", RegexOptions.RightToLeft); - Match m = target.Match(line); - if (!m.Success) - { - return null; - } + var target = new Regex(@"[;\s\n\r]*", RegexOptions.RightToLeft); + var m = target.Match(line); + if (!m.Success) return null; line = line.Substring(0, m.Index); - - if (line.Length == 0) - { - return null; - } - - line = ReplaceAllStringContents(line); - - ASResult resolve = null; - int pos = -1; - string word = null; - int stylemask = (1 << Sci.StyleBits) - 1; - ClassModel type = null; - - if (line[line.Length - 1] == ')') - { - pos = -1; - int lastIndex = 0; - int bracesBalance = 0; - while (true) - { - int pos1 = line.IndexOf("(", lastIndex); - int pos2 = line.IndexOf(")", lastIndex); - if (pos1 != -1 && pos2 != -1) - { - lastIndex = Math.Min(pos1, pos2); - } - else if (pos1 != -1 || pos2 != -1) - { - lastIndex = Math.Max(pos1, pos2); - } - else - { - break; - } - if (lastIndex == pos1) - { - bracesBalance++; - if (bracesBalance == 1) - { - pos = lastIndex; - } - } - else if (lastIndex == pos2) - { - bracesBalance--; - } - lastIndex++; - } - } - else - { - pos = line.Length; - } - if (pos != -1) - { - line = line.Substring(0, pos); - pos += startPos; - pos -= line.Length - line.TrimEnd().Length + 1; - pos = Sci.WordEndPosition(pos, true); - resolve = ASComplete.GetExpressionType(Sci, pos); - if (resolve.IsNull()) resolve = null; - word = Sci.GetWordFromPosition(pos); - } - - IASContext ctx = inClass.InFile.Context; - m = Regex.Match(line, "new\\s+([\\w\\d.<>,_$-]+)+(<[^]]+>)|(<[^]]+>)", RegexOptions.IgnoreCase); - - if (m.Success) - { - string m1 = m.Groups[1].Value; - string m2 = m.Groups[2].Value; - - string cname; - if (string.IsNullOrEmpty(m1) && string.IsNullOrEmpty(m2)) - cname = m.Groups[0].Value; - else - cname = String.Concat(m1, m2); - - if (cname.StartsWith("<")) - cname = "Vector." + cname; // literal vector - - type = ctx.ResolveType(cname, inClass.InFile); - if (!type.IsVoid()) resolve = null; - } - else + if (line.Length == 0) return null; + var pos = startPos + m.Index; + var expr = ASComplete.GetExpressionType(sci, pos, false, true); + if (expr.Type is not null || expr.Member is not null) pos = expr.Context.Position; + var ctx = inClass.InFile.Context; + var features = ctx.Features; + var resolve = expr; + if (resolve.Type is not null && !resolve.IsPackage) { - char c = (char)Sci.CharAt(pos); - if (c == '"' || c == '\'') - { - type = ctx.ResolveType("String", inClass.InFile); - } - else if (c == '}') - { - type = ctx.ResolveType(ctx.Features.objectKey, inClass.InFile); - } - else if (c == '>') + if (resolve.Type.Name == "Function") { - type = ctx.ResolveType("XML", inClass.InFile); + var type = ctx.CodeComplete.ToFunctionDeclarationString(expr.Member); + resolve = new ASResult {Type = new ClassModel {Name = type, InFile = FileModel.Ignore}, Context = expr.Context}; } - else if (c == ']') - { - type = ctx.ResolveType(ctx.Features.arrayKey, inClass.InFile); - } - else if (word != null && Char.IsDigit(word[0])) - { - type = ctx.ResolveType(ctx.Features.numberKey, inClass.InFile); - } - else if (word != null && (word == "true" || word == "false")) - { - type = ctx.ResolveType(ctx.Features.booleanKey, inClass.InFile); - } - if (type != null && type.IsVoid()) type = null; - } - if (resolve == null) - { - resolve = new ASResult(); + else if (!string.IsNullOrEmpty(resolve.Path) && Regex.IsMatch(resolve.Path, @"(\.\[.{0,}?\])$", RegexOptions.RightToLeft)) + resolve.Member = null; } - if (resolve.Type == null) + var word = sci.GetWordFromPosition(pos); + if (string.IsNullOrEmpty(word) && resolve.Type is not null) { - resolve.Type = type; + var tokens = Regex.Split(resolve.Context.Value, Regex.Escape(features.dot)); + word = tokens.LastOrDefault(it => it.Length > 0 && !(it.Length >= 2 && it[0] == '#' && it[it.Length - 1] == '~') && char.IsLetter(it[0])); } - return new StatementReturnType(resolve, pos, word); } - private static string ReplaceAllStringContents(string line) - { - string retLine = line; - Regex re1 = new Regex("'(?:[^'\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*'"); - Regex re2 = new Regex("\"(?:[^\"\\\\]|(?:\\\\\\\\)|(?:\\\\\\\\)*\\\\.{1})*\""); - Match m1 = re1.Match(line); - Match m2 = re2.Match(line); - while (m1.Success || m2.Success) - { - Match m = null; - if (m1.Success && m2.Success) m = m1.Index > m2.Index ? m2 : m1; - else if (m1.Success) m = m1; - else m = m2; - string sub = ""; - string val = m.Value; - for (int j = 0; j < val.Length - 2; j++) - sub += "A"; - - line = line.Substring(0, m.Index) + sub + "AA" + line.Substring(m.Index + m.Value.Length); - retLine = retLine.Substring(0, m.Index + 1) + sub + retLine.Substring(m.Index + m.Value.Length - 1); - - m1 = re1.Match(line); - m2 = re2.Match(line); - } - return retLine; - } - - private static string GuessVarName(string name, string type) + protected internal static string GuessVarName(string name, string type) { + if (name == "_") name = null; if (string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(type)) { - Match m = Regex.Match(type, "^([a-z0-9_$]+)", RegexOptions.IgnoreCase); - if (m.Success) - name = m.Groups[1].Value; - else - name = type; + var m = Regex.Match(type, "^([a-z0-9_$]+)", RegexOptions.IgnoreCase); + name = m.Success + ? m.Groups[1].Value + : type; } - if (string.IsNullOrEmpty(name)) - return name; + if (string.IsNullOrEmpty(name)) return name; // if constant then convert to camelCase - if (name.ToUpper() == name) - name = Camelize(name); + if (name.ToUpper() == name) name = Camelize(name); // if getter, then remove 'get' prefix - name = name.TrimStart(new char[] { '_' }); - if (name.Length > 3 && name.StartsWith("get") && (name[3].ToString() == char.ToUpper(name[3]).ToString())) + name = name.TrimStart('_'); + if (name.Length > 3 && name.StartsWithOrdinal("get")) { - name = char.ToLower(name[3]).ToString() + name.Substring(4); + var c = name[3]; + if (!char.IsDigit(c) && c.ToString() == char.ToUpper(c).ToString()) + { + name = char.ToLower(c) + name.Substring(4); + } } - if (name.Length > 1) - name = Char.ToLower(name[0]) + name.Substring(1); - else - name = Char.ToLower(name[0]) + ""; - - if (name == "this" || type == name) + if (name.Length > 1) name = char.ToLower(name[0]) + name.Substring(1); + else name = char.ToLower(name[0]) + ""; + var features = ASContext.Context.Features; + if (name == features.ThisKey || name == features.BaseKey || type == name) { - if (type != null && type.Length > 0) - name = Char.ToLower(type[0]) + type.Substring(1); - else - name = "p_this"; + if (!string.IsNullOrEmpty(type)) + { + // for example: int -> intValue + if (char.IsLower(type[0])) return name + "Value"; + // for example: Number -> number + return char.ToLower(type[0]) + type.Substring(1); + } + if (name == features.BaseKey) return "p_super"; + return "p_this"; } return name; } - private static void GenerateImplementation(ClassModel aType, int position) + static void GenerateImplementation(ClassModel iType, ClassModel inClass, ScintillaControl sci, bool detached) { - List typesUsed = new List(); - - StringBuilder sb = new StringBuilder(TemplateUtils.ReplaceTemplateVariable(TemplateUtils.GetTemplate("ImplementHeader"), "Class", aType.Type)); + var typesUsed = new HashSet(); + var header = TemplateUtils.ReplaceTemplateVariable(TemplateUtils.GetTemplate("ImplementHeader"), "Class", iType.Type); + header = TemplateUtils.ReplaceTemplateVariable(header, "BlankLine", detached ? BlankLine : null); + var sb = new StringBuilder(); + sb.Append(header); sb.Append(NewLine); - bool entry = true; - ASResult result = new ASResult(); - IASContext context = ASContext.Context; - ClassModel cClass = context.CurrentClass; - ContextFeatures features = context.Features; - bool canGenerate = false; - - aType.ResolveExtends(); // resolve inheritance chain - while (!aType.IsVoid() && aType.QualifiedName != "Object") - { - foreach (MemberModel method in aType.Members) - { - if ((method.Flags & (FlagType.Function | FlagType.Getter | FlagType.Setter)) == 0 - || method.Name == aType.Name) + var entry = true; + var result = new ASResult(); + var ctx = ASContext.Context; + var features = ctx.Features; + var codeGenerator = (ASGenerator) ctx.CodeGenerator; + var canGenerate = false; + var isHaxe = IsHaxe; + var flags = FlagType.Function | FlagType.Getter | FlagType.Setter; + if (isHaxe) flags |= FlagType.Variable; + + iType.ResolveExtends(); // expr inheritance chain + while (!iType.IsVoid() && iType.QualifiedName != "Object") + { + foreach (var method in iType.Members) + { + if ((method.Flags & flags) == 0 || method.Name == iType.Name) continue; // check if method exists - ASComplete.FindMember(method.Name, cClass, result, method.Flags, 0); + ASComplete.FindMember(method.Name, inClass, result, method.Flags, 0); if (!result.IsNull()) continue; - string decl = entry ? NewLine : ""; + string template; if ((method.Flags & FlagType.Getter) > 0) - decl = TemplateUtils.ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Getter")); + { + // for example: function get foo():Function/*(v:*):int*/ + if ((method.Flags & FlagType.Function) != 0 && method.Parameters is not null) + method.Type = ctx.CodeComplete.ToFunctionDeclarationString(method); + template = codeGenerator.GetGetterImplementationTemplate(method); + } else if ((method.Flags & FlagType.Setter) > 0) - decl = TemplateUtils.ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Setter")); - else - decl = TemplateUtils.ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Function")); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Member", "_" + method.Name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Void", features.voidKey); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Body", null); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "BlankLine", NewLine); - - if (!entry) { - decl = TemplateUtils.ReplaceTemplateVariable(decl, "EntryPoint", null); + // for example: function get set(v:Function/*(v:*):int*/):void + if (!method.Parameters.IsNullOrEmpty()) + { + var parameter = method.Parameters[0]; + if ((parameter.Flags & FlagType.Function) != 0 && parameter.Parameters is not null) + parameter.Type = ctx.CodeComplete.ToFunctionDeclarationString(parameter); + } + template = ((ASGenerator) ctx.CodeGenerator).ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Setter")); } - - decl += NewLine; - + else if ((method.Flags & FlagType.Function) > 0) + { + // for example: function get set(v:Function/*(v:*):int*/):void + if (method.Parameters is not null) + { + foreach (var parameter in method.Parameters) + { + if ((parameter.Flags & FlagType.Function) != 0 && parameter.Parameters is not null) + parameter.Type = ctx.CodeComplete.ToFunctionDeclarationString(parameter); + } + } + template = ((ASGenerator) ctx.CodeGenerator).ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Function")); + } + else template = NewLine + ((ASGenerator) ctx.CodeGenerator).ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Variable")); + + template = TemplateUtils.ReplaceTemplateVariable(template, "Member", "_" + method.Name); + template = TemplateUtils.ReplaceTemplateVariable(template, "Void", features.voidKey); + template = TemplateUtils.ReplaceTemplateVariable(template, "Body", codeGenerator.GetFunctionBody(method, inClass)); + template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); + if (!entry) template = TemplateUtils.ReplaceTemplateVariable(template, "EntryPoint", null); + template += NewLine; entry = false; - - sb.Append(decl); + sb.Append(template); canGenerate = true; - - addTypeOnce(typesUsed, getQualifiedType(method.Type, aType)); - - if (method.Parameters != null && method.Parameters.Count > 0) - foreach (MemberModel param in method.Parameters) - addTypeOnce(typesUsed, getQualifiedType(param.Type, aType)); + if (method.Type != features.voidKey) typesUsed.Add(method.Type); + if (!method.Parameters.IsNullOrEmpty()) + foreach (var param in method.Parameters) + typesUsed.Add(param.Type); } + + if (ctx.Settings.GenerateImports) typesUsed = (HashSet) GetQualifiedTypes(typesUsed, iType.InFile); // interface inheritance - aType = aType.Extends; + iType = iType.Extends; } - if (!canGenerate) - return; - - ScintillaNet.ScintillaControl Sci = ASContext.CurSciControl; - Sci.BeginUndoAction(); + if (!canGenerate) return; + sci.BeginUndoAction(); try { - position = Sci.CurrentPos; - if (ASContext.Context.Settings.GenerateImports && typesUsed.Count > 0) + var position = sci.CurrentPos; + if (ctx.Settings.GenerateImports && typesUsed.Count > 0) { - int offset = AddImportsByName(typesUsed, Sci.LineFromPosition(position)); - position += offset; - Sci.SetSel(position, position); + position += AddImportsByName(typesUsed, sci.LineFromPosition(position)); + sci.SetSel(position, position); } - InsertCode(position, sb.ToString()); + InsertCode(position, sb.ToString(), sci); } - finally { Sci.EndUndoAction(); } + finally { sci.EndUndoAction(); } } - private static void addTypeOnce(List typesUsed, string qualifiedName) + protected virtual string GetGetterImplementationTemplate(MemberModel method) => ToDeclarationWithModifiersString(method, TemplateUtils.GetTemplate("Getter")); + + static void AddTypeOnce(ICollection typesUsed, string qualifiedName) { if (!typesUsed.Contains(qualifiedName)) typesUsed.Add(qualifiedName); } - private static string getQualifiedType(string type, ClassModel aType) + protected static IEnumerable GetQualifiedTypes(IEnumerable types, FileModel inFile) { - if (type == null || type == "") return "*"; - if (type.IndexOf('<') > 0) // Vector. + var result = new HashSet(); + types = ASContext.Context.DecomposeTypes(types); + foreach (var type in types) { - Match mGeneric = Regex.Match(type, "<([^>]+)>"); - if (mGeneric.Success) + if (type == "*" || type.Contains(".")) result.Add(type); + else { - return getQualifiedType(mGeneric.Groups[1].Value, aType); + var model = ASContext.Context.ResolveType(type, inFile); + if (!model.IsVoid() && model.InFile.Package.Length > 0) result.Add(model.QualifiedName); } } + return result; + } - if (type.IndexOf('.') > 0) return type; - - ClassModel aClass = ASContext.Context.ResolveType(type, aType.InFile); - if (!aClass.IsVoid()) + static string GetQualifiedType(string type, MemberModel aType) + { + var dynamicKey = ASContext.Context.Features.dynamicKey ?? "*"; + if (string.IsNullOrEmpty(type)) return dynamicKey; + if (ASContext.Context.DecomposeTypes(new [] {type}).Count() > 1) return type; + if (type.IndexOf('<') > 0) // Vector. { - if (aClass.InFile.Package.Length != 0) - return aClass.QualifiedName; + var mGeneric = Regex.Match(type, "<([^>]+)>"); + if (mGeneric.Success) return GetQualifiedType(mGeneric.Groups[1].Value, aType); } - return "*"; + if (type.IndexOf('.') > 0) return type; + var aClass = ASContext.Context.ResolveType(type, aType.InFile); + return !aClass.IsVoid() + ? aClass.QualifiedName + : dynamicKey; } - private static MemberModel NewMember(string contextToken, MemberModel calledFrom, FlagType kind, Visibility visi) + static MemberModel NewMember(string name, MemberModel calledFrom, FlagType kind, Visibility access) { - string type = (kind == FlagType.Function && !ASContext.Context.Features.hasInference) - ? ASContext.Context.Features.voidKey : null; - if (calledFrom != null && (calledFrom.Flags & FlagType.Static) > 0) + var type = kind == FlagType.Function && !ASContext.Context.Features.hasInference + ? ASContext.Context.Features.voidKey + : null; + if (calledFrom is not null && (calledFrom.Flags & FlagType.Static) > 0) kind |= FlagType.Static; - return new MemberModel(contextToken, type, kind, visi); - } - - private static MemberModel NewMember(string contextToken, MemberModel calledFrom, FlagType kind) - { - return NewMember(contextToken, calledFrom, kind, GetDefaultVisibility()); + return new MemberModel(name, type, kind, access); } /// - /// Get Visibility.Private or Visibility.Protected, depending on user setting forcing the use of protected. - /// - public static Visibility GetDefaultVisibility() - { - if (ASContext.Context.Features.protectedKey != null && ASContext.CommonSettings.GenerateProtectedDeclarations) - return Visibility.Protected; - else return Visibility.Private; - } - - private static void GenerateFunction(MemberModel member, int position, bool detach, ClassModel inClass) - { - bool isInterface = ClassIsInterface(inClass); - bool isConstructor = (member.Flags & FlagType.Constructor) > 0; - string template = ""; - string result = ""; - if (isInterface) - { - template = TemplateUtils.GetTemplate("IFunction"); - result = TemplateUtils.ToDeclarationString(member, template); - } - else if (isConstructor) - { - template = TemplateUtils.GetTemplate("Constructor"); - result = TemplateUtils.ToDeclarationWithModifiersString(member, template); - } - else - { - template = TemplateUtils.GetTemplate("Function"); - result = TemplateUtils.ToDeclarationWithModifiersString(member, template); - result = TemplateUtils.ReplaceTemplateVariable(result, "Body", null); - } - - if (detach) - { - result = NewLine + TemplateUtils.ReplaceTemplateVariable(result, "BlankLine", NewLine); - } - else - { - result = TemplateUtils.ReplaceTemplateVariable(result, "BlankLine", null); - } - InsertCode(position, result); - } - - private static bool ClassIsInterface(ClassModel cm) + /// Get Visibility.Private or Visibility.Protected, depending on user setting forcing the use of protected. + /// + static Visibility GetDefaultVisibility(MemberModel model) { - return (cm.Flags & FlagType.Interface) > 0; + if (ASContext.Context.Features.protectedKey is not null + && ASContext.CommonSettings.GenerateProtectedDeclarations + && (model.Flags & FlagType.Final) == 0) + return Visibility.Protected; + return Visibility.Private; } - private static void GenerateVariable(MemberModel member, int position, bool detach) + static void GenerateVariable(MemberModel member, int position, bool detach) { - string result = ""; + string result; if ((member.Flags & FlagType.Constant) > 0) { - string template = TemplateUtils.GetTemplate("Constant"); - result = TemplateUtils.ToDeclarationWithModifiersString(member, template); - if (member.Value == null) - result = TemplateUtils.ReplaceTemplateVariable(result, "Value", null); - else - result = TemplateUtils.ReplaceTemplateVariable(result, "Value", member.Value); + var template = TemplateUtils.GetTemplate("Constant"); + result = ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(member, template); + result = TemplateUtils.ReplaceTemplateVariable(result, "Value", member.Value); } else { - string template = TemplateUtils.GetTemplate("Variable"); - result = TemplateUtils.ToDeclarationWithModifiersString(member, template); + var template = TemplateUtils.GetTemplate("Variable"); + result = ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(member, template); } if (firstVar) @@ -3304,110 +3388,49 @@ private static void GenerateVariable(MemberModel member, int position, bool deta InsertCode(position, result); } - private static string ReplaceAll(string template, string oldValue, string newValue) - { - if (template == null) - return null; - - string result = ""; - string[] a = template.Split(new string[] { oldValue }, StringSplitOptions.None); - for (int i = 0; i < a.Length; i++) - { - if (i > 0) - result += newValue; - result += a[i]; - } - return result; - } - - public static bool MakePrivate(ScintillaNet.ScintillaControl Sci, MemberModel member) + public static bool MakePrivate(ScintillaControl sci, MemberModel member, ClassModel inClass) { - ContextFeatures features = ASContext.Context.Features; - string visibility = GetPrivateKeyword(); - if (features.publicKey == null || visibility == null) return false; - Regex rePublic = new Regex(String.Format(@"\s*({0})\s+", features.publicKey)); - - string line; - Match m; - int index, position; - for (int i = member.LineFrom; i <= member.LineTo; i++) - { - line = Sci.GetLine(i); - m = rePublic.Match(line); + var features = ASContext.Context.Features; + var visibility = GetPrivateKeyword(inClass); + if (features.publicKey is null || visibility is null) return false; + var rePublic = new Regex($@"\s*({features.publicKey})\s+"); + for (var i = member.LineFrom; i <= member.LineTo; i++) + { + var line = sci.GetLine(i); + var m = rePublic.Match(line); if (m.Success) { - index = Sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index)); - position = Sci.PositionFromLine(i) + index; - Sci.SetSel(position, position + features.publicKey.Length); - Sci.ReplaceSel(visibility); + var index = sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index)); + var position = sci.PositionFromLine(i) + index; + sci.SetSel(position, position + features.publicKey.Length); + sci.ReplaceSel(visibility); UpdateLookupPosition(position, features.publicKey.Length - visibility.Length); return true; } } return false; - } - - public static bool MakeHaxeProperty(ScintillaNet.ScintillaControl Sci, MemberModel member, string args) - { - ContextFeatures features = ASContext.Context.Features; - string kind = features.varKey; - - if ((member.Flags & FlagType.Getter) > 0) - kind = features.getKey; - else if ((member.Flags & FlagType.Setter) > 0) - kind = features.setKey; - else if (member.Flags == FlagType.Function) - kind = features.functionKey; - - Regex reMember = new Regex(String.Format(@"{0}\s+({1})[\s:]", kind, member.Name)); - - string line; - Match m; - int index, position; - for (int i = member.LineFrom; i <= member.LineTo; i++) - { - line = Sci.GetLine(i); - m = reMember.Match(line); - if (m.Success) - { - index = Sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index)); - position = Sci.PositionFromLine(i) + index; - Sci.SetSel(position, position + member.Name.Length); - Sci.ReplaceSel(member.Name + args); - UpdateLookupPosition(position, 1); - return true; - } - } - return false; - } - - public static bool RenameMember(ScintillaNet.ScintillaControl Sci, MemberModel member, string newName) - { - ContextFeatures features = ASContext.Context.Features; - string kind = features.varKey; - - if ((member.Flags & FlagType.Getter) > 0) - kind = features.getKey; - else if ((member.Flags & FlagType.Setter) > 0) - kind = features.setKey; - else if (member.Flags == FlagType.Function) - kind = features.functionKey; - - Regex reMember = new Regex(String.Format(@"{0}\s+({1})[\s:]", kind, member.Name)); - - string line; - Match m; - int index, position; - for (int i = member.LineFrom; i <= member.LineTo; i++) - { - line = Sci.GetLine(i); - m = reMember.Match(line); + } + + public static bool RenameMember(ScintillaControl sci, MemberModel member, string newName) + { + var features = ASContext.Context.Features; + var kind = features.varKey; + + if ((member.Flags & FlagType.Getter) > 0) kind = features.getKey; + else if ((member.Flags & FlagType.Setter) > 0) kind = features.setKey; + else if (member.Flags == FlagType.Function) kind = features.functionKey; + + var reMember = new Regex($@"{kind}\s+({member.Name})[\s:]"); + for (var i = member.LineFrom; i <= member.LineTo; i++) + { + var line = sci.GetLine(i); + var m = reMember.Match(line); if (m.Success) { - index = Sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index)); - position = Sci.PositionFromLine(i) + index; - Sci.SetSel(position, position + member.Name.Length); - Sci.ReplaceSel(newName); + var index = sci.MBSafeTextLength(line.Substring(0, m.Groups[1].Index)); + var position = sci.PositionFromLine(i) + index; + sci.SetSel(position, position + member.Name.Length); + sci.ReplaceSel(newName); UpdateLookupPosition(position, 1); return true; } @@ -3418,827 +3441,636 @@ public static bool RenameMember(ScintillaNet.ScintillaControl Sci, MemberModel m /// /// Return an obvious property name matching a private var, or null /// - private static string GetPropertyNameFor(MemberModel member) + static string GetPropertyNameFor(MemberModel member) { - string name = member.Name; - if (name.Length < 1) - return null; - Match parts = Regex.Match(name, "([^_$]*)[_$]+(.*)"); - if (parts.Success) - { - string pre = parts.Groups[1].Value; - string post = parts.Groups[2].Value; - return (pre.Length > post.Length) ? pre : post; - } - return null; + if (IsHaxe) return null; + var name = member.Name; + if (name.Length == 0 || (member.Access & Visibility.Public) != 0) return null; + var parts = Regex.Match(name, "([^_$]*)[_$]+(.*)"); + if (!parts.Success) return null; + var pre = parts.Groups[1].Value; + var post = parts.Groups[2].Value; + return pre.Length > post.Length ? pre : post; } /// /// Return a smart new property name /// - private static string GetNewPropertyNameFor(MemberModel member) + static string GetNewPropertyNameFor(MemberModel member) { - if (member.Name.Length < 1) - return "prop"; + if (member.Name.Length == 0) return "prop"; if (Regex.IsMatch(member.Name, "^[A-Z].*[a-z]")) - return Char.ToLower(member.Name[0]) + member.Name.Substring(1); - else - return "_" + member.Name; + return char.ToLower(member.Name[0]) + member.Name.Substring(1); + return "_" + member.Name; } - private static void GenerateDelegateMethod(string name, MemberModel afterMethod, int position) + static void GenerateDelegateMethod(string name, MemberModel afterMethod, int position, ClassModel inClass) { - ContextFeatures features = ASContext.Context.Features; - - string acc = GetPrivateAccessor(afterMethod); - string template = TemplateUtils.GetTemplate("Delegate"); + var features = ASContext.Context.Features; string args = null; - string type = features.voidKey; - - if (features.hasDelegates && contextMember != null) // delegate functions types + var type = features.voidKey; + if (features.hasDelegates && contextMember is not null) // delegate functions types { args = contextMember.ParametersString(); type = contextMember.Type; } - string decl = BlankLine + TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", acc); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Name", name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Arguments", args); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Type", type); - InsertCode(position, decl); + var template = TemplateUtils.GetTemplate("Delegate"); + template = BlankLine + TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", GetPrivateAccessor(afterMethod, inClass)); + template = TemplateUtils.ReplaceTemplateVariable(template, "Name", name); + template = TemplateUtils.ReplaceTemplateVariable(template, "Arguments", args); + template = TemplateUtils.ReplaceTemplateVariable(template, "Type", type); + InsertCode(position, template); } - private static void GenerateEventHandler(string name, string type, MemberModel afterMethod, int position) + static void GenerateEventHandler(string name, string type, MemberModel afterMethod, int position, ClassModel inClass) { - ScintillaNet.ScintillaControl Sci = ASContext.CurSciControl; - Sci.BeginUndoAction(); + var ctx = ASContext.Context; + var sci = PluginBase.MainForm.CurrentDocument.SciControl; + sci.BeginUndoAction(); try { - int delta = 0; - ClassModel eventClass = ASContext.Context.ResolveType(type, ASContext.Context.CurrentModel); + var delta = 0; + var eventClass = ctx.ResolveType(type, ctx.CurrentModel); if (eventClass.IsVoid()) - if (type == "Event") - { - List typesUsed = new List(); - typesUsed.Add("flash.events.Event"); - delta = AddImportsByName(typesUsed, Sci.LineFromPosition(position)); - position += delta; - Sci.SetSel(position, position); - } - else if (type == "DataEvent") + { + if (TryImportType("flash.events." + type, ref delta, sci.LineFromPosition(position))) { - List typesUsed = new List(); - typesUsed.Add("flash.events.DataEvent"); - delta = AddImportsByName(typesUsed, Sci.LineFromPosition(position)); position += delta; - Sci.SetSel(position, position); + sci.SetSel(position, position); } - lookupPosition += delta; - string acc = GetPrivateAccessor(afterMethod); - string template = TemplateUtils.GetTemplate("EventHandler"); - string decl = NewLine + TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", acc); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Name", name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Type", type); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Void", ASContext.Context.Features.voidKey); - - string eventName = contextMatch.Groups["event"].Value; - string autoRemove = AddRemoveEvent(eventName); - if (autoRemove != null) - { - if (autoRemove.Length > 0) autoRemove += "."; - string remove = String.Format("{0}removeEventListener({1}, {2});\n\t$(EntryPoint)", autoRemove, eventName, name); - decl = decl.Replace("$(EntryPoint)", remove); + else type = null; } - InsertCode(position, decl); + lookupPosition += delta; + var newMember = new MemberModel + { + Name = name, + Type = type, + Access = GetDefaultVisibility(inClass) + }; + if ((afterMethod.Flags & FlagType.Static) > 0) newMember.Flags = FlagType.Static; + var template = TemplateUtils.GetTemplate("EventHandler"); + var declaration = NewLine + ((ASGenerator) ctx.CodeGenerator).ToDeclarationWithModifiersString(newMember, template); + declaration = TemplateUtils.ReplaceTemplateVariable(declaration, "Void", ctx.Features.voidKey); + var eventName = contextMatch.Groups["event"].Value; + var autoRemove = AddRemoveEvent(eventName); + ((ASGenerator) ctx.CodeGenerator).GenerateEventHandler(sci, position, declaration, autoRemove, eventName, name); } finally { - Sci.EndUndoAction(); + sci.EndUndoAction(); } } - static private string AddRemoveEvent(string eventName) + protected virtual void GenerateEventHandler(ScintillaControl sci, int position, string template, string currentTarget, string eventName, string handlerName) { - foreach (string autoRemove in ASContext.CommonSettings.EventListenersAutoRemove) + var ctx = ASContext.Context; + if (currentTarget is not null) { - string test = autoRemove.Trim(); - if (test.Length == 0 || test.StartsWith("//")) continue; - int colonPos = test.IndexOf(':'); - if (colonPos >= 0) test = test.Substring(colonPos + 1); - if (test == eventName) + var delta = 0; + if (TryImportType("flash.events.IEventDispatcher", ref delta, sci.LineFromPosition(position))) { - if (colonPos < 0) return ""; - else return autoRemove.Trim().Substring(0, colonPos); + position += delta; + sci.SetSel(position, position); + lookupPosition += delta; + currentTarget = "IEventDispatcher(e.currentTarget)"; } + if (currentTarget.Length == 0 && ASContext.CommonSettings.GenerateScope && ctx.Features.ThisKey is not null) + currentTarget = ctx.Features.ThisKey; + if (currentTarget.Length > 0) currentTarget += "."; + var remove = $"{currentTarget}removeEventListener({eventName}, {handlerName});\n\t$(EntryPoint)"; + template = template.Replace("$(EntryPoint)", remove); + } + InsertCode(position, template, sci); + } + + protected static bool TryImportType(string type, ref int delta, int atLine) + { + var @class = ASContext.Context.ResolveType(type, ASContext.Context.CurrentModel); + if (@class.IsVoid()) return false; + delta += AddImportsByName(new List {type}, atLine); + return true; + } + + static string AddRemoveEvent(string eventName) + { + foreach (var autoRemove in ASContext.CommonSettings.EventListenersAutoRemove) + { + var test = autoRemove.Trim(); + if (test.Length == 0 || test.StartsWithOrdinal("//")) continue; + var colonPos = test.IndexOf(':'); + if (colonPos >= 0) test = test.Substring(colonPos + 1); + if (test != eventName) continue; + return colonPos < 0 ? "" : autoRemove.Trim().Substring(0, colonPos); } return null; } - static private void GenerateGetter(string name, MemberModel member, int position) + static void GenerateGetter(string name, MemberModel member, int position) => GenerateGetter(name, member, position, true, false); + + protected static void GenerateGetter(string name, MemberModel member, int position, bool startsWithNewLine, bool endsWithNewLine) { - string acc = GetPublicAccessor(member); - string template = TemplateUtils.GetTemplate("Getter"); - string decl = NewLine + TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", acc); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Name", name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Type", FormatType(member.Type)); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Member", member.Name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "BlankLine", NewLine); - InsertCode(position, decl); + var newMember = new MemberModel + { + Name = name, + Type = MemberModel.FormatType(GetShortType(member.Type)), + Access = IsHaxe ? Visibility.Private : Visibility.Public + }; + if ((member.Flags & FlagType.Static) > 0) newMember.Flags = FlagType.Static; + var template = TemplateUtils.GetTemplate("Getter"); + template = startsWithNewLine + ? NewLine + ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(newMember, template) + : ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(newMember, template); + template = TemplateUtils.ReplaceTemplateVariable(template, "Member", member.Name); + template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); + if (endsWithNewLine) template += NewLine + NewLine; + InsertCode(position, template); } - static private void GenerateSetter(string name, MemberModel member, int position) + protected static void GenerateSetter(string name, MemberModel member, int position) { - string acc = GetPublicAccessor(member); - string template = TemplateUtils.GetTemplate("Setter"); - string decl = NewLine + TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", acc); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Name", name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Type", FormatType(member.Type)); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Member", member.Name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Void", ASContext.Context.Features.voidKey ?? "void"); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "BlankLine", NewLine); - InsertCode(position, decl); + var newMember = new MemberModel + { + Name = name, + Type = MemberModel.FormatType(GetShortType(member.Type)), + Access = IsHaxe ? Visibility.Private : Visibility.Public + }; + if ((member.Flags & FlagType.Static) > 0) newMember.Flags = FlagType.Static; + var template = TemplateUtils.GetTemplate("Setter"); + template = NewLine + ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(newMember, template); + template = TemplateUtils.ReplaceTemplateVariable(template, "Member", member.Name); + template = TemplateUtils.ReplaceTemplateVariable(template, "Void", ASContext.Context.Features.voidKey ?? "void"); + template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); + InsertCode(position, template); } - static private void GenerateGetterSetter(string name, MemberModel member, int position) + protected static void GenerateGetterSetter(string name, MemberModel member, int position) { - string template = TemplateUtils.GetTemplate("GetterSetter"); - if (template == "") + var template = TemplateUtils.GetTemplate("GetterSetter"); + if (template.Length == 0) { GenerateSetter(name, member, position); - ASContext.CurSciControl.SetSel(position, position); + PluginBase.MainForm.CurrentDocument?.SciControl.SetSel(position, position); GenerateGetter(name, member, position); return; } - string acc = GetPublicAccessor(member); - string decl = NewLine + TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", acc); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Name", name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Type", FormatType(member.Type)); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Member", member.Name); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "Void", ASContext.Context.Features.voidKey ?? "void"); - decl = TemplateUtils.ReplaceTemplateVariable(decl, "BlankLine", NewLine); - InsertCode(position, decl); + var newMember = new MemberModel + { + Name = name, + Type = MemberModel.FormatType(GetShortType(member.Type)), + Access = IsHaxe ? Visibility.Private : Visibility.Public + }; + if ((member.Flags & FlagType.Static) > 0) newMember.Flags = FlagType.Static; + template = NewLine + ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(newMember, template); + template = TemplateUtils.ReplaceTemplateVariable(template, "Member", member.Name); + template = TemplateUtils.ReplaceTemplateVariable(template, "Void", ASContext.Context.Features.voidKey ?? "void"); + template = TemplateUtils.ReplaceTemplateVariable(template, "BlankLine", NewLine); + InsertCode(position, template); } - static private string GetPrivateAccessor(MemberModel member) + static string GetStaticKeyword(MemberModel member) { - string acc = GetPrivateKeyword(); - if ((member.Flags & FlagType.Static) > 0) acc = (ASContext.Context.Features.staticKey ?? "static") + " " + acc; - return acc; + if ((member.Flags & FlagType.Static) > 0) return ASContext.Context.Features.staticKey ?? "static"; + return null; } - static public string GetPrivateKeyword() + static string GetPrivateAccessor(MemberModel member, MemberModel inClass) { - string acc; - if (GetDefaultVisibility() == Visibility.Protected) - acc = ASContext.Context.Features.protectedKey ?? "protected"; - else acc = ASContext.Context.Features.privateKey ?? "private"; - return acc; + var result = GetStaticKeyword(member); + if (!string.IsNullOrEmpty(result)) result += " "; + return result + GetPrivateKeyword(inClass); } - static private string GetPublicAccessor(MemberModel member) + static string GetPrivateKeyword(MemberModel inClass) { - string acc = ASContext.Context.Features.publicKey ?? "public"; - if ((member.Flags & FlagType.Static) > 0) acc = (ASContext.Context.Features.staticKey ?? "static") + " " + acc; - return acc; + if (GetDefaultVisibility(inClass) == Visibility.Protected) return ASContext.Context.Features.protectedKey ?? "protected"; + return ASContext.Context.Features.privateKey ?? "private"; } - private static MemberModel GetLatestMemberForFunction(ClassModel inClass, Visibility funcVisi, MemberModel isStatic) + static MemberModel GetLatestMemberForFunction(ClassModel inClass, Visibility access, MemberModel isStatic) { - MemberModel latest = null; - if (isStatic != null && (isStatic.Flags & FlagType.Static) > 0) - { - latest = FindLatest(FlagType.Function | FlagType.Static, funcVisi, inClass); - if (latest == null) - { - latest = FindLatest(FlagType.Function | FlagType.Static, 0, inClass, true, false); - } - } - else - { - latest = FindLatest(FlagType.Function, funcVisi, inClass); - } - if (latest == null) - { - latest = FindLatest(FlagType.Function, 0, inClass, true, false); - } - if (latest == null) + MemberModel latest; + if (isStatic is not null && (isStatic.Flags & FlagType.Static) > 0) { - latest = FindLatest(FlagType.Function, 0, inClass, false, false); + latest = FindLatest(FlagType.Function | FlagType.Static, access, inClass) + ?? FindLatest(FlagType.Function | FlagType.Static, 0, inClass, true, false); } - return latest; + else latest = FindLatest(FlagType.Function, access, inClass); + return latest + ?? FindLatest(FlagType.Function, 0, inClass, true, false) + ?? FindLatest(FlagType.Function, 0, inClass, false, false); } - private static MemberModel GetLatestMemberForVariable(GeneratorJobType job, ClassModel inClass, Visibility varVisi, MemberModel isStatic) + static MemberModel GetLatestMemberForVariable(GeneratorJobType job, ClassModel inClass, Visibility access, MemberModel isStatic) { - MemberModel latest = null; + MemberModel latest; if (job.Equals(GeneratorJobType.Constant)) { - if ((isStatic.Flags & FlagType.Static) > 0) - { - latest = FindLatest(FlagType.Constant | FlagType.Static, varVisi, inClass); - } - else - { - latest = FindLatest(FlagType.Constant, varVisi, inClass); - } - if (latest == null) - { - latest = FindLatest(FlagType.Constant, 0, inClass, true, false); - } + latest = ((isStatic.Flags & FlagType.Static) > 0 + ? FindLatest(FlagType.Constant | FlagType.Static, access, inClass) + : FindLatest(FlagType.Constant, access, inClass)) + ?? FindLatest(FlagType.Constant, 0, inClass, true, false); } else { - if ((isStatic.Flags & FlagType.Static) > 0) - { - latest = FindLatest(FlagType.Variable | FlagType.Static, varVisi, inClass); - if (latest == null) - { - latest = FindLatest(FlagType.Variable | FlagType.Static, 0, inClass, true, false); - } - } - else - { - latest = FindLatest(FlagType.Variable, varVisi, inClass); - } - } - if (latest == null) - { - latest = FindLatest(FlagType.Variable, varVisi, inClass, false, false); - } - return latest; - } - - static private MemberModel FindMember(string name, ClassModel inClass) - { - MemberList list; - if (inClass == ClassModel.VoidClass) - list = ASContext.Context.CurrentModel.Members; - else list = inClass.Members; - - MemberModel found = null; - foreach (MemberModel member in list) - { - if (member.Name == name) - { - found = member; - break; - } + latest = (isStatic.Flags & FlagType.Static) > 0 + ? FindLatest(FlagType.Variable | FlagType.Static, access, inClass) ?? FindLatest(FlagType.Variable | FlagType.Static, 0, inClass, true, false) + : FindLatest(FlagType.Variable, access, inClass); } - return found; + return latest ?? FindLatest(FlagType.Variable, access, inClass, false, false); } - static private MemberModel FindLatest(FlagType match, ClassModel inClass) - { - return FindLatest(match, 0, inClass); - } + static MemberModel FindLatest(FlagType match, ClassModel inClass) => FindLatest(match, 0, inClass); - static private MemberModel FindLatest(FlagType match, Visibility visi, ClassModel inClass) - { - return FindLatest(match, visi, inClass, true, true); - } + static MemberModel FindLatest(FlagType match, Visibility access, ClassModel inClass) => FindLatest(match, access, inClass, true, true); - static private MemberModel FindLatest(FlagType match, Visibility visi, ClassModel inClass, - bool isFlagMatchStrict, bool isVisibilityMatchStrict) + protected static MemberModel FindLatest(FlagType match, Visibility access, ClassModel inClass, bool isFlagMatchStrict, bool isVisibilityMatchStrict) { - MemberList list; - if (inClass == ClassModel.VoidClass) - list = ASContext.Context.CurrentModel.Members; - else - list = inClass.Members; + var list = inClass == ClassModel.VoidClass + ? ASContext.Context.CurrentModel.Members + : inClass.Members; MemberModel latest = null; MemberModel fallback = null; - foreach (MemberModel member in list) + foreach (var member in list) { fallback = member; if (isFlagMatchStrict && isVisibilityMatchStrict) { - if ((member.Flags & match) == match && (visi == 0 || (member.Access & visi) == visi)) + if ((member.Flags & match) == match && (access == 0 || (member.Access & access) == access)) { latest = member; } } - else if (isFlagMatchStrict && !isVisibilityMatchStrict) + else if (isFlagMatchStrict) { - if ((member.Flags & match) == match && (visi == 0 || (member.Access & visi) > 0)) + if ((member.Flags & match) == match && (access == 0 || (member.Access & access) > 0)) { latest = member; } } - else if (!isFlagMatchStrict && isVisibilityMatchStrict) + else if (isVisibilityMatchStrict) { - if ((member.Flags & match) > 0 && (visi == 0 || (member.Access & visi) == visi)) + if ((member.Flags & match) > 0 && (access == 0 || (member.Access & access) == access)) { latest = member; } } else { - if ((member.Flags & match) > 0 && (visi == 0 || (member.Access & visi) > 0)) + if ((member.Flags & match) > 0 && (access == 0 || (member.Access & access) > 0)) { latest = member; } } } - if (isFlagMatchStrict || isVisibilityMatchStrict) - fallback = null; + if (isFlagMatchStrict || isVisibilityMatchStrict) fallback = null; return latest ?? fallback; } - - static private string GetDeclaration(MemberModel member) + + static void AddExplicitScopeReference(ScintillaControl sci, ClassModel inClass, MemberModel inMember) { - return GetDeclaration(member, true); + var position = sci.CurrentPos; + var start = sci.WordStartPosition(position, true); + var length = sci.MBSafeTextLength(contextToken); + sci.SetSel(start, start + length); + var scope = (inMember.Flags & FlagType.Static) != 0 ? inClass.QualifiedName : "this"; + var text = $"{scope}{ASContext.Context.Features.dot}{contextToken}"; + sci.ReplaceSel(text); + UpdateLookupPosition(position, text.Length - length); } - static private string GetDeclaration(MemberModel member, bool addModifiers) + protected virtual MemberModel ToParameterVar(FunctionParameter member) { - // modifiers - FlagType ft = member.Flags; - string modifiers = ""; + var type = member.paramType.Length > member.paramQualType.Length ? member.paramType : member.paramQualType; + return new MemberModel(AvoidKeyword(member.paramName), GetShortType(type), FlagType.ParameterVar, 0); + } - modifiers += TemplateUtils.GetStaticExternOverride(member); + protected virtual string ToDeclarationWithModifiersString(MemberModel member, string template) => TemplateUtils.ToDeclarationWithModifiersString(member, template); - if (addModifiers) - modifiers += TemplateUtils.GetModifiers(member); - - // signature - if ((ft & FlagType.Getter) > 0) - return String.Format("{0}function get {1}", modifiers, member.ToDeclarationString()); - else if ((ft & FlagType.Setter) > 0) - return String.Format("{0}function set {1}", modifiers, member.ToDeclarationString()); - else if (ft == FlagType.Function) - return String.Format("{0}function {1}", modifiers, member.ToDeclarationString()); - else if (((ft & FlagType.Constant) > 0) && ASContext.Context.Settings.LanguageId != "AS2") - return String.Format("{0}const {1}", modifiers, member.ToDeclarationString()); - else - return String.Format("{0}var {1}", modifiers, member.ToDeclarationString()); - } #endregion #region override generator + /// /// List methods to override /// - /// Scintilla control /// Don't keep the list open if the word does not match /// Completion was handled - static private bool HandleOverrideCompletion(ScintillaNet.ScintillaControl Sci, bool autoHide) - { - //int line = Sci.LineFromPosition(Sci.CurrentPos); - - // explore members - IASContext ctx = ASContext.Context; - ClassModel curClass = ctx.CurrentClass; - if (curClass.IsVoid()) - return false; - ContextFeatures features = ASContext.Context.Features; - - List members = new List(); - curClass.ResolveExtends(); // Resolve inheritance chain - - // explore function or getters or setters - FlagType mask = FlagType.Function | FlagType.Getter | FlagType.Setter; - ClassModel tmpClass = curClass.Extends; - Visibility acc = ctx.TypesAffinity(curClass, tmpClass); - while (tmpClass != null && !tmpClass.IsVoid()) - { - if (tmpClass.QualifiedName.StartsWith("flash.utils.Proxy")) - { - foreach (MemberModel member in tmpClass.Members) - { - member.Namespace = "flash_proxy"; - members.Add(member); - } - break; - } - else - { - foreach (MemberModel member in tmpClass.Members) - if ((member.Flags & FlagType.Dynamic) > 0 - && (member.Flags & mask) > 0 - && (member.Access & acc) > 0) members.Add(member); - - tmpClass = tmpClass.Extends; - // members visibility - acc = ctx.TypesAffinity(curClass, tmpClass); - } - } - members.Sort(); - - // build list - List known = new List(); - - MemberModel last = null; - foreach (MemberModel member in members) - { - if (last == null || last.Name != member.Name) - known.Add(new MemberItem(member)); - last = member; - } - if (known.Count > 0) CompletionList.Show(known, autoHide); - return true; - } + protected virtual bool HandleOverrideCompletion(bool autoHide) => ASContext.Context.CodeComplete.HandleOverrideCompletion(string.Empty, autoHide); - static public void GenerateOverride(ScintillaNet.ScintillaControl Sci, ClassModel ofClass, MemberModel member, int position) + public static void GenerateOverride(ScintillaControl sci, ClassModel ofClass, MemberModel member, int position) { - ContextFeatures features = ASContext.Context.Features; - List typesUsed = new List(); - bool isProxy = (member.Namespace == "flash_proxy"); + var ctx = ASContext.Context; + var features = ctx.Features; + var typesUsed = new List(); + var isProxy = member.Namespace == "flash_proxy"; if (isProxy) typesUsed.Add("flash.utils.flash_proxy"); - bool isAS2Event = ASContext.Context.Settings.LanguageId == "AS2" && member.Name.StartsWith("on"); - bool isObjectMethod = ofClass.QualifiedName == "Object"; - - int line = Sci.LineFromPosition(position); - string currentText = Sci.GetLine(line); - int startPos = currentText.Length; + + var line = sci.LineFromPosition(position); + var currentText = sci.GetLine(line); + var startPos = currentText.Length; GetStartPos(currentText, ref startPos, features.privateKey); GetStartPos(currentText, ref startPos, features.protectedKey); GetStartPos(currentText, ref startPos, features.internalKey); GetStartPos(currentText, ref startPos, features.publicKey); GetStartPos(currentText, ref startPos, features.staticKey); GetStartPos(currentText, ref startPos, features.overrideKey); - startPos += Sci.PositionFromLine(line); - - FlagType flags = member.Flags; - string acc = ""; - string decl = ""; - if (features.hasNamespaces && member.Namespace != null - && member.Namespace.Length > 0 && member.Namespace != "internal") - acc = member.Namespace; - else if ((member.Access & Visibility.Public) > 0) acc = features.publicKey; - else if ((member.Access & Visibility.Internal) > 0) acc = features.internalKey; - else if ((member.Access & Visibility.Protected) > 0) acc = features.protectedKey; - else if ((member.Access & Visibility.Private) > 0 && features.methodModifierDefault != Visibility.Private) - acc = features.privateKey; - - bool isStatic = (flags & FlagType.Static) > 0; - if (isStatic) acc = features.staticKey + " " + acc; - - if (!isAS2Event && !isObjectMethod) - acc = features.overrideKey + " " + acc; - - acc = Regex.Replace(acc, "[ ]+", " ").Trim(); - + startPos += sci.PositionFromLine(line); + + var newMember = new MemberModel + { + Name = member.Name, + Type = member.Type + }; + if (features.hasNamespaces && !string.IsNullOrEmpty(member.Namespace) && member.Namespace != "internal") + newMember.Namespace = member.Namespace; + else newMember.Access = member.Access; + + var isAS2Event = ctx.Settings.LanguageId == "AS2" && member.Name.StartsWithOrdinal("on"); + if (!isAS2Event && ofClass.QualifiedName != "Object") newMember.Flags |= FlagType.Override; + string declaration; + var flags = member.Flags; + if ((flags & FlagType.Static) > 0) newMember.Flags |= FlagType.Static; + var parameters = member.Parameters; if ((flags & (FlagType.Getter | FlagType.Setter)) > 0) { - string type = member.Type; - string name = member.Name; - if (member.Parameters != null && member.Parameters.Count == 1) - type = member.Parameters[0].Type; - type = FormatType(type); - if (type == null && !features.hasInference) type = features.objectKey; - - bool genGetter = ofClass.Members.Search(name, FlagType.Getter, 0) != null; - bool genSetter = ofClass.Members.Search(name, FlagType.Setter, 0) != null; - - if (isHaxe) - { - // property is public but not the methods - acc = features.overrideKey; - } - - if (genGetter) - { - string tpl = TemplateUtils.GetTemplate("OverrideGetter", "Getter"); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Modifiers", acc); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Name", name); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Type", type); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Member", "super." + name); - decl += tpl; - } - if (genSetter) - { - string tpl = TemplateUtils.GetTemplate("OverrideSetter", "Setter"); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Modifiers", acc); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Name", name); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Type", type); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Member", "super." + name); - tpl = TemplateUtils.ReplaceTemplateVariable(tpl, "Void", ASContext.Context.Features.voidKey ?? "void"); - if (decl.Length > 0) - { - tpl = "\n\n" + tpl.Replace("$(EntryPoint)", ""); - } - decl += tpl; - } - decl = "$(Boundary)" + TemplateUtils.ReplaceTemplateVariable(decl, "BlankLine", ""); + if (IsHaxe) newMember.Access = Visibility.Private; + var type = newMember.Type; + if (parameters is not null && parameters.Count == 1 && parameters[0].Type is not null) type = parameters[0].Type; + type = MemberModel.FormatType(type); + if (type is null && !features.hasInference) type = features.objectKey; + newMember.Type = type; + declaration = ((ASGenerator) ctx.CodeGenerator).TryGetOverrideGetterTemplate(ofClass, parameters, newMember); + var set = ((ASGenerator) ctx.CodeGenerator).TryGetOverrideSetterTemplate(ofClass, parameters, newMember); + if (set.Length > 0 && declaration.Length > 0) set = "\n\n" + set.Replace("$(EntryPoint)", ""); + declaration += set; + declaration = TemplateUtils.ReplaceTemplateVariable(declaration, "BlankLine", ""); + typesUsed.Add(type); } else { - string type = FormatType(member.Type); - //if (type == null) type = features.objectKey; - - decl = acc + features.functionKey + " "; - bool noRet = type == null || type.Equals("void", StringComparison.OrdinalIgnoreCase); - type = (noRet && type != null) ? ASContext.Context.Features.voidKey : type; - if (!noRet) - { - string qType = getQualifiedType(type, ofClass); - typesUsed.Add(qType); - if (qType == type) - { - ClassModel rType = ASContext.Context.ResolveType(type, ofClass.InFile); - if (!rType.IsVoid()) type = rType.Name; - } - } - - string action = (isProxy || isAS2Event) ? "" : GetSuperCall(member, typesUsed, ofClass); - string template = TemplateUtils.GetTemplate("MethodOverride"); - + var type = MemberModel.FormatType(newMember.Type); + var noRet = type is null || type.Equals("void", StringComparison.OrdinalIgnoreCase); + type = (noRet && type is not null) ? features.voidKey : type; + if (!noRet) typesUsed.Add(type); + newMember.Template = member.Template; + newMember.Type = type; // fix parameters if needed - if (member.Parameters != null) - foreach (MemberModel para in member.Parameters) - if (para.Type == "any") para.Type = "*"; - - template = TemplateUtils.ReplaceTemplateVariable(template, "Modifiers", acc); - template = TemplateUtils.ReplaceTemplateVariable(template, "Name", member.Name); - template = TemplateUtils.ReplaceTemplateVariable(template, "Arguments", TemplateUtils.ParametersString(member, true)); - template = TemplateUtils.ReplaceTemplateVariable(template, "Type", type); + if (parameters is not null) + foreach (var para in parameters) + if (para.Type == "any") para.Type = "*"; + + newMember.Parameters = parameters; + var action = isProxy || isAS2Event ? "" : GetSuperCall(member, typesUsed); + var template = TemplateUtils.GetTemplate("MethodOverride"); + template = ((ASGenerator) ctx.CodeGenerator).ToDeclarationWithModifiersString(newMember, template); template = TemplateUtils.ReplaceTemplateVariable(template, "Method", action); - decl = template; + declaration = template; } - - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - if (ASContext.Context.Settings.GenerateImports && typesUsed.Count > 0) + if (ctx.Settings.GenerateImports && typesUsed.Count > 0) { - int offset = AddImportsByName(typesUsed, line); + var types = GetQualifiedTypes(typesUsed, ofClass.InFile); + var offset = AddImportsByName(types, line); position += offset; startPos += offset; } - - Sci.SetSel(startPos, position + member.Name.Length); - InsertCode(startPos, decl); + sci.SetSel(startPos, position + member.Name.Length); + InsertCode(startPos, declaration, sci); } - finally { Sci.EndUndoAction(); } + finally { sci.EndUndoAction(); } } - public static void GenerateDelegateMethods(ScintillaNet.ScintillaControl Sci, MemberModel member, - Dictionary selectedMembers, ClassModel classModel, ClassModel inClass) + protected virtual string TryGetOverrideGetterTemplate(ClassModel ofClass, List parameters, MemberModel newMember) { - Sci.BeginUndoAction(); - try - { - string result = TemplateUtils.ReplaceTemplateVariable( - TemplateUtils.GetTemplate("DelegateMethodsHeader"), - "Class", - classModel.Type); - - int position = -1; - ClassModel type; - List importsList = new List(); - bool isStaticMember = false; + var name = newMember.Name; + if (!ofClass.Members.Contains(name, FlagType.Getter)) return string.Empty; + var result = TemplateUtils.GetTemplate("OverrideGetter", "Getter"); + result = ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(newMember, result); + result = TemplateUtils.ReplaceTemplateVariable(result, "Member", $"super.{name}"); + return result; + } - if ((member.Flags & FlagType.Static) > 0) - isStaticMember = true; + protected virtual string TryGetOverrideSetterTemplate(ClassModel ofClass, List parameters, MemberModel newMember) + { + var name = newMember.Name; + if (!ofClass.Members.Contains(name, FlagType.Setter)) return string.Empty; + var result = TemplateUtils.GetTemplate("OverrideSetter", "Setter"); + result = ((ASGenerator) ASContext.Context.CodeGenerator).ToDeclarationWithModifiersString(newMember, result); + result = TemplateUtils.ReplaceTemplateVariable(result, "Member", $"super.{name}"); + result = TemplateUtils.ReplaceTemplateVariable(result, "Void", ASContext.Context.Features.voidKey ?? "void"); + return result; + } + public static void GenerateDelegateMethods(ScintillaControl sci, MemberModel member, Dictionary selectedMembers, ClassModel classModel, ClassModel inClass) + { + var ctx = ASContext.Context; + var generateImports = ctx.Settings.GenerateImports; + sci.BeginUndoAction(); + try + { + var result = TemplateUtils.GetTemplate("DelegateMethodsHeader"); + result = TemplateUtils.ReplaceTemplateVariable(result, "Class", classModel.Type); + var position = -1; + var importsList = new List(); + var isStaticMember = (member.Flags & FlagType.Static) > 0; inClass.ResolveExtends(); - - Dictionary.KeyCollection selectedMemberKeys = selectedMembers.Keys; - foreach (MemberModel m in selectedMemberKeys) - { - MemberModel mCopy = (MemberModel) m.Clone(); - - string methodTemplate = NewLine; - - bool overrideFound = false; - ClassModel baseClassType = inClass; - while (baseClassType != null && !baseClassType.IsVoid()) - { - MemberList inClassMembers = baseClassType.Members; - foreach (MemberModel inClassMember in inClassMembers) - { - if ((inClassMember.Flags & FlagType.Function) > 0 - && m.Name.Equals(inClassMember.Name)) - { - mCopy.Flags |= FlagType.Override; - overrideFound = true; - break; - } - } - - if (overrideFound) - break; - - baseClassType = baseClassType.Extends; - } - - if (isStaticMember && (m.Flags & FlagType.Static) == 0) - mCopy.Flags |= FlagType.Static; - - if ((m.Flags & FlagType.Setter) > 0) - { - methodTemplate += TemplateUtils.GetTemplate("Setter"); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers", - (TemplateUtils.GetStaticExternOverride(m) + TemplateUtils.GetModifiers(m)).Trim()); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", m.Name); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", ""); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", m.Parameters[0].Type); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + m.Name); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Void", ASContext.Context.Features.voidKey ?? "void"); - } - else if ((m.Flags & FlagType.Getter) > 0) - { - methodTemplate += TemplateUtils.GetTemplate("Getter"); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers", - (TemplateUtils.GetStaticExternOverride(m) + TemplateUtils.GetModifiers(m)).Trim()); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", m.Name); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", ""); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", FormatType(m.Type)); - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + m.Name); - } - else + foreach (var m in selectedMembers.Keys) + { + var mCopy = m.Clone(); + var methodTemplate = NewLine; + var baseClassType = inClass; + if (baseClassType.ContainsMember(m.Name, FlagType.Function, true)) + mCopy.Flags |= FlagType.Override; + var flags = m.Flags; + if (isStaticMember && (flags & FlagType.Static) == 0) mCopy.Flags |= FlagType.Static; + var variableTemplate = string.Empty; + ((ASGenerator) ctx.CodeGenerator).TryGetGetterSetterDelegateTemplate(member, m, ref flags, ref variableTemplate, ref methodTemplate); + if (!string.IsNullOrEmpty(variableTemplate)) result += variableTemplate + ":" + m.Type + ";"; + if ((flags & FlagType.Function) > 0) { methodTemplate += TemplateUtils.GetTemplate("Function"); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Body", "<<$(Return) >>$(Body)"); methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", null); - methodTemplate = TemplateUtils.ToDeclarationWithModifiersString(mCopy, methodTemplate); - if (m.Type != null && m.Type.ToLower() != "void") + methodTemplate = ((ASGenerator) ctx.CodeGenerator).ToDeclarationWithModifiersString(mCopy, methodTemplate); + if (m.Type is not null && m.Type.ToLower() != "void") methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Return", "return"); else methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Return", null); // check for varargs - bool isVararg = false; - if (m.Parameters != null && m.Parameters.Count > 0) + var isVararg = false; + if (!m.Parameters.IsNullOrEmpty()) { - MemberModel mm = m.Parameters[m.Parameters.Count - 1]; - if (mm.Name.StartsWith("...")) + var mm = m.Parameters[m.Parameters.Count - 1]; + if (mm.Name.StartsWithOrdinal("...")) isVararg = true; } - string callMethodTemplate = TemplateUtils.GetTemplate("CallFunction"); + var callMethodTemplate = TemplateUtils.GetTemplate("CallFunction"); if (!isVararg) { callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name", member.Name + "." + m.Name); - callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments", - TemplateUtils.CallParametersString(m)); + callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments", TemplateUtils.CallParametersString(m)); callMethodTemplate += ";"; } else { - List pseudoParamsList = new List(); - pseudoParamsList.Add(new MemberModel("null", null, FlagType.ParameterVar, 0)); - pseudoParamsList.Add(new MemberModel("[$(Subarguments)].concat($(Lastsubargument))", null, FlagType.ParameterVar, 0)); - MemberModel pseudoParamsOwner = new MemberModel(); - pseudoParamsOwner.Parameters = pseudoParamsList; - - callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name", - member.Name + "." + m.Name + ".apply"); - callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments", - TemplateUtils.CallParametersString(pseudoParamsOwner)); + var pseudoParamsList = new List + { + new MemberModel("null", null, FlagType.ParameterVar, 0), + new MemberModel("[$(Subarguments)].concat($(Lastsubargument))", null, FlagType.ParameterVar, 0) + }; + var pseudoParamsOwner = new MemberModel {Parameters = pseudoParamsList}; + callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Name", member.Name + "." + m.Name + ".apply"); + callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Arguments", TemplateUtils.CallParametersString(pseudoParamsOwner)); callMethodTemplate += ";"; - List arrayParamsList = new List(); + var arrayParamsList = new List(); for (int i = 0; i < m.Parameters.Count - 1; i++) { - MemberModel param = m.Parameters[i]; + var param = m.Parameters[i]; arrayParamsList.Add(param); } - pseudoParamsOwner.Parameters = arrayParamsList; - - callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Subarguments", - TemplateUtils.CallParametersString(pseudoParamsOwner)); - - callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Lastsubargument", - m.Parameters[m.Parameters.Count - 1].Name.TrimStart(new char[] { '.', ' '})); + callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Subarguments", TemplateUtils.CallParametersString(pseudoParamsOwner)); + callMethodTemplate = TemplateUtils.ReplaceTemplateVariable(callMethodTemplate, "Lastsubargument", m.Parameters[m.Parameters.Count - 1].Name.TrimStart('.', ' ')); } - methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Body", callMethodTemplate); } methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "BlankLine", NewLine); result += methodTemplate; - - if (m.Parameters != null) + if (generateImports && m.Parameters is not null) { - for (int i = 0; i < m.Parameters.Count; i++) - { - MemberModel param = m.Parameters[i]; - if (param.Type != null) - { - type = ASContext.Context.ResolveType(param.Type, selectedMembers[m].InFile); - importsList.Add(type.QualifiedName); - } - } + importsList.AddRange(from param in m.Parameters where param.Type is not null select param.Type); } - if (position < 0) { - MemberModel latest = GetLatestMemberForFunction(inClass, mCopy.Access, mCopy); - if (latest == null) + var latest = GetLatestMemberForFunction(inClass, mCopy.Access, mCopy); + if (latest is null) { - position = Sci.WordStartPosition(Sci.CurrentPos, true); - Sci.SetSel(position, Sci.WordEndPosition(position, true)); + position = sci.WordStartPosition(sci.CurrentPos, true); + sci.SetSel(position, sci.WordEndPosition(position, true)); } else { - position = Sci.PositionFromLine(latest.LineTo + 1) - ((Sci.EOLMode == 0) ? 2 : 1); - Sci.SetSel(position, position); + position = sci.PositionFromLine(latest.LineTo + 1) - ((sci.EOLMode == 0) ? 2 : 1); + sci.SetSel(position, position); } } - else - { - position = Sci.CurrentPos; - } - - if (m.Type != null) - { - type = ASContext.Context.ResolveType(m.Type, selectedMembers[m].InFile); - importsList.Add(type.QualifiedName); - } + else position = sci.CurrentPos; + if (generateImports && m.Type is not null) importsList.Add(m.Type); } - - if (importsList.Count > 0 && position > -1) + if (generateImports && importsList.Count > 0 && position > -1) { - int o = AddImportsByName(importsList, Sci.LineFromPosition(position)); - position += o; - Sci.SetSel(position, position); + var types = GetQualifiedTypes(importsList, inClass.InFile); + position += AddImportsByName(types, sci.LineFromPosition(position)); + sci.SetSel(position, position); } + InsertCode(position, result, sci); + } + finally { sci.EndUndoAction(); } + } - InsertCode(position, result); + protected virtual void TryGetGetterSetterDelegateTemplate(MemberModel member, MemberModel receiver, ref FlagType flags, ref string variableTemplate, ref string methodTemplate) + { + if ((flags & FlagType.Getter) != 0) + { + var modifiers = (TemplateUtils.GetStaticExternOverride(receiver) + TemplateUtils.GetModifiers(receiver)).Trim(); + methodTemplate += TemplateUtils.GetTemplate("Getter"); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers", modifiers); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", receiver.Name); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", ""); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", MemberModel.FormatType(receiver.Type)); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + receiver.Name); + flags &= ~FlagType.Function; + } + if ((flags & FlagType.Setter) != 0) + { + var modifiers = (TemplateUtils.GetStaticExternOverride(receiver) + TemplateUtils.GetModifiers(receiver)).Trim(); + methodTemplate += TemplateUtils.GetTemplate("Setter"); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Modifiers", modifiers); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Name", receiver.Name); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "EntryPoint", ""); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Type", receiver.Parameters[0].Type); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Member", member.Name + "." + receiver.Name); + methodTemplate = TemplateUtils.ReplaceTemplateVariable(methodTemplate, "Void", ASContext.Context.Features.voidKey ?? "void"); + flags &= ~FlagType.Function; } - finally { Sci.EndUndoAction(); } } - private static void GetStartPos(string currentText, ref int startPos, string keyword) + static void GetStartPos(string currentText, ref int startPos, string keyword) { - if (keyword == null) return; - int p = currentText.IndexOf(keyword); + if (keyword is null) return; + var p = currentText.IndexOfOrdinal(keyword); if (p > 0 && p < startPos) startPos = p; } - private static string GetShortType(string type) + static readonly Regex reShortType = new Regex(@"(?=\w+\.<)|(?:\w+\.)"); + + protected static string GetShortType(string type) { - if (type == null || type.Length == 0) - { - return type; - } - Regex r = new Regex(@"[^\.]+(\.<.+>)?(@.+|$)"); - Match m = r.Match(type); - if (m.Success) + if (string.IsNullOrEmpty(type)) return type; + if (!type.Contains('@') && type.LastIndexOf('.') is { } startIndex && startIndex != -1) { - type = m.Value; + var importName = type.Substring(startIndex + 1); + var imports = ASContext.Context.ResolveImports(ASContext.Context.CurrentModel); + if (imports.Count == 0) imports = ASContext.Context.CurrentModel.Imports; + if (!imports.Any(it => it.Name == importName && it.Type != type)) + type = reShortType.Replace(type, string.Empty); } - return type; - } - - private static string FormatType(string type) - { + else type = reShortType.Replace(type, string.Empty); return MemberModel.FormatType(type); } - private static string CleanType(string type) + static string CleanType(string type) { - if (type == null || type.Length == 0) - { - return type; - } - int p = type.IndexOf('$'); + if (string.IsNullOrEmpty(type)) return type; + var p = type.IndexOf('$'); if (p > 0) type = type.Substring(0, p); p = type.IndexOf('<'); if (p > 1 && type[p - 1] == '.') p--; if (p > 0) type = type.Substring(0, p); - p = type.IndexOf("@"); - if (p > 0) - { - type = type.Substring(0, p); - } + p = type.IndexOf('@'); + if (p > 0) type = type.Substring(0, p); return type; } - private static string GetSuperCall(MemberModel member, List typesUsed, ClassModel aType) + static string GetSuperCall(MemberModel member, ICollection typesUsed) { - string args = ""; - if (member.Parameters != null) - foreach (MemberModel param in member.Parameters) + var args = ""; + if (member.Parameters is not null) + foreach (var param in member.Parameters) { - if (param.Name.StartsWith(".")) break; - args += ", " + param.Name; - addTypeOnce(typesUsed, getQualifiedType(param.Type, aType)); + if (param.Name.StartsWith('.')) break; + args += ", " + TemplateUtils.GetParamName(param); + AddTypeOnce(typesUsed, param.Type); } - bool noRet = member.Type == null || member.Type.Length == 0 || member.Type.Equals("void", StringComparison.OrdinalIgnoreCase); - if (!noRet) addTypeOnce(typesUsed, getQualifiedType(member.Type, aType)); + var noRet = string.IsNullOrEmpty(member.Type) || member.Type.Equals("void", StringComparison.OrdinalIgnoreCase); + if (!noRet) AddTypeOnce(typesUsed, member.Type); - string action = ""; + var result = ""; if ((member.Flags & FlagType.Function) > 0) { - action = + result = (noRet ? "" : "return ") + "super." + member.Name + ((args.Length > 2) ? "(" + args.Substring(2) + ")" : "()") + ";"; } else if ((member.Flags & FlagType.Setter) > 0 && args.Length > 0) { - action = "super." + member.Name + " = " + member.Parameters[0].Name + ";"; + result = "super." + member.Name + " = " + member.Parameters[0].Name + ";"; } else if ((member.Flags & FlagType.Getter) > 0) { - action = "return super." + member.Name + ";"; + result = "return super." + member.Name + ";"; } - return action; + return result; } #endregion @@ -4249,25 +4081,22 @@ private static string GetSuperCall(MemberModel member, List typesUsed, C /// Generates all the missing imports in the given types list /// /// Types to import if needed - /// Resolve types to import from this other file /// Current line in editor /// Inserted characters count - private static int AddImportsByName(List typesUsed, int atLine) + protected static int AddImportsByName(IEnumerable typesUsed, int atLine) { - int length = 0; - IASContext context = ASContext.Context; - FileModel inFile = context.CurrentModel; - List addedTypes = new List(); - string cleanType = null; - foreach (string type in typesUsed) - { - cleanType = CleanType(type); - if (cleanType == null || cleanType.Length == 0 || cleanType.IndexOf('.') <= 0 || addedTypes.Contains(cleanType)) + var length = 0; + var context = ASContext.Context; + var addedTypes = new HashSet(); + typesUsed = context.DecomposeTypes(typesUsed); + foreach (var type in typesUsed) + { + var cleanType = CleanType(type); + if (string.IsNullOrEmpty(cleanType) || addedTypes.Contains(cleanType) || !cleanType.Contains('.')) continue; addedTypes.Add(cleanType); - MemberModel import = new MemberModel(cleanType.Substring(cleanType.LastIndexOf('.') + 1), cleanType, FlagType.Import, Visibility.Public); - if (!context.IsImported(import, atLine)) - length += InsertImport(import, false); + var import = new MemberModel(cleanType.Substring(cleanType.LastIndexOf('.') + 1), cleanType, FlagType.Import, Visibility.Public); + if (!context.IsImported(import, atLine)) length += InsertImport(import, false); } return length; } @@ -4280,26 +4109,24 @@ private static int AddImportsByName(List typesUsed, int atLine) /// Inserted characters count public static int InsertImport(MemberModel member, bool fixScrolling) { - ScintillaNet.ScintillaControl sci = ASContext.CurSciControl; - FileModel cFile = ASContext.Context.CurrentModel; - int position = sci.CurrentPos; - int curLine = sci.LineFromPosition(position); - - string fullPath = member.Type; + var fullPath = member.Type; if ((member.Flags & (FlagType.Class | FlagType.Enum | FlagType.TypeDef | FlagType.Struct)) > 0) { - /*if (member.InFile != null && member.InFile.Package != "" && member.InFile.Module != "") - fullPath = member.InFile.Package + "." + member.InFile.Module; - else*/ fullPath = CleanType(member.Type); + var inFile = member.InFile; + if (inFile is not null && inFile.Module == member.Name && inFile.Package != "") + fullPath = inFile.Package + "." + inFile.Module; + fullPath = CleanType(fullPath); } - string nl = LineEndDetector.GetNewLineMarker(sci.EOLMode); - string statement = "import " + fullPath + ";" + nl; - - // locate insertion point - int line = (ASContext.Context.InPrivateSection) ? cFile.PrivateSectionIndex : 0; - if (cFile.InlinedRanges != null) + var sci = PluginBase.MainForm.CurrentDocument.SciControl; + var newLineMarker = LineEndDetector.GetNewLineMarker(sci.EOLMode); + var statement = "import " + fullPath + ";" + newLineMarker; + var position = sci.CurrentPos; + var curLine = sci.LineFromPosition(position); + var cFile = ASContext.Context.CurrentModel; + var line = (ASContext.Context.InPrivateSection) ? cFile.PrivateSectionIndex : 0; + if (cFile.InlinedRanges is not null) { - foreach (InlineRange range in cFile.InlinedRanges) + foreach (var range in cFile.InlinedRanges) { if (position > range.Start && position < range.End) { @@ -4308,30 +4135,35 @@ public static int InsertImport(MemberModel member, bool fixScrolling) } } } - int firstLine = line; - bool found = false; - int packageLine = -1; - string txt; - int indent = 0; - Match mImport; + var firstLine = line; + var found = false; + var packageLine = -1; + var indent = 0; + var skipIfDef = 0; while (line < curLine) { - txt = sci.GetLine(line++).TrimStart(); - // insert imports after a package declaration - if (txt.StartsWith("package")) + var txt = sci.GetLine(line++).TrimStart(); + if (packageLine != -2 && txt.StartsWith("package")) { packageLine = line; firstLine = line; } - else if (txt.StartsWith("import")) + // skip Haxe #if blocks + else if (txt.StartsWithOrdinal("#if ") && !txt.Contains("#end")) skipIfDef++; + else if (skipIfDef > 0) + { + if (txt.StartsWithOrdinal("#end")) skipIfDef--; + else continue; + } + // insert imports after a package declaration + else if (txt.Length > 6 && txt.StartsWithOrdinal("import") && txt[6] <= 32) { - packageLine = -1; + packageLine = -2; found = true; indent = sci.GetLineIndentation(line - 1); // insert in alphabetical order - mImport = ASFileParserRegexes.Import.Match(txt); - if (mImport.Success && - String.Compare(mImport.Groups["package"].Value, fullPath) > 0) + var mImport = ASFileParserRegexes.Import.Match(txt); + if (mImport.Success && CaseSensitiveImportComparer.CompareImports(mImport.Groups["package"].Value, fullPath) > 0) { line--; break; @@ -4343,11 +4175,15 @@ public static int InsertImport(MemberModel member, bool fixScrolling) break; } - if (packageLine >= 0 && !isHaxe && txt.IndexOf('{') >= 0) + if (packageLine >= 0) { - packageLine = -1; - indent = sci.GetLineIndentation(line - 1) + PluginBase.MainForm.Settings.IndentSize; - firstLine = line; + if (IsHaxe) packageLine = -2; + else if (txt.Contains('{')) + { + packageLine = -2; + indent = sci.GetLineIndentation(line - 1) + PluginBase.Settings.IndentSize; + firstLine = line; + } } } @@ -4359,187 +4195,206 @@ public static int InsertImport(MemberModel member, bool fixScrolling) sci.ReplaceSel(statement); sci.SetLineIndentation(line, indent); sci.LineScroll(0, firstLine - sci.FirstVisibleLine + 1); - + ASContext.Context.RefreshContextCache(fullPath); - if (sci.EOLMode == 2) return sci.GetLine(line).Length + nl.Length; - else return sci.GetLine(line).Length + nl.Length - 1; + return sci.GetLine(line).Length; } #endregion #region common safe code insertion - static private int lookupPosition; - public static void InsertCode(int position, string src) + protected static int lookupPosition; + + public static void InsertCode(int position, string src) => InsertCode(position, src, PluginBase.MainForm.CurrentDocument?.SciControl); + + public static void InsertCode(int position, string src, ScintillaControl sci) { - ScintillaNet.ScintillaControl Sci = ASContext.CurSciControl; - Sci.BeginUndoAction(); + sci.BeginUndoAction(); try { - if (ASContext.CommonSettings.StartWithModifiers) - src = FixModifiersLocation(src); + if (ASContext.CommonSettings.DeclarationModifierOrder.Length > 1) + src = FixModifiersLocation(src, ASContext.CommonSettings.DeclarationModifierOrder); - int len = SnippetHelper.InsertSnippetText(Sci, position + Sci.MBSafeTextLength(Sci.SelText), src); + int len = SnippetHelper.InsertSnippetText(sci, position + sci.MBSafeTextLength(sci.SelText), src); UpdateLookupPosition(position, len); - AddLookupPosition(); + AddLookupPosition(sci); } - finally { Sci.EndUndoAction(); } + finally { sci.EndUndoAction(); } } /// - /// Move "visibility" modifier at the beginning of the line + /// Order declaration modifiers /// - private static string FixModifiersLocation(string src) + static string FixModifiersLocation(string src, string[] modifierOrder) { - bool needUpdate = false; - string[] lines = src.Split('\n'); - for (int i = 0; i < lines.Length; i++) + var needUpdate = false; + var lines = src.Split('\n'); + for (var i = 0; i < lines.Length; i++) { - string line = lines[i]; + var line = lines[i]; + var m = reModifiers.Match(line); + if (!m.Success) continue; - Match m = reModifiers.Match(line); - if (m.Success) + Group decl = m.Groups[2]; + string modifiers = decl.Value; + string before = "", after = ""; + bool insertAfter = false; + + foreach (var it in modifierOrder) { - Group decl = m.Groups[2]; - Match m2 = reModifier.Match(decl.Value); - if (m2.Success) + if (it == GeneralSettings.DECLARATION_MODIFIER_REST) insertAfter = true; + else { - string repl = m2.Value + decl.Value.Remove(m2.Index, m2.Length); - lines[i] = line.Remove(decl.Index, decl.Length).Insert(decl.Index, repl); - needUpdate = true; + var modifier = RemoveAndExtractModifier(it, ref modifiers); + if (insertAfter) after += modifier; + else before += modifier; } } + + modifiers = before + modifiers + after; + + if (decl.Value != modifiers) + { + lines[i] = line.Remove(decl.Index, decl.Length).Insert(decl.Index, modifiers); + needUpdate = true; + } } - if (needUpdate) return String.Join("\n", lines); - else return src; + return needUpdate ? string.Join("\n", lines) : src; } - private static void UpdateLookupPosition(int position, int delta) + static string RemoveAndExtractModifier(string modifier, ref string modifiers) { - if (lookupPosition > position) - { - if (lookupPosition < position + delta) lookupPosition = position;// replaced text at cursor position - else lookupPosition += delta; - } + modifier += " "; + var index = modifiers.IndexOfOrdinal(modifier); + if (index == -1) return null; + modifiers = modifiers.Remove(index, modifier.Length); + return modifier; } - private static void AddLookupPosition() + protected static void UpdateLookupPosition(int position, int delta) { - if (lookupPosition >= 0) - { - ScintillaNet.ScintillaControl Sci = ASContext.CurSciControl; - if (Sci == null) return; - int lookupLine = Sci.LineFromPosition(lookupPosition); - int lookupCol = lookupPosition - Sci.PositionFromLine(lookupLine); - ASContext.Panel.SetLastLookupPosition(ASContext.Context.CurrentFile, lookupLine, lookupCol); - } + if (lookupPosition <= position) return; + if (lookupPosition < position + delta) lookupPosition = position;// replaced text at cursor position + else lookupPosition += delta; + } + + static void AddLookupPosition() => AddLookupPosition(PluginBase.MainForm.CurrentDocument?.SciControl); + + protected static void AddLookupPosition(ScintillaControl sci) + { + if (lookupPosition < 0 || sci is null) return; + var lookupLine = sci.LineFromPosition(lookupPosition); + var lookupCol = lookupPosition - sci.PositionFromLine(lookupLine); + // TODO: Refactor, doesn't make a lot of sense to have this feature inside the Panel + ASContext.Panel.SetLastLookupPosition(sci.FileName, lookupLine, lookupCol); } - #endregion + + #endregion } #region related structures /// /// Available generators /// - public enum GeneratorJobType:int + public enum GeneratorJobType : long { - GetterSetter, - Getter, - Setter, - ComplexEvent, - BasicEvent, - Delegate, - Variable, - Function, - ImplementInterface, - PromoteLocal, - MoveLocalUp, - AddImport, - Class, - FunctionPublic, - VariablePublic, - Constant, - Constructor, - ToString, - FieldFromPatameter, - AddInterfaceDef, - ConvertToConst, - AddAsParameter, - ChangeMethodDecl, - EventMetatag, - AssignStatementToVar, - ChangeConstructorDecl, + GetterSetter = 1, + Getter = 1 << 1, + Setter = 1 << 2, + ComplexEvent = 1 << 3, + BasicEvent = 1 << 4, + Delegate = 1 << 5, + Variable = 1 << 6, + Function = 1 << 7, + ImplementInterface = 1 << 8, + PromoteLocal = 1 << 9, + MoveLocalUp = 1 << 10, + AddImport = 1 << 11, + Class = 1 << 12, + FunctionPublic = 1 << 13, + VariablePublic = 1 << 14, + Constant = 1 << 15, + Constructor = 1 << 16, + ToString = 1 << 17, + FieldFromParameter = 1 << 18, + AddInterfaceDef = 1 << 19, + ConvertToConst = 1 << 20, + AddAsParameter = 1 << 21, + ChangeMethodDecl = 1 << 22, + EventMetatag = 1 << 23, + AssignStatementToVar = 1 << 24, + ChangeConstructorDecl = 1 << 25, + Interface = 1 << 26, + User = 1 << 27, } /// /// Generation completion list item /// - class GeneratorItem : ICompletionListItem + public class GeneratorItem : ICompletionListItem { - private string label; - private GeneratorJobType job; - private MemberModel member; - private ClassModel inClass; - private Object data; + internal GeneratorJobType Job { get; } + readonly MemberModel member; + readonly ClassModel inClass; + readonly Action action; - public GeneratorItem(string label, GeneratorJobType job, MemberModel member, ClassModel inClass) + public GeneratorItem(string label, GeneratorJobType job, Action action) : this(label, job, action, null) { - this.label = label; - this.job = job; - this.member = member; - this.inClass = inClass; } - public GeneratorItem(string label, GeneratorJobType job, MemberModel member, ClassModel inClass, Object data) : this(label, job, member, inClass) + public GeneratorItem(string label, GeneratorJobType job, Action action, object data) { - - this.data = data; + Label = label; + Job = job; + this.action = action; + Data = data; } - public string Label + public GeneratorItem(string label, GeneratorJobType job, MemberModel member, ClassModel inClass) : this(label, job, member, inClass, null) { - get { return label; } - } - public string Description - { - get { return TextHelper.GetString("Info.GeneratorTemplate"); } } - public System.Drawing.Bitmap Icon + public GeneratorItem(string label, GeneratorJobType job, MemberModel member, ClassModel inClass, object data) { - get { return (System.Drawing.Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_DECLARATION); } + Label = label; + Job = job; + this.member = member; + this.inClass = inClass; + Data = data; } + public string Label { get; } + + public string Description => TextHelper.GetString("Info.GeneratorTemplate"); + + public Bitmap Icon => (Bitmap)ASContext.Panel.GetIcon(PluginUI.ICON_DECLARATION); + public string Value { get { - ASGenerator.GenerateJob(job, member, inClass, label, data); + if (action is not null) action(); + else ASGenerator.GenerateJob(Job, member, inClass, Label, Data); return null; } } - public Object Data - { - get - { - return data; - } - } + public object Data { get; } } - class FoundDeclaration + public class FoundDeclaration { - public MemberModel member; - public ClassModel inClass; + public MemberModel Member; + public ClassModel InClass; public FoundDeclaration() { - member = null; - inClass = ClassModel.VoidClass; + Member = null; + InClass = ClassModel.VoidClass; } } - class FunctionParameter + public class FunctionParameter { public string paramType; public string paramQualType; @@ -4548,7 +4403,7 @@ class FunctionParameter public FunctionParameter(string parameter, string paramType, string paramQualType, ASResult result) { - this.paramName = parameter; + paramName = parameter; this.paramType = paramType; this.paramQualType = paramQualType; this.result = result; @@ -4557,16 +4412,16 @@ public FunctionParameter(string parameter, string paramType, string paramQualTyp class StatementReturnType { - public ASResult resolve; - public Int32 position; - public String word; + public readonly ASResult Resolve; + public readonly int Position; + public readonly string Word; - public StatementReturnType(ASResult resolve, Int32 position, String word) + public StatementReturnType(ASResult resolve, int position, string word) { - this.resolve = resolve; - this.position = position; - this.word = word; + Resolve = resolve; + Position = position; + Word = word; } } #endregion -} +} \ No newline at end of file diff --git a/External/Plugins/ASCompletion/Completion/ArgumentsProcessor.cs b/External/Plugins/ASCompletion/Completion/ArgumentsProcessor.cs index 78366bd453..ddc3ec5131 100644 --- a/External/Plugins/ASCompletion/Completion/ArgumentsProcessor.cs +++ b/External/Plugins/ASCompletion/Completion/ArgumentsProcessor.cs @@ -1,36 +1,24 @@ -using System; using System.Collections; -using System.Text; using System.Text.RegularExpressions; namespace ASCompletion.Completion { public class ArgumentsProcessor { - static public string Process(string text, Hashtable variables) - { - ArgumentsProcessor proc = new ArgumentsProcessor(); - proc.variables = variables; - return proc.Run(text); - } - - /* PRIVATE */ + static readonly Regex re_Argument = + new Regex("\\$\\((?[a-z]+)\\)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); - static private Regex re_Argument = - new Regex("\\$\\((?[a-z]+)\\)", RegexOptions.Compiled | RegexOptions.IgnoreCase); + public static string Process(string text, Hashtable variables) => new ArgumentsProcessor {variables = variables}.Run(text); - private Hashtable variables; + Hashtable variables; - private string Run(string text) - { - return re_Argument.Replace(text, new MatchEvaluator(Lookup)); - } + string Run(string text) => re_Argument.Replace(text, Lookup); - private string Lookup(Match m) + string Lookup(Match m) { - string name = m.Groups["name"].Value; + var name = m.Groups["name"].Value; if (variables.ContainsKey(name)) return (string)variables[name]; - else return m.Value; + return m.Value; } } } diff --git a/External/Plugins/ASCompletion/Completion/Brace.cs b/External/Plugins/ASCompletion/Completion/Brace.cs new file mode 100644 index 0000000000..5e7ab19cfb --- /dev/null +++ b/External/Plugins/ASCompletion/Completion/Brace.cs @@ -0,0 +1,319 @@ +using System; +using System.Text.RegularExpressions; +using PluginCore; +using Array = System.Array; + +namespace ASCompletion.Completion +{ + /// + /// Represents a set of brace characters used for automatic closing braces. + /// + [Serializable] + public sealed class Brace + { + string name; + char open; + char close; + bool addSpace; + bool ignoreWhitespace; + Rule[] rules; + + public string Name + { + get => name; + set => name = value; + } + + public char Open + { + get => open; + set => open = value; + } + + public char Close + { + get => close; + set => close = value; + } + + public bool AddSpace + { + get => addSpace; + set => addSpace = value; + } + + public bool IgnoreWhitespace + { + get => ignoreWhitespace; + set => ignoreWhitespace = value; + } + + public Rule[] Rules + { + get => rules; + set => rules = value ?? Array.Empty(); + } + + /// + /// Creates an instance of . + /// + public Brace(string name, char open, char close, bool addSpace, bool ignoreWhitespace, Rule[] rules) + { + Name = name; + Open = open; + Close = close; + AddSpace = addSpace; + IgnoreWhitespace = ignoreWhitespace; + Rules = rules; + } + + /// + /// Returns whether this brace should open with the matching close brace automatically inserted. + /// + public bool ShouldOpen(char charBefore, byte styleBefore, char charAfter, byte styleAfter) + { + foreach (var it in rules) + { + if (it.Matches(charBefore, styleBefore, charAfter, styleAfter)) + { + return true; + } + } + return false; + } + + /// + /// Returns whether this brace should close with the matching close brace overwritten. + /// + public bool ShouldClose(int currentPosition, int nextPosition) + { + return ignoreWhitespace || currentPosition == nextPosition; + } + + /// + /// Returns whether this brace should remove the matching close brace. + /// + public bool ShouldRemove(int currentPosition, int nextPosition) + { + return ignoreWhitespace || currentPosition == nextPosition; + } + + /// + /// Returns a object that represents the current object. + /// + public override string ToString() + { + return open + " " + name + " " + close; + } + + [Serializable] + public sealed class Rule + { + bool notAfterChars; + Regex afterChars; + bool notAfterStyles; + Style[] afterStyles; + bool notBeforeChars; + Regex beforeChars; + bool notBeforeStyles; + Style[] beforeStyles; + Logic logic; + + public Rule() + { + notAfterChars = false; + afterChars = null; + notAfterStyles = false; + afterStyles = null; + notBeforeChars = false; + beforeChars = null; + notBeforeStyles = false; + BeforeStyles = null; + logic = 0; + } + + public Rule(bool? notAfterChars, string afterChars, bool? notAfterStyles, Style[] afterStyles, bool? notBeforeChars, string beforeChars, bool? notBeforeStyles, Style[] beforeStyles, Logic? logic) + { + Logic = logic ?? 0; + NotAfterChars = notAfterChars ?? this.logic != 0; + AfterChars = afterChars; + NotAfterStyles = notAfterStyles ?? this.logic != 0; + AfterStyles = afterStyles; + NotBeforeChars = notBeforeChars ?? this.logic != 0; + BeforeChars = beforeChars; + NotBeforeStyles = notBeforeStyles ?? this.logic != 0; + BeforeStyles = beforeStyles; + } + + public bool NotAfterChars + { + get => notAfterChars; + set => notAfterChars = value; + } + + public string AfterChars + { + get => FromRegex(afterChars); + set => afterChars = ToRegex(value); + } + + public bool NotAfterStyles + { + get => notAfterStyles; + set => notAfterStyles = value; + } + + public Style[] AfterStyles + { + get => afterStyles ?? Array.Empty + + + + + +

    Artistic Style 2.06

    + +

    + A Free, Fast, and Small Automatic Formatter
    + for C, C++, C++/CLI, Objective‑C, C#, and Java Source Code +

    + +

    Contents

    + +

    + General Information +

    +

    + Quick Start +

    +

    + Usage +

    +

    + Options +

    +

    + Options File +

    +

    + Disable Formatting +

    +

    + Bracket Style Options +

    +

    + default bracket style    + style=allman    + style=java    + style=kr    + style=stroustrup    + style=whitesmith    + style=vtk    + style=banner    + style=gnu    + style=linux    + style=horstmann    + style=1tbs    + style=google    + style=pico    + style=lisp    +

    +

    + Tab Options +

    +

    + default indent    + indent=spaces    + indent=tab    + indent=force‑tab    + --indent=force‑tab‑x    +

    +

    + Bracket Modify Options +

    +

    + attach‑namespaces    + attach‑classes    + attach‑inlines    + attach‑extern‑c    +

    +

    + Indentation Options +

    +

    + indent‑classes    + indent‑modifiers    + indent‑switches    + indent‑cases    + indent‑namespaces    + indent‑labels    + indent‑preproc‑block    + indent‑preproc‑define    + indent‑preproc‑cond    + indent‑col1‑comments    + min‑conditional‑indent    + max‑instatement‑indent    +

    +

    + Padding Options +

    +

    + break‑blocks    + break‑blocks=all    + pad‑oper    + pad‑comma    + pad‑paren    + pad‑paren‑out    + pad‑first‑paren‑out    + pad‑paren‑in    + pad‑header    + unpad‑paren    + delete‑empty‑lines    + fill‑empty‑lines    + align‑pointer    + align‑reference    +

    +

    + Formatting Options +

    +

    + break‑closing‑brackets    + break‑elseifs    + add‑brackets    + add‑one‑line‑brackets    + remove‑brackets    + keep‑one‑line‑blocks    + keep‑one‑line‑statements    + convert‑tabs    + close‑templates    + remove‑comment‑prefix    + max‑code‑length    + break‑after‑logical    + mode    +

    +

    + Objective‑C Options +

    +

    + pad‑method‑prefix    + unpad‑method‑prefix    + pad‑return‑type    + unpad‑return‑type    + align‑method‑colon    + pad‑method‑colon    +

    +

    + Other Options    +

    +

    + suffix    suffix=none    + recursive    + dry-run    + exclude    + ignore‑exclude‑errors    + ignore‑exclude‑errors‑x    + errors‑to‑stdout    + preserve‑date    + verbose    + formatted    + quiet    + lineend    +

    +

    + Command Line Only +

    +

    + options    + options=none    + ascii    + version    + help    + html    + html=    +

    +

    +   +

    +
    + + + +

    General Information

    + +

    Line Endings

    + +

    + Line endings in the formatted file will be the same as the input file. If there are mixed line endings the most + frequent occurrence will be used. There is also an option to specify or change the line endings. +

    + +

    File Type

    + +

    + Artistic Style will determine the file type from the file extension. The extension ".java" indicates a Java file, + and ".cs" indicates a C# file. Everything else is a C type file (C, C++, C++/CLI, or Objective-C). If you are + using a non-standard file extension for Java or C#, use one of the --mode= options. +

    + +

    Wildcards and Recursion

    + +

    + Artistic Style can process directories recursively. Wildcards (such as "*.cpp" or "*.c??") are processed internally. + If a shell is used it should pass the wildcards to Artistic Style instead of resolving them first. For Linux use + double quotes around paths whose file name contains wildcards. For Windows use double quotes around paths whose + file name contains spaces. The recursive option in the + Other Options section contains information on recursive processing. +

    + +

    File Names

    + +

    + When a file is formatted, the newly indented file retains the original file name. A copy of the original file + is created with an .orig appended to the original file name. (This can be set to + a different string by the option --suffix=, or suppressed altogether by the options -n + or --suffix=none). Thus, after indenting SourceFile.cpp the indented file will + be named SourceFile.cpp, while the original pre-indented file will be renamed to SourceFile.cpp.orig. +

    + +

    Internationalization

    + +

    + Artistic Style has been internationalized to process files and directories in any language. +

    +

    + It has also been translated into several languages. The translation to use is determined from the User Locale + for Windows and the LANG environment variable for other systems. The translation will be done automatically from + these settings. If no translation is available it will default to English. There is an ascii option to use English + instead of the system language. +

    +

    + The source code for the translations is at the end of ASLocalizer.cpp in the form of an English‑Translation + pair. If you make corrections to a translation, send the source as a bug report and it will be included in the + next release. +

    +

    + To add a new language, add a new translation class to ASLocalizer.h. Add the English‑Translation pair to + the constructor in ASLocalizer.cpp. Update the WinLangCode array and add the language code to the function setTranslationClass(). + The ASLocalizer.cpp program contains comments that give web pages for obtaining the LCIDs and language codes. + Send the source code as a bug report and it will be included in the next release. +

    + +

    Other Considerations

    + +

    + The names of special characters used in programming vary by region. The terminology used by Artistic Style, + followed by other common names, is: +

    +
    + brackets { } ‑ also called braces, curly brackets, or curly braces.
    + parens ( ) ‑ also called parentheses, brackets, round brackets, circle brackets, or soft brackets.
    + block parens [ ] ‑ also called brackets, square brackets, closed brackets, or hard brackets.
    + angle brackets < > ‑ also called brackets, pointy brackets, triangular brackets, diamond brackets, tuples, + or chevrons. +
    +

    + Artistic Style can format standard class library statements such as Open GL, wxWidgets, Qt, and MFC. +

    +

    + Embedded assembler language is formatted correctly. This includes extended assembly and Microsoft specific assembler + lines and blocks. +

    +

    + Artistic Style can format embedded SQL statements. The SQL formatting will be maintained as long as the standard + hanging indent format is used. If the "exec sql" statement is indented more than the following statements, the + SQL will be aligned in a single column. +

    +

    + Unicode files encoded as UTF‑16, both big and little endian, will be formatted. The files must begin with + a byte order mark (BOM) to be recognized. Files encoded as UTF‑32 will be rejected. Some compilers do not + support these encodings. These files can be converted to UTF‑8 encoding with the program "iconv". There + are Linux and Windows versions available (the Windows version does not seem to work for all encodings). A sample + command line is "iconv ‑f  UTF‑16 ‑t UTF‑8 < filein.cpp > fileout.cpp. Visual + Studio can convert the files from the "File > Advanced Save Options" menu. Then select encoding "Unicode (UTF‑8 + with signature) - Codepage 65001". There are other development environments and text editors, such as SciTE, that + can convert files to UTF‑8. +

    +

    + Embedded statements that are multiple-line and are NOT in a C-type format, such as Python, are usually mal-formatted + (a C-type format has blocks enclosed by brackets and statements terminated by a semi-colon). Macros that define + functions may cause the following code to be mal-formatted because the macro is missing the brackets and semi-colons + from the definition. If you have source code with these types of statements, exclude them with the + exclude=#### option described in the Other Options section. +

    +

    +   +

    +
    + + + +

    Quick Start

    + +

    + If you have never used Artistic Style there are a couple of ways to start. +

    +

    + One is to run it with no options at all. This will use the default bracket + style, 4 spaces per indent, and no formatting changes. This will break the brackets for one + line blocks and will break one line statements. To change this use the option + keep-one-line-blocks and/or + keep-one-line-statements described in the + Formatting Options section +

    +

    + Another way is to use one of the bracket styles described in the Bracket Style + Options section. Select one with a bracket formatting style you like. If no indentation option is set, + the default option of 4 spaces will be used. These options also break one line blocks and one line statements + as described above. +

    +

    + Once you are familiar with the options you can customize the format to your personal preference. +

    +

    +   +

    +
    + + + +

    Usage

    + +

    + Artistic style is a console program that receives information from the command line. The format of the command + line is: +

    +
    astyle  [OPTIONS]  SourceFile1  SourceFile2  SourceFile3  [ . . . ]
    +
    +

    + The block parens [ ] indicate that more than one option or more than one file name can be entered. They are NOT + actually included in the command. For the options format see the following Options section. +

    +
    +

    +   Example to format a single file: +

    +
    astyle  --style=allman  /home/user/project/foo.cpp
    +
    +

    +   Example to format all .cpp and .h files recursively: +

    +
    astyle  --style=allman --recursive  /home/user/project/*.cpp  /home/user/project/*.h
    +
    +
    +

    + Another option will format a single file and change the name: +

    +
    astyle  [OPTIONS] < OriginalSourceFile > BeautifiedSourceFile
    +
    +

    + This option can be used to display the formatted file without updating: +

    +
    astyle  [OPTIONS] < OriginalSourceFile | less
    +
    +

    + The < and > characters are used + to redirect the files into standard input (cin) and out of standard output (cout) - don't forget them! With this + option only one file at a time can be formatted. Wildcards are not recognized, there are no console messages, + and a backup is not created. On Windows the output will always have Windows line ends. +

    +

    +   +

    +
    + + + +

    Options

    + +

    + Not specifying any options will result in the default bracket style, + 4 spaces per indent, and no formatting changes. +

    +

    + Options may be written in two different ways. +

    + +

    Long options

    + +

    + These options start with '--', and must be written one at a time.
    + (Example: '--style=allman --indent=spaces=4') +

    + +

    Short Options

    + +

    + These options start with a single '-', and may be concatenated together.
    + (Example: '-bps4' is the same as writing '-b -p -s4'.) +

    +

    +   +

    +
    + + + +

    Options File

    + +

    + An OPTIONAL default options file may be used to supplement or replace the command line options.  +

    +
      +
    • The command line options have precedence. If there is a conflict between a command line option and an option in + the default options file, the command line option will be used. +
    • +
    • Artistic Style looks for this file in the following locations (in order): +
        +
      1. the file indicated by the --options= command line option;
      2. +
      3. the file and directory indicated by the environment variable ARTISTIC_STYLE_OPTIONS (if it exists);
      4. +
      5. the file named .astylerc in the directory pointed to by the HOME environment variable (e.g. "$HOME/.astylerc" + on Linux); +
      6. +
      7. the file named astylerc in the directory pointed to by the USERPROFILE environment variable (e.g. "%USERPROFILE%\astylerc" + on Windows). +
      8. +
      +
    • +
    • This option file lookup can be disabled by specifying --options=none on the command line.
    • +
    • Options may be set apart by new-lines, tabs, commas, or spaces.
    • +
    • Long options in the options file may be written without the preceding '--'.
    • +
    • Lines within the options file that begin with '#' are considered line-comments.
    • +
    +

    + Example of a default options file: +

    +
    +
    # this line is a comment
    +--style=allman      # this is a line-end comment
    +# long options can be written without the preceding '--'
    +indent-switches     # cannot do this on the command line
    +# short options must have the preceding '-'
    +-t -p
    +# short options can be concatenated together
    +-M60Ucv
    +
    +

    +   +

    + +
    + + + +

    + Disable Formatting +

    + +

    + Formatting and indenting can be disabled with comment tags inserted in the source code. +

    + +

    + Disable Block +

    + +

    + Blocks of code can be disabled using "off" and "on" tags. The tags are included in the source + file as comments. The comment may be a C comment (/* ... */) or a C++ line comment (//). The tag must be included + in a single line comment. If the comment exceeds one line the indent tag will be ignored. Additional information + can be included with the tag. +

    +

    + The beginning tag is "*INDENT-OFF*" and the ending tag is "*INDENT-ON*". + They may be used anywhere in the program with the following condition; parsing is partially disabled between the + tags. Disabling partial statements may result in incorrect formatting after the ending tag. If this happens expand + the tags to include additional code. +

    +
    +

    + The following retains the format of a preprocessor define: +

    +
    // *INDENT-OFF*
    +#define FOO_DECLARE_int32_(name) \
    +        FOO_API_ extern ::Int32 FOO_FLAG(name)
    +// *INDENT-ON*
    +
    + +

    + Disable Line +

    + +

    + Artistic Style cannot always determine the usage of symbols with more than one meaning. For example an asterisk + (*) can be multiplication, a pointer, or a pointer dereference. The "&" and "&&" + symbols are a similar + problem. +

    +

    + If a symbol is being padded incorrectly, padding it manually may fix the problem. If it is still being + padded incorrectly, then disabling the formatting may be necessary. To avoid having to use the "disable block" + tags above, a single line disable is available. +

    +

    + A line-end comment tag "*NOPAD* will disable the "pad-oper", "align-pointer", and "align-reference" + options. Parsing does NOT stop and all other formatting will be applied to the line. The tag applies to the + one line only. +

    +
    +

    + The following prevents the operator padding from changing: +

    +
    size_t foo = (unsigned int) -1;  // *NOPAD*
    +
    +

    +   +

    +
    + + + +

    Bracket Style Options

    + +

    + Bracket Style options define the bracket style to use. All options default to 4 spaces per indent, indented with + spaces. + By default, none of the styles indent namespaces. Other indentations are indicated in the individual style + description. All options will break the brackets for one line blocks and will break one line statements. To change + this + use the option keep-one-line-blocks and/or + keep-one-line-statements described in the Formatting Options section +

    +

    +   +

    +

    + default bracket style
    + If no bracket style is requested, the default bracket style will be used. The opening brackets are not changed + and the closing brackets will be broken from the preceding line. There are a few exceptions to this. +

    +

    +   +

    +

    + --style=allman / --style=bsd / --style=break / -A1
    + Allman style uses broken brackets. +

    +
    +
    int Foo(bool isBar)
    +{
    +    if (isBar)
    +    {
    +        bar();
    +        return 1;
    +    }
    +    else
    +        return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=java / --style=attach / -A2
    + Java style uses attached brackets. +

    +
    +
    int Foo(bool isBar) {
    +    if (isBar) {
    +        bar();
    +        return 1;
    +    } else
    +        return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=kr / --style=k&r / --style=k/r / -A3
    + Kernighan & Ritchie style uses linux brackets. Opening brackets are broken from namespaces, classes, and function + definitions. Brackets are attached to everything else including statements within a function, arrays, structs, + and enums. +

    +

    + Using the k&r option may cause problems because of the &. This can be resolved by enclosing the k&r + in quotes (e.g. ‑‑style="k&r") or by using one of the alternates ‑‑style=kr or ‑‑style=k/r. +

    +
    +
    int Foo(bool isBar)
    +{
    +    if (isBar) {
    +        bar();
    +        return 1;
    +    } else
    +        return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=stroustrup / -A4
    + Stroustrup style uses stroustrup brackets. Brackets are broken from function definitions only. Brackets are attached + to everything else including namespaces, classes, and statements within a function, arrays, structs, and enums. + This style frequently is used with an indent of 5 spaces. +

    +
    +
    int Foo(bool isBar)
    +{
    +    if (isBar) {
    +        bar();
    +        return 1;
    +    } else
    +        return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=whitesmith / -A5
    + Whitesmith style uses broken, indented brackets. Switch blocks and class blocks are indented to prevent a 'hanging + indent' with following case statements and C++ class modifiers (public, private, protected).  +

    +
    +
    int Foo(bool isBar)
    +    {
    +    if (isBar)
    +        {
    +        bar();
    +        return 1;
    +        }
    +    else
    +        return 0;
    +    }
    +
    +
    +

    +   +

    +

    + --style=vtk / -A15
    + VTK (Visualization Toolkit) style uses broken, indented brackets, except for the opening bracket. Switch blocks + are indented to prevent a 'hanging indent' with following case statements.  +

    +
    +
    int Foo(bool isBar)
    +{
    +    if (isBar)
    +        {
    +        bar();
    +        return 1;
    +        }
    +    else
    +        return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=banner / -A6
    + Banner style uses attached, indented brackets. Switch blocks and class blocks are indented to prevent a 'hanging + indent' with following case statements and C++ class modifiers (public, private, protected).  +

    +
    +
    int Foo(bool isBar) {
    +    if (isBar) {
    +        bar();
    +        return 1;
    +        }
    +    else
    +        return 0;
    +    }
    +
    +
    +

    +   +

    +

    + --style=gnu / -A7
    + GNU style uses broken brackets and indented blocks. This style frequently is used with + an indent of 2 spaces. +

    +

    + Extra indentation is added to blocks within a function. The opening bracket for namespaces, classes, + and functions is not indented. +

    +
    +
    int Foo(bool isBar)
    +{
    +    if (isBar)
    +        {
    +            bar();
    +            return 1;
    +        }
    +    else
    +        return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=linux / --style=knf / -A8
    + Linux style uses linux brackets. Opening brackets are broken from namespace, class, and function + definitions. Brackets are attached to everything else including statements within a function, arrays, structs, + and enums. Minimum conditional indent is one-half indent. If you want a different minimum conditional + indent use the K&R style instead. This style works best with a large indent. It frequently is used with an + indent of 8 spaces. +

    +

    + Also known as Kernel Normal Form (KNF) style, this is the style used in the Linux kernel. +

    +
    +
    int Foo(bool isBar)
    +{
    +        if (isFoo) {
    +                bar();
    +                return 1;
    +        } else
    +                return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=horstmann / -A9
    + Horstmann style uses run-in brackets. Brackets are broken and allow run-in statements. + Switches are indented to allow a run-in to the opening switch block. This style frequently is used with an indent + of 3 spaces. +

    +
    +
    int Foo(bool isBar)
    +{   if (isBar)
    +    {   bar();
    +        return 1;
    +    }
    +    else
    +        return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=1tbs / --style=otbs / -A10
    + "One True Brace Style" uses linux brackets and adds brackets to unbracketed one line conditional + statements. Opening brackets are broken from namespaces, classes, and function definitions. Brackets are attached + to everything else including statements within a function, arrays, structs, and enums.  +

    +

    + In the following example brackets have been added to the "return 0;" statement. The option + ‑‑add‑one‑line‑brackets can also be used with this style. +

    +
    +
    int Foo(bool isBar)
    +{
    +    if (isFoo) {
    +        bar();
    +        return 1;
    +    } else {
    +        return 0;
    +    }
    +}
    +
    +
    +

    +   +

    +

    + --style=google / -A14
    + Google style uses attached brackets and indented class access modifiers. See the indent-modifiers + option for an example of the indented modifiers format. This style frequently is used with an indent of 2 spaces. +

    +
    +
    int Foo(bool isBar) {
    +    if (isBar) {
    +        bar();
    +        return 1;
    +    } else
    +        return 0;
    +}
    +
    +
    +

    +   +

    +

    + --style=pico / -A11
    + Pico style uses run-in brackets and attached closing brackets. Opening brackets are broken + and allow run-in statements. The closing bracket is attached to the last line in the block. Switches are indented + to allow a run-in to the opening switch block. The style implies keep-one-line-blocks and keep-one-line-statements. + If add-brackets is used they will be added as one-line brackets. This style frequently is used with an indent + of 2 spaces. +

    +
    +
    int Foo(bool isBar)
    +{   if (isBar)
    +    {   bar();
    +        return 1; }
    +    else
    +        return 0; }
    +
    +
    +

    +   +

    +

    + --style=lisp / --style=python / -A12
    + Lisp style uses attached opening and closing brackets. Opening brackets are attached at the + end of the statement. The closing bracket is attached to the last line in the block. The style implies keep-one-line-statements + but NOT keep-one-line-blocks. This style does not support one-line brackets. If add-one-line-brackets is used + they will be added as multiple-line brackets. +

    +
    +
    int Foo(bool isBar) {
    +    if (isBar) {
    +        bar()
    +        return 1; }
    +    else
    +        return 0; }
    +
    +
    +

    +   +

    +
    + + + +

    Tab Options

    + +

    + The following examples show whitespace characters. A space is indicated with a . (dot), a tab + is indicated by a > (greater than). +

    +

    + default indent
    + If no indentation option is set, the default option of 4 spaces will be used (e.g. -s4 + --indent=spaces=4 + ). +

    +
    +

    + with default values: +

    +
    void Foo() {
    +....if (isBar1
    +............&& isBar2)    // indent of this line can be changed with min-conditional-indent
    +........bar();
    +}
    +
    +
    +

    +   +

    +

    + --indent=spaces / --indent=spaces=# / -s#
    + Indent using # spaces per indent (e.g. -s3 --indent=spaces=3 + ). # must be between 2 and 20. Not specifying # will result in a default of + 4 spaces per indent. +

    +
    +

    + with indent=spaces=3 +

    +
    void Foo() {
    +...if (isBar1
    +.........&& isBar2)    // indent of this line can be changed with min-conditional-indent
    +......bar();
    +}
    +
    +
    +

    +   +

    +

    + --indent=tab / --indent=tab=# / -t / -t#
    + Indent using tabs for indentation, and spaces for continuation line alignment. This ensures that + the code is displayed correctly  regardless of the viewer’s tab size. Treat each indent as # spaces + (e.g. -t6 / --indent=tab=6). + # must be between 2 and 20. If no # is set, treats indents as 4 spaces. +

    +
    +

    + with indent=tab: +

    +
    void Foo() {
    +>   if (isBar1
    +>   ........&& isBar2)    // indent of this line can be changed with min-conditional-indent
    +>   >   bar();
    +}
    +
    +

    + with style=linux, indent=tab=8: +

    +
    void Foo()
    +{
    +>       if (isBar1
    +>       ....&& isBar2)    // indent of this line can NOT be changed with style=linux
    +>       >       bar();
    +}
    +
    +
    +

    +   +

    +

    + --indent=force-tab / --indent=force-tab=# / -T / -T#
    + Indent using all tab characters, if possible. If a continuation line is not an even number of + tabs, spaces will be added at the end. Treat each tab as # spaces (e.g. -T6 + / --indent=force-tab=6). # must be between + 2 and 20. If no # is set, treats tabs as 4 spaces. +

    +
    +

    + with indent=force-tab: +

    +
    void Foo() {
    +>   if (isBar1
    +>   >   >   && isBar2)    // indent of this line can be changed with min-conditional-indent
    +>   >   bar();
    +}
    +
    +
    +

    +   +

    +

    + --indent=force-tab-x / --indent=force-tab-x=# / -xT / -xT# +
    + This force-tab option allows the tab length to be set to a length that is different than the indent length. This + may cause the indentation to be a mix of both tabs and spaces. Tabs will be used to indent, if + possible. If a tab indent cannot be used, spaces will be used instead. +

    +

    + This option sets the tab length. Treat each tab as # spaces (e.g. -xT6 + / --indent=force-tab-x=6). # must be between + 2 and 20. If no # is set, treats tabs as 8 spaces. To change the indent length from the default + of 4 spaces the option "indent=force-tab" must also be used. +

    +
    +

    + with indent=force-tab-x (default tab length of 8 and default indent length of 4): +

    +
    void Foo() {
    +....if (isBar1
    +>       ....&& isBar2)    // indent of this line can be changed with min-conditional-indent
    +>       bar();
    +}
    +
    +
    +

    +   +

    +
    + + + +

    Bracket Modify Options

    + +

    + --attach-namespaces / -xn
    + Attach brackets to a namespace statement. This is done regardless of the bracket style being used. +

    +
    +

    + the bracket is always attached to a namespace statement: +

    +
    namespace FooName {
    +...
    +}
    +
    +
    +

    +   +

    +

    + --attach-classes / -xc
    + Attach brackets to a class statement. This is done regardless of the bracket style being used. +

    +
    +

    + the bracket is always attached to a class statement: +

    +
    class FooClass {
    +...
    +};
    +
    +
    +

    +   +

    +

    + --attach-inlines / -xl
    + Attach brackets to class and struct inline function definitions. This is not done for run-in type brackets (Horstmann + and Pico styles). This option is effective for C++ files only. +

    +
    +

    + all brackets are always attached to class and struct inline function definitions: +

    +
    class FooClass
    +{
    +    void Foo() {
    +    ...
    +    }
    +};
    +
    +
    +

    +   +

    +

    + --attach-extern-c / -xk
    + Attach brackets to a bracketed extern "C" statement. This is done regardless of the bracket style being used. + This option is effective for C++ files only. +

    +

    + An extern "C" statement that is part of a function definition is formatted according to the requested bracket + style. Bracketed extern "C" statements are unaffected by the bracket style and this option is the only way to + change them. +

    +
    +

    + this option attaches brackets to a bracketed extern "C" statement: +

    +
    #ifdef __cplusplus
    +extern "C" {
    +#endif
    +
    +

    + but function definitions are formatted according to the requested bracket style: +

    +
    extern "C" EXPORT void STDCALL Foo()
    +{}
    +
    +
    +

    +   +

    +
    + + + +

    Indentation Options

    + +

    + --indent-classes / -C
    + Indent 'class' and 'struct' blocks so that the entire block is indented. The struct + blocks are indented only if an access modifier, 'public:', 'protected:' or 'private:', + is declared somewhere in the struct. This option is effective for C++ files only. +

    +
    +
    class Foo
    +{
    +public:
    +    Foo();
    +    virtual ~Foo();
    +};
    +
    +

    + becomes: +

    +
    class Foo
    +{
    +    public:
    +        Foo();
    +        virtual ~Foo();
    +};
    +
    +
    +

    +   +

    +

    + --indent-modifiers / -xG
    + Indent 'class' and 'struct' access modifiers, 'public:', 'protected:' + and 'private:', one half indent. The rest of the class is not indented. This option is effective + for C++ files only. If used with indent‑classes this option will be ignored. +

    +
    +
    class Foo
    +{
    +public:
    +    Foo();
    +    virtual ~Foo();
    +};
    +
    +

    + becomes: +

    +
    class Foo
    +{
    +  public:
    +    Foo();
    +    virtual ~Foo();
    +};
    +
    +
    +

    +   +

    +

    + --indent-switches / -S
    + Indent 'switch' blocks so that the 'case X:' statements are indented in the switch + block. The entire case block is indented. +

    +
    +
    switch (foo)
    +{
    +case 1:
    +    a += 1;
    +    break;
    +
    +case 2:
    +{
    +    a += 2;
    +    break;
    +}
    +}
    +
    +

    + becomes: +

    +
    switch (foo)
    +{
    +    case 1:
    +        a += 1;
    +        break;
    +
    +    case 2:
    +    {
    +        a += 2;
    +        break;
    +    }
    +}
    +
    +
    +

    +   +

    +

    + --indent-cases / -K
    + Indent 'case X:' blocks from the 'case X:' headers. Case statements not enclosed in + blocks are NOT indented. +

    +
    +
    switch (foo)
    +{
    +    case 1:
    +        a += 1;
    +        break;
    +
    +    case 2:
    +    {
    +        a += 2;
    +        break;
    +    }
    +}
    +
    +

    + becomes: +

    +
    switch (foo)
    +{
    +    case 1:
    +        a += 1;
    +        break;
    +
    +    case 2:
    +        {
    +            a += 2;
    +            break;
    +        }
    +}
    +
    +
    +

    +   +

    +

    + --indent-namespaces / -N
    + Add extra indentation to namespace blocks. This option has no effect on Java files. +

    +
    +
    namespace foospace
    +{
    +class Foo
    +{
    +    public:
    +        Foo();
    +        virtual ~Foo();
    +};
    +}
    +
    +

    + becomes: +

    +
    namespace foospace
    +{
    +    class Foo
    +    {
    +        public:
    +            Foo();
    +            virtual ~Foo();
    +    };
    +}
    +
    +
    +

    +   +

    +

    + --indent-labels / -L
    + Add extra indentation to labels so they appear 1 indent less than the current indentation, rather than being flushed + to the left (the default). +

    +
    +
    void Foo() {
    +    while (isFoo) {
    +        if (isFoo)
    +            goto error;
    +        ...
    +error:
    +        ...
    +        }
    +}
    +
    +

    + becomes (with indented 'error:'): +

    +
    void Foo() {
    +    while (isFoo) {
    +        if (isFoo)
    +            goto error;
    +        ... 
    +    error:
    +        ...
    +        }
    +}
    +
    +
    +

    +   +

    + +

    + --indent-preproc-block / -xW
    + Indent preprocessor blocks at bracket level zero, and immediately within a namespace. There are restrictions on + what will be indented. Blocks within methods, classes, arrays, etc, will not be indented. Blocks containing brackets + or multi-line define statements will not be indented. Without this option the preprocessor block is not indented. +

    +
    +
    #ifdef _WIN32
    +#include <windows.h>
    +#ifndef NO_EXPORT
    +#define EXPORT
    +#endif
    +#endif
    +
    +

    + becomes: +

    +
    #ifdef _WIN32
    +    #include <windows.h>
    +    #ifndef NO_EXPORT
    +        #define EXPORT
    +    #endif
    +#endif
    +
    +
    +

    +   +

    +

    + --indent-preproc-define / -w
    + Indent multi-line preprocessor definitions ending with a backslash. Should be used with --convert-tabs for proper + results. Does a pretty good job, but cannot perform miracles in obfuscated preprocessor definitions. Without this + option the preprocessor statements remain unchanged. +

    +
    +
    #define Is_Bar(arg,a,b) \
    +(Is_Foo((arg), (a)) \
    +|| Is_Foo((arg), (b)))
    +
    +

    + becomes: +

    +
    #define Is_Bar(arg,a,b) \
    +    (Is_Foo((arg), (a)) \
    +     || Is_Foo((arg), (b)))
    +
    +
    +

    +   +

    +

    + --indent-preproc-cond / -xw
    + Indent preprocessor conditional statements to the same level as the source code. +

    +
    +
            isFoo = true;
    +#ifdef UNICODE
    +        text = wideBuff;
    +#else
    +        text = buff;
    +#endif
    +

    + becomes: +

    +
            isFoo = true;
    +        #ifdef UNICODE
    +        text = wideBuff;
    +        #else
    +        text = buff;
    +        #endif
    +
    +
    +

    +   +

    +

    + --indent-col1-comments / -Y
    + Indent C++ comments beginning in column one. By default C++ comments beginning in column one are + assumed to be commented‑out code and not indented. This option will allow the comments to be indented with + the code. +

    +
    +
    void Foo()\n"
    +{
    +// comment
    +    if (isFoo)
    +        bar();
    +}
    +
    +

    + becomes: +

    +
    void Foo()\n"
    +{
    +    // comment
    +    if (isFoo)
    +        bar();
    +}
    +
    +
    +

    +   +

    +

    + --min-conditional-indent=# / -m#
    + Set the minimal indent that is added when a header is built of multiple lines. This indent helps to easily separate + the header from the command statements that follow. The value for # + indicates a number of indents and is a minimum value. The indent may be greater to align with + the data on the previous line.
    + The valid values are:
    + 0 - no minimal indent. The lines will be aligned with the paren on the preceding line.
    + 1 - indent at least one additional indent.
    + 2 - indent at least two additional indents.
    + 3 - indent at least one-half an additional indent. This is intended for large indents (e.g. 8).
    + The default value is 2, two additional indents. +

    +
    +
    // default setting makes this non-bracketed code clear
    +if (a < b
    +        || c > d)
    +    foo++;
    +
    +// but creates an exaggerated indent in this bracketed code
    +if (a < b
    +        || c > d)
    +{
    +    foo++;
    +}
    +
    +

    + becomes (when setting --min-conditional-indent=0): +

    +
    // setting makes this non-bracketed code less clear
    +if (a < b
    +    || c > d)
    +    foo++;
    +
    +// but makes this bracketed code clearer
    +if (a < b
    +    || c > d)
    +{
    +    foo++;
    +}
    +
    +
    +

    +   +

    +

    + --max-instatement-indent=# / -M#
    + Set the  maximum of # spaces to indent a continuation line. The + # indicates a number of columns and must not be less than 40 nor greater than 120. + If no value is set, the default value of 40 will be + used. This option will prevent continuation lines from + extending too far to the right. Setting a larger value will allow the code to be extended further to the right. +

    +
    +
    fooArray[] = { red,
    +         green,
    +         blue };
    +
    +fooFunction(barArg1,
    +         barArg2,
    +         barArg3);
    +
    +

    + becomes (with larger value): +

    +
    fooArray[] = { red,
    +               green,
    +               blue };
    +
    +fooFunction(barArg1,
    +            barArg2,
    +            barArg3);
    +
    +
    +

    +   +

    +
    + + + +

    Padding Options

    + +

    + --break-blocks / -f
    + Pad empty lines around header blocks (e.g. 'if', 'for', 'while'...). +

    +
    +
    isFoo = true;
    +if (isFoo) {
    +    bar();
    +} else {
    +    anotherBar();
    +}
    +isBar = false;
    +
    +

    + becomes: +

    +
    isFoo = true;
    +
    +if (isFoo) {
    +    bar();
    +} else {
    +    anotherBar();
    +}
    +
    +isBar = false;
    +
    +
    +

    +   +

    +

    + --break-blocks=all / -F
    + Pad empty lines around header blocks (e.g. 'if', 'for', 'while'...). Treat + closing header blocks (e.g. 'else', 'catch') as stand-alone blocks. +

    +
    +
    isFoo = true;
    +if (isFoo) {
    +    bar();
    +} else {
    +    anotherBar();
    +}
    +isBar = false;
    +
    +

    + becomes: +

    +
    isFoo = true;
    +
    +if (isFoo) {
    +    bar();
    +
    +} else {
    +    anotherBar();
    +}
    +
    +isBar = false;
    +
    +
    +

    +   +

    +

    + --pad-oper / -p
    + Insert space padding around operators. This will also pad commas. Any end of line comments will remain in the + original column, if possible. Note that there is no option to unpad. Once padded, they stay padded. +

    +
    +
    if (foo==2)
    +    a=bar((b-c)*a,d--);
    +
    +

    + becomes: +

    +
    if (foo == 2)
    +    a = bar((b - c) * a, d--);
    +
    +
    +

    +   +

    +

    + --pad-comma / -xg
    + Insert space padding after commas. This is not needed if pad-oper is used. Any end of line comments will remain + in the original column, if possible. Note that there is no option to unpad. Once padded, they stay padded. +

    +
    +
    if (isFoo(a,b)
    +    bar(a,b);
    +
    +

    + becomes: +

    +
    if (isFoo(a, b)
    +    bar(a, b);
    +
    +
    +

    +   +

    +

    + --pad-paren / -P +
    + Insert space padding around parenthesis on both the outside and the inside. + Any end of line comments will remain in the original column, if possible. +

    +
    +
    if (isFoo((a+2), b))
    +    bar(a, b);
    +
    +

    + becomes: +

    +
    if ( isFoo ( ( a+2 ), b ) )
    +    bar ( a, b );
    +
    +
    +

    +   +

    +

    + --pad-paren-out / -d +
    + Insert space padding around parenthesis on the outside only. Parentheses that are empty will + not be padded. Any end of line comments will remain in the original column, if possible. This can be used with + unpad-paren below to remove unwanted spaces. +

    +
    +
    if (isFoo((a+2), b))
    +    bar(a, b);
    +
    +

    + becomes: +

    +
    if (isFoo ( (a+2), b) )
    +    bar (a, b);
    +
    +
    +

    +   +

    +

    + --pad-first-paren-out / -xd +
    + Insert space padding around the first parenthesis in a series on the outside + only. Parentheses that are empty will not be padded. Any end of line comments will remain in the original column, + if possible. This can be used with unpad-paren below to remove unwanted spaces. If used with pad‑paren or + pad‑paren‑out, this option will be ignored. If used with pad‑paren‑in, the result will + be the same as pad‑paren. +

    +
    +
    if (isFoo((a+2), b))
    +    bar(a, b);
    +
    +

    + becomes: +

    +
    if (isFoo ((a+2), b))
    +    bar (a, b);
    +
    +
    +

    +   +

    +

    + --pad-paren-in / -D +
    + Insert space padding around parenthesis on the inside only. Any end of line comments will remain + in the original column, if possible. This can be used with unpad-paren below to remove unwanted spaces. +

    +
    +
    if (isFoo((a+2), b))
    +    bar(a, b);
    +
    +

    + becomes: +

    +
    if ( isFoo( ( a+2 ), b ) )
    +    bar( a, b );
    +
    +
    +

    +   +

    +

    + --pad-header / -H +
    + Insert space padding between a header (e.g. 'if', 'for', 'while'...) + and the following paren. Any end of line comments will remain in the original column, if possible. This can + be used with unpad-paren to remove unwanted spaces. +

    +
    +
    if(isFoo((a+2), b))
    +    bar(a, b);
    +

    + becomes: +

    +
    if (isFoo((a+2), b))
    +    bar(a, b);
    +
    +
    +

    +   +

    +

    + --unpad-paren / -U +
    + Remove extra space padding around parenthesis on the inside and outside. Any end of line comments will remain + in the original column, if possible. This option can be used in combination with the paren padding options pad‑paren, + pad‑paren‑out, pad‑paren‑in, and pad‑header + above. Only padding that has not been requested by other options will be removed. +

    +

    + For example, if a source has parens padded on both the inside and outside, and you want inside only. You need + to use unpad-paren to remove the outside padding, and pad‑paren‑in to retain + the inside padding. Using only pad‑paren‑in would not remove the outside padding. +

    +
    +
    if ( isFoo( ( a+2 ), b ) )
    +    bar ( a, b );
    +
    +

    + becomes (with no padding option requested): +

    +
    if(isFoo((a+2), b))
    +    bar(a, b);
    +
    +
    +

    +   +

    +

    + --delete-empty-lines / -xe
    + Delete empty lines within a function or method. Empty lines outside of functions or methods are NOT deleted. If + used with break-blocks or break-blocks=all it will delete all lines EXCEPT the lines added by the break-blocks + options. +

    +
    +
    void Foo()
    +{
    +
    +    foo1 = 1;
    +
    +    foo2 = 2;
    +
    +}
    +
    +

    + becomes: +

    +
    void Foo()
    +{
    +    foo1 = 1;
    +    foo2 = 2;
    +}
    +
    +
    +

    +   +

    +

    + --fill-empty-lines / -E
    + Fill empty lines with the white space of the previous line. +

    +

    +   +

    +

    + --align-pointer=type   / -k1
    + --align-pointer=middle / -k2
    + --align-pointer=name   / -k3 +

    + Attach a pointer or reference operator (*, &, or ^) to either the variable type (left) or variable name (right), + or place it between the type and name (middle). The spacing between the type and name will be preserved, if possible. + This option is for C/C++, C++/CLI, and C# files. To format references separately use the following align-reference + option. +

    +
    +
    char* foo1;
    +char & foo2;
    +String ^s1;
    +

    + becomes (with align-pointer=type): +

    +
    char* foo1;
    +char& foo2;
    +String^ s1;
    +
    +
    +
    char* foo1;
    +char & foo2;
    +String ^s1;
    +

    + becomes (with align-pointer=middle): +

    +
    char * foo1;
    +char & foo2;
    +String ^ s1;
    +
    +
    +
    char* foo1;
    +char & foo2;
    +String ^s1;
    +

    + becomes (with align-pointer=name): +

    +
    char *foo1;
    +char &foo2;
    +String ^s1;
    +
    +

    +   +

    +

    + --align-reference=none   / -W0
    + --align-reference=type   / -W1
    + --align-reference=middle / -W2
    + --align-reference=name   / -W3 +

    + This option will align references separate from pointers. Pointers are not changed by this option. If pointers + and references are to be aligned the same, use the previous align-pointer option. The option align-reference=none + will not change the reference alignment. The other options are the same as for align-pointer. This option is for + C/C++, C++/CLI, and C# files. +

    +
    +
    char &foo1;
    +

    + becomes (with align-reference=type): +

    +
    char& foo1;
    +
    +
    +
    char& foo2;
    +

    + becomes (with align-reference=middle): +

    +
    char & foo2;
    +
    +
    +
    char& foo3;
    +

    + becomes (with align-reference=name): +

    +
    char &foo3;
    +
    +

    +   +

    +
    + + + +

    Formatting Options

    + +

    + --break-closing-brackets / -y +
    + When used with --style=java, --style=kr, --style=stroustrup, --style=linux, or --style=1tbs, this breaks closing + headers (e.g. 'else', 'catch', ...) from their immediately preceding closing brackets. Closing header brackets + are always broken with the other styles. +

    +
    +
    void Foo(bool isFoo) {
    +    if (isFoo) {
    +        bar();
    +    } else {
    +        anotherBar();
    +    }
    +}
    +
    +

    + becomes (a broken 'else'): +

    +
    void Foo(bool isFoo) {
    +    if (isFoo) {
    +        bar();
    +    }
    +    else {
    +        anotherBar();
    +    }
    +}
    +
    +
    +

    +   +

    +

    + --break-elseifs / -e
    + Break "else if" header combinations into separate lines. This option has no effect if keep-one-line-statements + is used, the "else if" statements will remain as they are. +

    +

    + If this option is NOT used, "else if" header combinations will be placed on a single line. +

    +
    +
    if (isFoo) {
    +    bar();
    +}
    +else if (isFoo1()) {
    +    bar1();
    +}
    +else if (isFoo2()) {
    +    bar2;
    +}
    +
    +

    + becomes: +

    +
    if (isFoo) {
    +    bar();
    +}
    +else
    +    if (isFoo1()) {
    +        bar1();
    +    }
    +    else
    +        if (isFoo2()) {
    +            bar2();
    +        }
    +
    +
    +

    +   +

    +

    + --add-brackets / -j +
    + Add brackets to unbracketed one line conditional statements (e.g. 'if', 'for', + 'while'...). The statement must be on a single line. The brackets will be added according to + the currently requested predefined style or bracket type. If no style or bracket type is requested the brackets + will be attached. If --add-one-line-brackets is also used the result will be one line brackets. +

    +
    +
    if (isFoo)
    +    isFoo = false;
    +
    +

    + becomes: +

    +
    if (isFoo) {
    +    isFoo = false;
    +}
    +
    +
    +

    +   +

    +

    + --add-one-line-brackets / -J +
    + Add one line brackets to unbracketed one line conditional statements (e.g. 'if', 'for', + 'while'...). The statement must be on a single line. The option implies --keep-one-line-blocks and + will not break the one line blocks. +

    +
    +
    if (isFoo)
    +    isFoo = false;
    +
    +

    + becomes: +

    +
    if (isFoo)
    +    { isFoo = false; }
    +
    +
    +

    +   +

    +

    + --remove-brackets / -xj
    + Remove brackets from conditional statements (e.g. 'if', 'for', 'while'...). + The statement must be a single statement on a single line. If --add-brackets or --add-one-line-brackets is also + used the result will be to add brackets. Brackets will not be removed from "One True Brace Style", --style=1tbs. +

    +
    +
    if (isFoo)
    +{
    +    isFoo = false;
    +}
    +

    + becomes: +

    +
    if (isFoo)
    +    isFoo = false;
    +
    +
    +

    +   +

    +

    + --keep-one-line-blocks / -O +
    + Don't break one-line blocks. +

    +
    +
    if (isFoo)
    +{ isFoo = false; cout << isFoo << endl; }
    +
    +

    + remains unchanged. +

    +
    +

    +   +

    +

    + --keep-one-line-statements / -o +
    + Don't break complex statements and multiple statements residing on a single line. +

    +
    +
    if (isFoo)
    +{
    +    isFoo = false; cout << isFoo << endl;
    +}
    +
    +

    + remains unchanged. +

    +
    if (isFoo) DoBar();
    +
    +

    + remains unchanged. +

    +
    +

    +   +

    +

    + --convert-tabs / -c
    + Converts tabs into spaces in the non-indentation part of the + line. The number of spaces inserted will maintain the spacing of the tab. The current setting for spaces per tab + is used. It may not produce the expected results if convert-tabs is used when changing spaces per tab. Tabs are + not replaced in quotes. +

    +

    +   +

    +

    + --close-templates / -xy
    + Closes whitespace in the angle brackets of template definitions. Closing the ending angle brackets is now allowed + by the C++11 standard. Be sure your compiler supports this before making the changes. +

    +
    +
    Stack< int,List< int > > stack1;
    +

    + becomes: +

    +
    Stack<int,List<int>> stack1;
    +
    +

    +   +

    +

    + --remove-comment-prefix / -xp
    + Remove the preceding '*' in a multi-line comment that begins a line. A trailing '*', if present, is also removed. + Text that is less than one indent is indented to one indent. Text greater than one indent is not changed. Multi-line + comments that begin a line but without the preceding '*' are indented to one indent for consistency. This can + slightly modify the indentation of commented out blocks of code. Lines containing all '*' are left unchanged. + Extra spacing is removed from the comment close '*/'. +

    +
    +
    /*
    + * comment line 1
    + * comment line 2
    + */
    +

    + becomes: +

    +
    /*
    +    comment line 1
    +    comment line 2
    +*/
    +
    +

    +   +

    +

    + --max-code-length=#   / -xC# +
    + --break-after-logical / -xL

    + The option max‑code‑length will break a line if the code exceeds # + characters. The valid values are 50 thru 200. Lines without logical conditionals will break on a logical conditional + (||, &&, ...), comma, paren, semicolon, or space. +

    +

    + Some code will not be broken, such as comments, quotes, and arrays. If used with keep‑one‑line‑blocks + or add-one-line-brackets the blocks will NOT be broken. If used with keep‑one‑line‑statements + the statements will be broken at a semicolon if the line goes over the maximum length. If there is no available + break point within the max code length, the line will be broken at the first available break point after the max + code length. +

    +

    + By default logical conditionals will be placed first on the new line. The option break‑after‑logical + will cause the logical conditionals to be placed last on the previous line. This option has no effect without + max‑code‑length. +

    +
    +
    if (thisVariable1 == thatVariable1 || thisVariable2 == thatVariable2 || thisVariable3 == thatVariable3)
    +    bar();
    +

    + becomes: +

    +
    if (thisVariable1 == thatVariable1
    +        || thisVariable2 == thatVariable2
    +        || thisVariable3 == thatVariable3)
    +    bar();
    +

    + becomes (with break‑after‑logical): +

    +
    if (thisVariable1 == thatVariable1 ||
    +        thisVariable2 == thatVariable2 ||
    +        thisVariable3 == thatVariable3)
    +    bar();
    +
    +

    +   +

    +

    + --mode=c
    + --mode=cs
    + --mode=java
    + Indent a C type, C#, or Java file. C type files are C, C++, C++/CLI, and Objective-C. The option is usually + set from the file extension for each file. You can override the setting with this entry. It will be used for all + files regardless of the file extension. It allows the formatter to identify language specific syntax such as C++ + classes, templates, and keywords. +

    +

    +   +

    +
    + + + +

    Objective‑C Options

    + +

    + These options are effective for Objective‑C files only. The paren padding options will still apply to the + Objective-C method prefix and return type unless overridden by the following options. +

    +

    + Because of the longer indents sometimes needed for Objective‑C, the option "max-instatement-indent" may + need to be increased. If you are not getting the paren and square bracket alignment you want try increasing this + value. The option is described in the "Indentation Options" section. +

    +

    + --pad-method-prefix / -xQ
    + Insert space padding after the '-' or '+' Objective‑C method prefix. This will add exactly + one space. Any additional spaces will be deleted. This option takes precedence over the pad-paren options. +

    +
    +
    -(void)foo1;
    ++(void)foo2;
    +

    + becomes: +

    +
    - (void)foo1;
    ++ (void)foo2;
    +
    +

    +   +

    +

    + --unpad-method-prefix / -xR
    + Remove all space padding after the '-' or '+' Objective‑C method prefix.  + This option will be ignored if used with pad‑method‑prefix. It takes precedence over the pad-paren + options. +

    +
    +
    - (void)foo1;
    ++ (void)foo2;
    +

    + becomes: +

    +
    -(void)foo1;
    ++(void)foo2;
    +
    +

    +   +

    +

    + --pad-return-type / -xq
    + Insert space padding after the Objective‑C return type. This will add exactly one + space. Any additional spaces will be deleted. This option takes precedence over the pad-paren options. +

    +
    +
    -(void)foo1;
    ++(void)foo2;
    +

    + becomes: +

    +
    -(void) foo1;
    ++(void) foo2;
    +
    +

    +   +

    +

    + --unpad-return-type / -xr
    + Remove all space padding after the Objective‑C return type. This option + will be ignored if used with pad‑return‑type. It takes precedence over the pad-paren options. +

    +
    +
    -(void) foo1;
    ++(void) foo2;
    +

    + becomes: +

    +
    -(void)foo1;
    ++(void)foo2;
    +
    +

    +   +

    +

    + --align-method-colon / -xM
    + Align the colons in Objective‑C method declarations. +

    +
    +
    -(void)deleteKey:(id)key
    +    atIndex:(int)index
    +    ofNode:(Node*)node;
    +

    + becomes: +

    +
    -(void)deleteKey:(id)key
    +         atIndex:(int)index
    +          ofNode:(Node*)node;
    +
    +

    +   +

    +

    + --pad-method-colon=none   / -xP0
    + --pad-method-colon=all    / -xP1
    + --pad-method-colon=after  / -xP2
    + --pad-method-colon=before / -xP3 +

    + Add or remove space padding before or after the colons in an Objective‑C method call. These options will + pad exactly one space. Any additional spaces will be deleted. +

    +
    +

    + with pad-method-colon=none: +

    +
    [node insertKey:key];
    +

    + with pad-method-colon=all: +

    +
    [node insertKey : key];
    +

    + with pad-method-colon=after: +

    +
    [node insertKey: key];
    +

    + with pad-method-colon=before: +

    +
    [node insertKey :key];
    +
    +

    +   +

    +
    + + + +

    Other Options

    + +

    + These are non-formatting options available for the command-line. They can also be included in an options file. +

    + +

    + --suffix=####
    + Append the suffix #### instead of '.orig' to original file name (e.g. --suffix=.bak). + If this is to be a file extension, the dot '.' must be included. Otherwise the suffix will be appended to the + current file extension. +

    +

    + --suffix=none / -n
    + Do not retain a backup of the original file. The original file is purged after it is formatted. +

    +

    + --recursive / -r / -R
    + For each directory in the command line, process all subdirectories recursively. When using the recursive option + the file name statement should contain a wildcard. Linux users should place the file path and name in double quotes + so the shell will not resolve the wildcards (e.g. "$HOME/src/*.cpp"). Windows users should place the file path + and name in double quotes if the path or name contains spaces. +

    +

    + --dry-run
    + Perform a trial run with no changes made to the files. The report will be output as usual. +

    +

    + --exclude=####
    + Specify a file or sub directory #### to be excluded from processing. +

    +

    + Excludes are matched from the end of the file path. An exclude option of "templates" will exclude ALL directories + named "templates". An exclude option of "cpp/templates" will exclude ALL "cpp/templates" directories. You may + proceed backwards in the directory tree to exclude only the required directories. +

    +

    + Specific files may be excluded in the same manner. An exclude option of "default.cpp" will exclude ALL files named + "default.cpp". An exclude option of "python/default.cpp" will exclude ALL files named "default.cpp" contained + in a "python" subdirectory. You may proceed backwards in the directory tree to exclude only the required files. +

    +

    + Wildcards are NOT allowed. There may be more than one exclude statement. The file path and name may be placed + in double quotes (e.g. ‑‑exclude="foo bar.cpp"). +

    +

    + --ignore-exclude-errors / -i
    + Allow processing to continue if there are errors in the "exclude=###" options.
    + This option lets the excludes for several projects be entered in a single option file. This option may be placed + in the same option file as the excludes. It will display the unmatched excludes. The following option will not + display the unmatched excludes. +

    +

    + --ignore-exclude-errors-x / -xi
    + Allow processing to continue if there are errors in the "exclude=###" options.
    + This option lets the excludes for several projects be entered in a single option file. This option may be placed + in the same option file as the excludes. It will NOT display the unmatched excludes. The preceding option will + display the unmatched excludes.
    +

    +

    + --errors-to-stdout / -X
    + Print errors to standard-output rather than to standard-error.
    + This option should be helpful for systems/shells that do not have a separate output to standard-error, such as + in Windows95. +

    +

    + --preserve-date / -Z
    + Preserve the original file's date and time modified. The time modified will be changed a few micro seconds to + force the changed files to compile. This option is not effective if redirection is used to rename the input file. +

    +

    + --verbose / -v
    + Verbose display mode. Display optional information, such as release number, date, and statistical data. +

    +

    + --formatted / -Q
    + Formatted files display mode. Display only the files that have been formatted. Do not display files that + are unchanged. +

    +

    + --quiet / -q
    + Quiet display mode. Suppress all output except error messages. +

    +

    + --lineend=windows / -z1
    + --lineend=linux   / -z2
    + --lineend=macold  / -z3 +

    + Force use of the specified line end style. Valid options are windows (CRLF), linux (LF), and macold (CR). MacOld + style is the format for Mac OS 9 and earlier. OS X uses the Linux style. If one of these options + is not used the line ends will be determined automatically from the input file. +

    +

    + When redirection is used on Windows the output will always have Windows line ends. This option + will be ignored. +

    +

    +   +

    +
    + + + +

    Command Line Only

    + +

    These options are available for the command-line only. They are NOT available in an options file.

    +

    + --options=####
    + Specify an options file #### to read and use. It must contain a file path for the file. This will allow the file + name to be changed from astylerc or .astylerc. +

    +

    + --options=none
    + Disable the default options file. Only the command-line parameters will be used. +

    +

    + --ascii / -I
    + The displayed output will be ascii characters only. The text will be displayed in English and numbers will not + be formatted. The short option must be by itself, it cannot be concatenated with other options. +

    +

    + --version / -V
    + Print version number and quit. The short option must be by itself, it cannot be concatenated with other options. +

    +

    + --help / -h / -?
    + Print a help message and quit. The short option must be by itself, it cannot be concatenated with other options. +

    +

    + --html / -!
    + Open the HTML help + file "astyle.html" in the default browser and quit. The short option must be by itself, it + cannot be concatenated with other options. The documentation must be installed in the standard install path (/usr/share/doc/astyle/html + for Linux or %PROGRAMFILES%\AStyle\doc for Windows). If installed to a different path use html=###. +

    +

    + --html=####
    + Open a HTML help file in the default browser using the file path #### and quit. A HTML file other than "astyle.help" + may be specified. The path may include a directory path and a file name, or a file name only (e.g. html=install.html). + If only a file name is used it is assumed to be in the standard install path (/usr/share/doc/astyle/html + for Linux or %PROGRAMFILES%\AStyle\doc for Windows). In both cases the file name must include the html extension. + File paths containing spaces must be enclosed in quotes. +

    +

    + On Linux the HTML file is opened using the script "xdg-open" from the install package "xdg-utils". This should + be installed + by default on most distributions. +

    +

    + Any HTML file can be opened by this option. The files you are likely to need are astyle.html (the default), install.html, + and index.html. +

    +

    +   +

    +
    + +

    + + + +

    + +

    +   +

    +

    +   +

    + + + + + diff --git a/External/Tools/AStyle/doc/favicon.ico b/External/Tools/AStyle/doc/favicon.ico new file mode 100644 index 0000000000..0de820b57d Binary files /dev/null and b/External/Tools/AStyle/doc/favicon.ico differ diff --git a/External/Tools/AStyle/doc/index.html b/External/Tools/AStyle/doc/index.html new file mode 100644 index 0000000000..039976240b --- /dev/null +++ b/External/Tools/AStyle/doc/index.html @@ -0,0 +1,230 @@ + + + + + + Artistic Style - Index + + + + + + + + + + +

    Artistic Style 2.06

    + +

    + A Free, Fast, and Small Automatic Formatter
    + for C, C++, C++/CLI, Objective‑C, C#, and Java Source Code +

    + +
    + + + + + + + + + + + + + +
    + Project Page:http://astyle.sourceforge.net/
    + SourceForge:http://sourceforge.net/projects/astyle/
    +
    + +

    +   +

    +

    + Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C++/CLI, Objective‑C, + C# and Java programming languages. +

    +

    + When indenting source code, we as programmers have a tendency to use both spaces and tab characters to create + the wanted indentation. Moreover, some editors by default insert spaces instead of tabs when pressing the tab + key, and other editors (Emacs for example) have the ability to "pretty up" lines by automatically setting up the + white space before the code on the line, possibly inserting spaces in a code that up to now used only tabs for + indentation. +

    +

    + Since the NUMBER of space characters showed on screen for each tab character in the source code changes between + editors (unless the user sets up the number to his liking...), one of the standard problems programmers are facing + when moving from one editor to another is that code containing both spaces and tabs that was up to now perfectly + indented, suddenly becomes a mess to look at when changing to another editor. Even if you as a programmer take + care to ONLY use spaces or tabs, looking at other people's source code can still be problematic. +

    +

    + To address this problem, Artistic Style was created – a filter written in C++ that automatically re-indents + and re-formats C / C++ / Objective‑C / C++/CLI / C# / Java source files. It can be used from a command line, + or it can be incorporated as classes in another C++ program. +

    + +

    + Documentation +

    + +

    + There is complete documentation for using Artistic Style. The documentation needed to install and run Artistic + Style is included in the distribution package. It does not need an Internet connection. +

    + +

    + News and Release Notes +

    + +

    + These contain information on the changes in the current release. The News contains information on major changes + and how they might affect the use of Artistic Style. The Release Notes contains a list of all changes made to + the program. Information on old releases is also listed. +

    + +

    + Download +

    + +

    + The latest release can be downloaded from the SourceForge file releases page. A link to the "latest version" near + the top of the page will download the correct package for your platform. Or you can select the appropriate + package from the "astyle" release folders. The Windows package contains a compiled binary. Other platforms + will need to compile the source code. Makefiles are included for the most popular compilers. Follow the install + instructions for the appropriate platform as described in the "Install" documentation. +

    + +

    + Subversion +

    + +

    + The latest development files can be checked out from the Artistic Style repository using Subversion. +

    + +

    + Install +

    + +

    + This containd information on compiling and installing Artistic Style. The Windows platform comes with a precompiled + executable. Other platforms must compile the project. Follow the instructions for the appropriate platform (Linux, + Mac, or Windows). +

    + +

    + License +

    + +

    + Artistic Style may be used and distributed under the + MIT license. The MIT is a permiissive license with a minimum of restrictions on software use. It is compatable + with the GNU General Public License (GPL) and most other licenses. You can use Artistic Style in free or commercial + software without charge. Projects that use Artistic Style do NOT have to make the Artistic Style source code available. +

    + +

    + Scripts +

    + +

    + This page contains scripts to support the Artistic Style program. They are in various script languages and work + on different platforms. It includes scripts to clean the directories of backup files created by Artistic Style. +

    + +

    + Links +

    + +

    + There are several applications that use Artistic Style as contributed software. It is either embedded in the application + or called as a command line program. The applications include Graphical User Interfaces to view the effect of + formatting on the source code, development environments for various platforms, and other software. There + are also links to style information and various style guides.

    + +

    + Developer Information +

    + +

    + Artistic Style has compile options for creating a shared library (DLL) or static library for use with a Graphical + User Interface (GUI). With the Java Development Kit (JDK) installed it can be compiled as a Java Native Interface + (JNI) and called from a Java program. The Developer Information documents the calling procedure and has example + programs for C++, C++/CLI, Objective‑C, Java, C#, and Python. +

    + +

    Bug Reports, Change Requests, Update Notifications

    + +

    + Bug reports and change requests should be submitted to the bug tracker + page. You must be logged in to SourceForge to submit a report. If possible include an example + that shows the problem. It does not need to be functional code. Note that code copied and pasted into the bug + report will not be indented after the data is submitted. You must indicate the indentation when + you submit the request (e.g. replace leading spaces with periods). +

    +

    + The best way to subscribe to update notifications is using the + SourceForge Project Page "Update Notifications" button. The option to subscribe is also displayed + during a file download. The subscription options for a project can be modified using the "Me", "Account + Settings" option on the SourceForge bar at the top of the page. Select the "Subscriptions" tab + and check the notifications you want. Usually only the "files" option is needed. +

    +

    + You can also subscribe to change notifications using an RSS feed. There is an RSS symbol on the + SourceForge Files page. Or you can use the "subscriptions" + or "add content" option available in your RSS reader. +

    +

    + To contact the project by email use the address jimp03@email.com. +

    + +

    Maintainers

    + +

    + Artistic Style is maintained and updated by Jim Pattee. The original author + was Tal Davidson, Israel. +

    + +

    Acknowledgments

    + +

    + Thanks to Jim Watson, Fred Shwartz, W. Nathaniel Mills III, Danny Deschenes, Andre Houde, + Richard Bullington, Paul-Michael Agapow, Daryn Adler, Dieter Bayer, Sam Cooler, Jim Duff, + Emilio Guijarro, Jens Krinke, Eran Ifrah, Travis Robinson, Max Horn, Ettl Martin, + Mario Gleichmann, J P Nurmi, Colin D Bennett, Christian Stimming, MrTact, Wim Rosseel, + Matthew Woehlke, Chris Schwarz, Chang Jiang, Arseny Solokha, Milian Wolff, Johannes Martin, + Arne F?rlie, Marvin Humphrey, J, Christopher Sean Morrison, Keith OHara, louis6g, Evmenov Georgiy, + beta100100, Ruzzz, Peter A. Bigot, HyungKi Jeong, David Faure, Carl Moore, Mofi, Travis Vitek + for their patches and contributions to Artistic Style. +

    +

    + Thanks to SourceForge for giving Artistic Style its home. +

    +

    + Thanks to all the dedicated beta-testers and bug notifiers! +

    + + + +

    +   +

    + +

    + + + +

    + +

    +   +

    + + + + + diff --git a/External/Tools/AStyle/doc/install.html b/External/Tools/AStyle/doc/install.html new file mode 100644 index 0000000000..199cd2d2b3 --- /dev/null +++ b/External/Tools/AStyle/doc/install.html @@ -0,0 +1,477 @@ + + + + + + Artistic Style - Install Information + + + + + + + + +

    + Artistic Style Install Information +

    + +

    +   +

    + +

    + Contents +

    + +

    + Artistic Style Versions +

    +

    + Linux Version +

    +

    + GCC Compiler +

    +

    + Clang Compiler +

    +

    + Intel Compiler +

    +

    + Other Makefile Targets +

    +

    + Mac OS X Version +

    +

    + Xcode +

    +

    + Makefile +

    +

    + Windows Version +

    +

    + Precompiled Executable +

    +

    + Visual C++ Compiler +

    +

    + Other Compilers +

    +

    + Compiler Options +

    + +

    + Artistic Style Versions +

    + +

    + astyle_x.x_linux.tar.gz is the Linux version of Artistic Style. It contains the source code, + documentation, and makefiles. The Linux Version compile instructions below give information for compiling the + source code. +

    +

    + astyle_x.x_macosx.tar.gz is the Mac OS X version of Artistic Style. It contains the source code, + documentation, Xcode project files, and a makefile. The Mac OS X Version compile instructions below give information + for compiling the source code. +

    +

    + astyle_x.x_windows.zip is the Windows version of Artistic Style. It contains the source code, + documentation, Visual C project files, and an executable. The Windows Version compile instructions below give + information for compiling the source code. +

    +

    + Only one platform is supported in each distribution package. If you use Artistic Style on more than one platform + you will need to download packages for each platform. The main difference in platforms is the build directories + and the line endings. Most compilers and development packages will accept any type of line ending. The source + code and documentation are the same for all distributions. +

    + +

    + Linux Version +

    + +

    + GCC Compiler +

    + +

    + To compile using the GCC compiler you must have GCC (3.1 or better) installed. +

    +

    + The build has no autoconf dependency. To build the Artistic Style configurations use the makefile located in the + astyle/build/gcc directory. The executables will be in the astyle/build/gcc/bin directory. To build the command + line configuration enter the following: +

    +
    cd astyle/build/gcc
    make +
    +

    + To build the other astyle configurations you can enter the file name or a symbolic name. Entering "make astyle" + or "make release" will build the command line configuration. Following are the symbolic names and file names (in + parens) of the various configurations: +

    +
      +
    • release builds the Artistic Style command line program (astyle). This is the default option. +
    • +
    • shared builds the Artistic Style program as a shared library (libastyle.so).
    • +
    • static builds the Artistic Style program as a static library (libastyle.a).
    • +
    • debug builds the Artistic Style command line program with debugging information (astyled). +
    • +
    • shareddebug builds the Artistic Style program as a shared library with debugging information + (libastyled.so). +
    • +
    • staticdebug builds the Artistic Style program as a static library with debugging information + (libastyled.a). +
    • +
    • all builds all the above configurations. +

      + The following Java shared library builds are separate from the above. They include a Java Native Interface (JNI) + and require that the Java Development Kit (JDK) be installed. The environment variable JAVA_HOME should be defined. + It defines the install directory for the JDK. The makefile also has default install directories for Java 5 and + 6. If the compile cannot find the file jni.h, either set the variable or change the value in the makefile. +

      +
    • +
    • java builds the Artistic Style program as a shared library which includes the JNI (libastylej.so). +
    • +
    • javadebug builds the Artistic Style program as a shared library which includes the JNI and debugging + information + (libastylejd.so).
    • +
    • javaall builds all the above java configurations.
    • +
    +

    + More than one configuration can be built at the same time. For example, to build all the release configurations + enter: +

    +
    cd astyle/build/gcc
    make release shared static
    +

    + The Other Makefile Targets section contains additional target options. +

    + +

    + Clang Compiler +

    + +

    + Clang has a static analyzer that finds potential bugs in C/C++ and Objective-C programs. It can be run as a standalone + tool from the command-line, and runs in tandem with a build. There is a script file, analyze.sh, that will run + the analysis on Artistic Style. +

    +

    + The build has no autoconf dependency. To build the Artistic Style configurations use the makefile located in the + astyle/build/clang directory. The executables will be in the astyle/build/clang/bin directory. To build the command + line configuration enter the following: +

    +
    cd astyle/build/clang
    make +
    +

    + To build the other astyle configurations you can enter the file name or a symbolic name. The configurations for + Clang are the same as for the GCC compiler. More than one configuration can be + built at the same time. For example, to build all the release configurations enter: +

    +
    cd astyle/build/clang
    make release shared static +
    +

    + The Other Makefile Targets section contains additional target options. +

    + +

    + Intel Compiler +

    + +

    + These procedures and the makefile are for recent versions of the compiler. They may not work for earlier versions. + Instructions for your compiler are in the compiler documentation file "get_started_lc.htm". +

    +

    + To compile the source there are environment variables that must be set by running the compiler environment script + compilervars.sh (or compilervars.csh) with an argument that specifies the target architecture. If this has not + been done already enter: "source  <install-dir>/bin/compilervars.sh <arg>", + where <install-dir> is the directory where the compiler is installed and <arg> is ia32 + or intel64. If this is not done "make" will display an error message "*** The compiler environment + variables are not set." On an Intel x64 platform installed in the default directory the instruction would be +

    +
    source /opt/intel/composer_xe_2015/bin/compilervars.sh intel64
    +

    + The build has no autoconf dependency. To build the Artistic Style configurations use the makefile located in the + astyle/build/intel directory. The output executables will be in the astyle/build/intel/bin directory. To build + the command line configuration enter the following: +

    +
    cd astyle/build/intel
    make
    +

    + To build the other astyle configurations you can enter the file name or a symbolic name. The configuration names + for Intel are the same as for the GCC compiler. More than one configuration can be + built at the same time. For example, to build the entire debug configurations enter: +

    +
    cd astyle/build/intel
    make debug shareddebug staticdebug
    +

    + The Other Makefile Targets section contains additional target options. +

    + +

    + Other Makefile Targets +

    + +

    + The following makefile targets are available for GCC, Clang, Intel, and Mac. +

    + +
    + clean +
    + +

    + Removes the object and executable files for all configurations. +

    +

    + To remove the files for all configurations: +

    +
    make clean
    +
    + +
    + cleanobj +
    + +

    + Removes the object files for all configurations. The executables will not be removed. +

    +

    + To remove only the object files for all configurations: +

    +
    make cleanobj
    +
    + +
    + install +
    + +

    + Installs the + astyle executable and documentation files. The default is /usr/bin for the executable and /usr/share/doc/astyle + for the documentation. You must have the appropriate permissions to use install. +

    +

    + To install the astyle to the default directories: +

    +
    sudo make install
    +
    +

    + To install astyle to a different bin directory set a value for the macro $(prefix). For example to install the + executable to a user's home directory (/home/user/bin): +

    +
    sudo make prefix=$HOME install
    +
    + +
    + uninstall +
    + +

    + Uninstalls the executable and documentation. You must have the appropriate permissions to use uninstall. +

    +

    + To uninstall astyle from the default directories: +

    +
    sudo make uninstall
    +
    +

    + To uninstall the files from a different directory set a value for the macro $(prefix). For example to uninstall + the files from a user's home directory (/home/user): +

    +
     sudo make prefix=$HOME uninstall
    +
    +

    + NOTE: The uninstall option will NOT remove the .astylerc files from the users home directories. The files must + be removed individually for each user. +

    + +

    + Mac OS X Version +

    + +

    Xcode

    + +

    + Artistic Style workspace and project files for the Xcode development environment are available in the "build/xcode" + directory. A workspace can be used to build a single project or all the projects. The project files have Debug + and Release configurations. The following projects are available. +

    +
      +
    • AStyle builds the Artistic Style command line program (astyle).
    • +
    • AStyleA builds the Artistic Style program as a Static Library (libastyle.a). This can be statically + linked with an executable.
    • +
    • AStyleDylib builds the Artistic Style program as a Dynamic Library (libastyle.dylib). It can + be used with C/C++, Objective C, C#, and Python programs.
    • +
    • AStyleJava builds the Artistic Style program as a Dynamic Library (libastylej.dylib) that can + be called from a Java program. The Java Development (JDK) is required for the project to compile. The Project + Properties must have an include path to the JDK include directory. The output dylib can also be called from a + C++ or C# program.
    • +
    + +
    install
    + +

    + Only the astyle executable is installed. The library project installs are sent to UninstalledProjects in + the Build directory. The following instructions are for the astyle executable and documentation files. The default + install directory is /usr/bin for the executable and /usr/share/doc/astyle + for the documentation. You must have the appropriate permissions to use install. + If sudo is not used for the install an error will occur during the build. +

    +

    + To install the astyle executable to the default directory: +

    +
    cd astyle/build/xcode
    +sudo xcodebuild install -project AStyle.xcodeproj
    +
    +

    + A script is used to install the documentation + from the same directory. +

    +
    sudo bash install.sh
    +
    + +
    + uninstall +
    + +

    + Uninstalls the executable and documentation. You must have the appropriate permissions to use uninstall. +

    +

    + A script is used to uninstall astyle and the documentation: +

    +
    sudo bash uninstall.sh
    +
    +

    + NOTE: The uninstall option will NOT remove the .astylerc files from the users home directories. The files must + be removed individually for each user. +

    + +

    Makefile

    + +

    + The Artistic Style makefile compile uses the OS X "Command Line Tools". If you have Xcode 4.3 or newer + the command line tools, such as "make", are NOT installed by default. They must be downloaded and installed + separately. Once everything is successfully installed you should see "make" and other command line developer + tools in /usr/bin. +

    +

    + The build has no autoconf dependency. To build the Artistic Style configurations use the makefile located in the + astyle/build/mac directory. The executables will be in the astyle/build/mac/bin directory. To build the command + line configuration enter the following: +

    +
    cd astyle/build/mac
    make +
    +

    + To build the other astyle configurations you can enter the file name or a symbolic name. The configurations for + Mac are the same as for the Linux GCC compiler. More than one configuration can be + built at the same time. For example, to build all the release configurations enter: +

    +
    cd astyle/build/mac
    make release shared static +
    +

    + The Other Makefile Targets section contains additional target options. +

    + +

    + Windows Version +

    + +

    + Precompiled Executable +

    + +

    + In addition to the source files, the Windows distribution package contains an Artistic Style Win32 executable + (AStyle.exe). If you prefer to compile the executable yourself follow the following instructions. +

    + +

    + Visual C++ Compiler +

    + +

    + There are + solution and project files for + several versions of the Visual C compiler. Open an Artistic Style solution + file in the appropriate "build" directory. All projects have Debug, Release and Static configurations. + Debug file output will be in the "debug" directory. Release file output will be in the "bin" + directory. Static file output will be in the "binstatic" directory. The following solution files are available. +

    +
      +
    • All AStyle ll AStyle builds the release and the debug configurations for all the following. +
    • +
    • AStyle builds the Artistic Style command line program (AStyle.exe). This project has an extra + "Static" option. It is the same as the "Release" build except that it is linked with a static runtime library. + This is needed if the executable is to be run on a system without Visual Studio installed. The builds for this + configuration are placed in a separate "binstatic" directory.
    • +
    • AStyleDll builds the Artistic Style program as a Dynamic Link Library (AStyle.dll). This will + also build an exports library and a static library for linking the dll.
    • +
    • AStyleJava builds the Artistic Style program as a Dynamic Link Library (AStylej.dll) that can + be called from a Java program. The Java Development (JDK) is required for the project to compile. The Project + Properties must have an include path to the JDK include and include/win32 directories. This is set in "Project + > Properties > C/C++ > General > Additional Include Directories". The default setting + is for the JDK to be installed in the default directory, but it may not be the most current release. The output + DLL can also be called from a C++ or C# program.
    • +
    • AStyleLib builds the Artistic Style program as a Static Library (libAStyle.lib). This can be + statically linked to a calling program.
    • +
    + +

    + Other Compilers +

    + +

    + To use other compilers a project file must be built using a development environment. +

    +
      +
    • Create a project using the compiler's development environment.
    • +
    • Add to the project all the .cpp and .h files in the "src" directory.
    • +
    • The Compiler Options section discusses the compiler options to use.
    • +
    • Compile.
    • +
    + +

    + Compiler Options +

    + +

    + No macro definitions are required to compile the executable. To compile as a static or shared (dynamic) library + define the macro ASTYLE_LIB. To compile a Java shared (dynamic) library define the macro ASTYLE_JNI. The + option ASTYLE_NO_EXPORTS is sometimes needed for static libraries to prevent compiler error and warning + messages. Use the appropriate compiler and linker options to compile the static or shared library. Add debug + options to compile the debug versions. +

    +

    + Artistic Style is a small program and it is best to optimize for speed. The debug configurations are not usually + optimized. To optimize for speed in the release configurations use the macro NDEBUG to remove asserts. If + necessary, use an option to activate the C++11 standards (--std=c++0x on GCC and MinGW). Use an + option that allows inline function expansion. Runtime Type Information (RTTI) is NOT needed. Exceptions are + NOT + used. Use whole program optimization if your compiler supports it. There may be other options you can use depending + on the compiler. +

    +

    +   +

    + +

    + + + +

    + +

    +   +

    + + + + + diff --git a/External/Tools/AStyle/doc/links.html b/External/Tools/AStyle/doc/links.html new file mode 100644 index 0000000000..8cb15036bb --- /dev/null +++ b/External/Tools/AStyle/doc/links.html @@ -0,0 +1,254 @@ + + + + + + Artistic Style - Links + + + + + + + + +

    Artistic Style Links

    + +

    +   +

    + +

    Programs Using AStyle

    + +

    + The following development environments use Artistic Style as a contributed add-on. It is either embedded in the + application or called as a command line program. +

    +

    + Dev-Cpp + is a new and improved fork of the original Bloodshed Dev-C++. It is a free IDE for programming in C and C++. It + is bundled with, and uses, the MinGW or TDM-GCC port of the GCC as its compiler. It is currently Windows only. + The Artictic Style interface includes a live Preview window. +

    +

    + CodeBender is a + browser-based IDE for programming and uploading to Arduino boards. It includes built-in libraries for code sharing. + Artistic Style is used as the code formatter. +

    +

    + CodeBlocks is + a multi-platform, open source, C++ development environment based on wxWidgets. It has support for multiple compilers and plug-ins for wxWidgets development. +

    +

    + CodeLite is an + open source, free, cross platform IDE specialized in C, C++, PHP and JavaScript. It supports all major + compilers. Threr is support for wxWidgets and includes a class + generator and a unit test program generator. Code completion is based on Ctags. +

    +

    + KDevelop is a + multi-platform, integrated development environment for building + KDE applications. It supports many programming languages and can be used to develop applications other + than KDE. +

    +

    + Monkey Studio + is a cross platform IDE written in C++/Qt. Its primary goal was to be a Qt only IDE, but it evolved into a way to support Qt development and any kind + of project. +

    +

    + Qt + Creator is a cross-platform integrated development environment tailored to the needs of Qt developers. An Artistic Style Plugin is available as an integrated plugin. + It can format source code within the editor or format an entire project. There is a help display available to + show the effect of each option. +

    +

    + SciTE + is a Scintilla based source code editor. Originally built to demonstrate Scintilla, it has grown to be a generally useful editor with facilities for building + and running programs. It is currently available for Windows, Linux, and Mac OS X operating systems. The Linux + and Mac versions are based on GTK+. +

    +

    + Sublime Text + is a is a sophisticated text editor for code, markup and prose that includes Artistic Style as a plug-in. Nearly + everything in Sublime Text is customizable with simple JSON files.The plug-ins are Python based. + Sublime Text is available for OS X, Windows and Linux. +

    +

    + tIDE is + a full featured open source + Java integrated development environment. It is a small, powerful, quick, efficient, easy and open framework + to create 100% Java applications. +

    +

    + UltraEdit is a commercial programmer's text editor for Microsoft + Windows, Linux and Mac OS X. It can be evaluated for free for 30 days. Artistic Style is included in the Tools + Toolbar. It includes an options dialog. The number of indent spaces is passed to Artistic Style is based on + the Indent Spaces value defined under Word Wrap/Tab Settings in Configuration based on the file extension of + the active file. +

    +

    + Visual Studio + is an integrated development environment from Microsoft. + AStyle Extension is an extension written in C# and formats C/C++ + and C# + source code using Artistic Style. It can be installed in Visual Studio (except Express editions) + using the "Tools" > "Extensions and Updates" menu. Search the "Online" entry + for "astyle". The source code is available on GitHub. +

    + +

    Graphical User Interfaces

    + +

    + Artistic Style is a command line program and, as such, does not give you a chance to review the effect of different + options before formatting the source code. The following Graphical User Interface program will allow you to review + the changes before the code is updated. They allow you to select the options you want without actually updating + the source. +

    +

    + Artistic Style for Windows + is an Artistic Style GUI program for Windows. It uses an unmodified Artistic Style program in a Windows GUI. It + will work under Linux using WINE. Everything done in the editor is undo-able, including formatting of the entire + document. Documents can be reviewed and reformatted using different options. It can be executed from most development + environments and will open the currently selected document.
    + Here are the links for downloading version 2.05.1 of + + AStyleWin and + + AStyleWinD. The website has been having problems and I have not been able to update it. + The downloads contain Windows executables and documentation. +

    +

    + Universal Indent + Gui is a cross platform GUI that supports several code formatters. The main feature is a live + preview to show how the selected formatting options affect the source code. This allows review and testing of + the various options before formatting a file. It can be used with a sample file or with your actual source code. + It is a good way to try out the options from various indentation programs. This program is not always kept up + to date. Be sure to check the AStyle release before relying on the results. +

    + +

    Other Programs

    + +

    + These programs were mentioned in previous versions of the News + or other documentation. They are included here for reference. +

    +

    + Google Test + and Google Mock + are frameworks for writing C++ tests on a variety of platforms. Based on the xUnit architecture it supports automatic + test discovery, a rich set of assertions, user-defined assertions, death tests, fatal and non-fatal failures, + value- and type-parameterized tests, various options for running the tests, and XML test report generation. Google + Mock is a library for writing and using C++ mock methods. +

    +

    + Highlight converts + source code to formatted text with syntax highlighting. Output is in several formats including HTML. It supports + over 160 programming languages and includes 80 color themes. Highlight is used for the examples in the "Developer + Information" section. +

    +

    + Python Tools for Visual Studio + is a free, open source plug-in that turns Visual Studio into a Python IDE. It can be switched between Python versions + or different Python interpreters. It uses the Visual Studio integrated debugger that enables you to set break + points, step through functions, change the current statement, inspect local variables, and perform other operations + while debugging. +

    + +

    Information

    + +

    The following links contain general information on coding and coding styles.

    + +

    + Indent Style + at Wikipedia discusses the common indent styles used in programming. The basic criteria for most Artistic Style + predefined styles were taken from this discussion. +

    +

    + Programming + style at Wikipedia is a set of rules or guidelines used when writing the source code for a computer + program. It is often claimed that following a particular programming style will help programmers to read and understand + source code conforming to the style, and help to avoid introducing errors. +

    +

    + Programming with Style + describes popular indent styles. Its purpose is to provide enough information to help people decide on which indent + style to use. +

    + +

    Style Guides

    + +

    + Chromium + style guide generally follows the Google Style Guide but has extensions beyond the Google style + guide. There is interesting information on common C++ Dos and Don'ts. +

    +

    + Google style + guides have Google's standards for several programming languages along with a python program + to verify the style and an Emacs script for using the style. +

    + +

    + Kdelibs + Coding Style describes the recommended coding style for kdelibs. It follows the Qt 4 coding style, + with one main difference. +

    +

    + LLVM coding standards + describes a few coding standards that are being used in the LLVM source tree. +

    +

    + + Mozilla’s style guide explains the basic styles and patterns that are used in the + Mozilla codebase. +

    +

    + Qt Coding Style + is an overview of the coding conventions used when writing Qt code. +

    + +

    Other Links

    + +

    + These links were mentioned in previous versions of the News. They are included here for reference. +

    +

    + Install Instructions for .NET Framework SDK + are instructions for adding x64 platforms to Visual Studio Express 2010. Express editions after 2010 have the + x64 platforms already installed. Visual Studio 2010 is the last edition that will work on Windows XP (platform + toolset v100). Visual Studio 2012 (platform toolset v110) and higher contains dependencies on Windows API functions + that exist only on Windows Vista, Windows 7, and Windows 8. This means that applications built with Visual Studio + 2012 and higher would fail to load and execute on Windows XP. +

    +

    + Survey + General Information and Survey Options are the results of an Artistic Style survey + from May 2011. There is a commentary on the survey in the May 2011 News under the heading "Survey Results". +

    +

    +   +

    + +

    + + +

    + +

    +   +

    + + + + diff --git a/External/Tools/AStyle/doc/news.html b/External/Tools/AStyle/doc/news.html new file mode 100644 index 0000000000..e914b87b50 --- /dev/null +++ b/External/Tools/AStyle/doc/news.html @@ -0,0 +1,553 @@ + + + + + + Artistic Style - News + + + + + + + + +

    Artistic Style News

    + +

    +   +

    + +

    Artistic Style 2.06  (Pending)

    + +

    + A new option, "pad‑comma", will add a space following a comma. The option "pad‑oper" + has not been changed and will also add a space following a comma. +

    +

    + All spaces before a comma are now removed. Use the disable block comments if there are arrays with vertical alignment + where this is not wanted. +

    +

    + New Objective‑C options "pad‑return‑type" and "unpad‑return‑type" will + add or remove space padding after the Objective‑C return type. It is described in the "Objective‑C" + section of the documentation. +

    +

    + The Objective‑C align‑method‑colon has been changed for method declarations and definitions. + For multi‑line arguments when the first keyword is shorter than the others the colons are aligned on the + longest line instead of the first line. The alignment includes room for the indentation. This aligns all colons + after the first line for a better appaerance. Arguments that do not have a short keyword in the first line will + remain the same. This style conforms to the Google Objective‑C Style Guide. +

    +

    + The Objective‑C align‑method‑colon option is now applied to Objective‑C method calls in + addition to method declarations and definitions. +

    +

    + Processing for c++14 single‑quote digit separators has been added. +

    + +

    + New + Software License +

    + +

    + The Artisic Style software license has changed. It is now under the MIT license. This is a permissive license + which can be used in proprietory software and does NOT require modified Artistic Style source code be made available. + It is compatable with the GNU General Public License (GPL) and most other software licenses. The change was made + to remove restrictions on using the software and to make it available for any project that wants to use it. +

    +

    + If there are problems with the license change send an email to Artistic Style and its use will be approved on + a individual basis. +

    + +

    + Assignment Operator Alignment +

    + +

    + Visual Studio 2013 and 2015 have an Edit option "Align Assignments" that will align assignment operators + across multiple lines. There is also an extension named "Code alignment" that will align the code on + other items as well. Other development environments may have something similar. These will selectively align the + data and allow for customization of the format. +

    +

    + These options and extensions can be used with Artistic Style. If you choose to do this, the space padding will + be maintained and the alignment will be preserved. +

    + +

    + Microsoft Clang Compiler +

    + + +

    + The Microsoft Clang Compiler is available with Visual Studio 2015 Update 1. It is usually + used for Android or iOS + support but the CodeGen support can be used with Windows. The Clang Update 1 version is a preview and is + incomplete, but can be used if you want. It will require modification of the Visual Studio 2015 project files. +

    +

    + The Clang compiler can be installed from the Visual Studio 2015 install program by selecting the "Clang + with Microsoft CodeGen" option. If Visual Studio 2015 Update 1 is already installed, Clang can be installed + by selecting File > New > Project > Visual C++ > Cross Platform, select CodeGen support option. +

    +

    + To use Clang open a Visual Studio 2015 AStyle Solution. Make the following change to all configurations: +

    +
      +
    • General > Platform Toolset, select "Clang 3.7 with Microsoft CodeGen".
    • +
    +

    + Make sure to hit "Apply" before editing other properties to let the project system load the corresponding + toolset definition. +

    +

    + The Update 1 preview release does not provide any support for automatic migration of values between Visual Studio + 2015 and Clang 3.7. The invalid properties must be fixed manually manually. These may change with subsequent Visual + Studio updates. +

    +

    + The properties that need changing in Visual Studio Update 1 are: +

    +
      +
    • C/C++ > General > Debug Information Format, select "Full Debug Information (DWARF2)" for Debug + or "None" for Release.
    • +
    • C/C++ > General > Warning Level, select "Enable All Warnings".
    • +
    • C/C++ > Code Generation > Enable C++ Exceptions, select "Yes" for Debug or "No" for + Release.
    • +
    • C/C++ > Precompiled Headers > Precompiled Header, select "Not Using Precompiled Headers".
    • +
    +

    + The following is needed if you are building an executable instead of a static or dynamic library: +

    +
      +
    • C/C++ > Preprocessor > Preprocessor Definitions, add " __STDC__=0". To remove the warnings + this causes, C/C++ > Command Line > Additional Options, enter "-Wno-macro-redefined". +
    • +
    +

    + The project should now compile and run. +

    + +

    + Windows XP +

    + +

    + The executable in the Windows distribution package is now compiled with a Visual Studio version that will no + longer work on Windows XP. Beginning with Visual Studio 2012, auto‑vectorization tries to make loops run + faster by automatically vectorizing the code. Auto‑vectorization is on by default, there are no compiler + switches, #pragmas, or hints. But it uses SSE instructions not available in Windows XP. Microsoft ended + support and updates for XP on April 8, 2014, and the usage share percentage continues to decrease. +

    +

    + If you are using XP, Artistic Style should be compiled on the XP machine. Compiling on XP with any + compiler should produce an XP executable. +

    +

    + To compile on a non‑XP machine for use on  XP, using a compiler other than Visaul Studio should always + produce an XP executable. Using Vusual Studio 2010 or earlier should always produce an XP executable. If + you are using Visual Studio 2012, 2013, or 2015 on a non‑XP machine, do the following for the Artistic Style + configuration you want to use: +

    +
      +
    • "Windows XP Support for C++" must be installed. It is available as an option in the Visual Studio install + and can be installed as a modification to the original install.
    • +
    • In the Artistic Style Properties, change General > Platform Toolset, to "Windows XP".
    • +
    • In the Artistic Style Properties, change C/C++ > Preprocessor > Preprocessor Definitions to include + _USING_V110_SDK71_.
    • +
    • Change other Properties if you want, such as Output Directory or Target Name.
    • +
    • Compile. The output should be executable on Windows XP. It will also execute on the later versions of Windows. +
    • +
    + +

    + SourceForge +

    + +

    + Recently, SourceForge began adding potentially unwanted programs (PUPs), also known as "crapware", to + software installers of certain applications. Some large projects have already left the site. Artistic Style does + not use installer downloads and therefore was not affected by this. Downloads are in the form + of .zip or .tar.gz files. However, having the PUPs available on the host site affects the integrity of every + application that uses the site. +

    +

    + What is even more troubling is that the uBlock browser add‑on, and all of its spin‑offs, is now blocking + access to the site by default. Even though Artistic Style has never used PUPs, the site is prevented from loading. + The block can be easily removed, but may discourage some people from using the software. are. +

    +

    + SourceForge is apparently taking steps to correct the situation. If this is not resolved fairly soon, Artistic + Style will be relocated to another site. If this happens, I will give notification of the new site at the + current SourceForge address. + ess. +

    + +

    + Acknowledgments +

    + +

    + Thanks to David Faure for their contributions. +

    + +

    Artistic Style 2.05  (November 2014)

    + +

    + Release 2.05.1 (December 2014) is a maintenance release and no new features were added. A list of changes is in + the Release Notes. The following information is for the original 2.05 release. +

    + +

    + A new bracket style option, "style=vtk", has been added. It uses indented brackets, like Whitesmith, + except opening brackets for classes, functions, and methods are not indented. A complete description of the VTK + style is available at the "Visualization Toolkit" website (http://www.vtk.org/). +

    +

    + A new preprocessor indent option "indent-preproc-block" will indent preprocessor block statements one additional + indent. The block must be top-level, or included within a namespace, and there are restrictions on what can be + indented. + The option is described in the "Indentation Options" section of the documentation. +

    +

    + A new option, "dry-run", will run Artistic Style without updating the files. The report will be output as usual. +

    +

    + Formatting of source code may now be disabled for portions of a program by embedding special comment tags in the + program. These are described in a new "Disable Formatting" section of the documentation. They work the + same as in other formatters. There are tags to disable formatting for a block of code, and a tag to disable formatting + of a single line. This should allow any custom formatting to be retained. +

    +

    + The product version number has been added to the filename of shared library (DLL) compiles. This will allow multiple + versions of a shared library on the same system without conflicts. +

    +

    + An attribute '__attribute__ ((visibility ("default")))' has been added to exported functions + on Linux shared libraries. This allows the option "-fvisibility=hidden" to be used on dynamic library + compiles. According to the GNU documentation, "Using this feature can very substantially improve linking + and load times of shared object libraries, produce more optimized code, provide near-perfect API export and prevent + symbol clashes. It is strongly recommended that you use this in any shared objects you distribute." +

    +

    + Improvements have been made in the formatting of C++11 uniform initializers (enclosed by brackets). The opening + bracket will not be space padded unless it is padded initially. The closing bracket will not be broken from the + final line unless it is broken initially. And the known problems with uniform initializers in class constructors + have been fixed. +

    +

    + The Windows compiler definition ASTYLE_NO_VCX (no Visual Studio exports) has been changed to ASTYLE_NO_EXPORTS. + It is sometimes needed for static libraries on other compilers to prevent error and warning messages. +

    +

    + Qt and Boost macros foreach, forever, Q_FOREACH, and Q_FOREVER will now be recognized as headers. +

    +

    + The main documentation for Artistic Style is in HTML format. Until now there has not been a way to display it + from the astyle console program. A new option, "html" or "-!" will display the help documentation in the default + browser. This documentation is more complete than the astyle "help" option. It includes examples, and has an index + for easier navigation. Since astyle is typically run from a script this should allow an easy way to access the + documentation. The option is available only from the command line. +

    +

    + The new "html" option assumes the documentation is installed in the standard install path. This is /usr/share/doc/astyle/html + for Linux and the path %programfiles%\AStyle\doc for Windows. If it is installed to a different directory, use + the variation "html=<actual_install_path>astyle.html. This option can also be used to open other HTML files. + More information is in the "Command Line Only" section of the documentation. +

    +

    + The "html" option on Linux uses the script "xdg-open" from the install package "xdg-utils" to find the default + browser. This should be available on most systems.  If it is not available on your system you can file a + bug report requesting a change. It would be helpful if you could determine how it is done before filing the report. + You can also file a bug report if the documentation is not installed to the above "default" directories. The HTML + documentation takes quite a bit of effort to maintain and I would like to make it easily available. +

    +

    + The "help" option has been changed to send the output to stdout instead of stderr. This will allow piping and + redirection of the output. A common way to use the option on Linux is "astyle --help | less", which + will page the display. The "version" option has also been changed to stdout. +

    +

    + A shared library error handler argument has been changed from "char*" to "const char*". In + some cases this may cause compile errors in a user program until the references have been changed. +

    +

    + The "Indent Style" topic on Wikipedia states that the "ANSI" style refers to K&R style brackets + and not Allman style as used by Artistic Style. The option "style=ansi" is therefore being depreciated and will + be removed in a future release. Use one of the other long options instead (style=allman, style=bsd, or style=break). +

    +

    + Some of the documentation has been removed from the distribution package. It still contains all files needed to + install and run Artistic Style. The included files can be used without an Internet connection. +

    +

    + There are now build files available for Xcode on Mac. The makefile is still available for those who want it. Both + now use the LLVM Clang compiler. There has been a + change to the makefile debug locations to make them similar to Xcode. The "Install Instructions" have + been updated for both. +

    +

    + The Python Example in the Developer Information now supports Iron Python. The + programming instructions are sometimes different since the ctypes module works differently. The example script + documents the differences. If you use Python Tools for Visual Studio, it now installs in the Express editions + (beginning with release 2.1). Node.js can also be installed in Visual Studio Express. +

    +

    + The executable in the Windows distribution package is now compiled with Visual Studio 2013 and will no longer + work on XP. If you are using XP, Artistic Style will need to be recompiled on the XP machine. +

    +

    + A new Visual + Studio Community Edition has been released. It is free, combines all of the Express editions into a single + development environment, and allows the addition of Visual Studio extensions. There is an + + AStyle Extension available for installation. It has a graphic interface, adds menu entries, and can be + used from within Visual Studio. To install it search the "Extensions and Updates", "Online" + entry for "astyle". +

    +

    + Thanks to Peter A. Bigot, HyungKi Jeong, David Faure, and Carl Moore for their contributions. +

    + +

    Artistic Style 2.04  (November 2013)

    + +

    + With a new Artistic Style release some unchanged source files will be formatted because of changes to Artistic + Style. You may want to format your source before making program changes in order to bring it up to date. +

    +

    + A new programming language, Objective‑C, has been added to Artistic Style. Four new options, "align‑method‑colon", + "pad‑method‑colon=", "pad‑method‑prefix", and "unpad‑method‑prefix" have been + added to format the methods. The options are described in a new "Objective‑C" section in the documentation. + These new options affect only Objective‑C source code. They have no effect on the other programming languages. +

    +

    + Because of the longer continuation indents sometimes needed for Objective‑C, the option "max-instatement-indent" + may need to be increased. If you are not getting the paren and square bracket alignment you want, try increasing + this value. The default minimum is 40 and the maximum is 120. +

    +

    + A new bracket style option, "style=google", has been added. It uses attached brackets and indents the class access + modifiers one-half indent.  A complete description of the Google style is available at the google‑styleguide + website (https://code.google.com/p/google-styleguide/). The website has standards for several programming languages + along with a python program to verify the style and an emacs script for using the style. +

    +

    + A new indent option "indent-modifiers" will indent class access modifiers (public, protected, or 'private) one-half + indent. The rest of the class is not indented. It is described in the "Indentation Options" section of the documentation. +

    +

    + Four new bracket modify options, "attach-namespaces", "attach-classes", "attach-inlines", and "attach-extern-c", + can be used to modify your selected bracket style. They are described in a new "Bracket Modify Options" section + of the documentation. +

    +

    + A new option, "remove-brackets", will remove brackets from conditional statements. The statement must be a single + statement on a single line. It is described in the "Formatting Options" section of the documentation. +

    +

    + A new option, "indent-preproc-cond", will indent preprocessor conditional statements (#if #elif, #else, #endif). + It is described in the "Indentation Options" section of the documentation. The option "indent-preprocessor" has + been deprecated and will be removed in a future release. Use "indent-preproc-define" instead. The processing of + preprocessor #define statements has not changed. +

    +

    + A new option, "remove-comment-prefix", will remove a leading '*' from multi-line comments. It is described in + the "Formatting Options" section of the documentation. With the syntax coloring of modern editors a leading '*' + for comment lines is not as useful as it once was. The current trend is toward code that is easier to maintain. + The idea is that a style that is hard to maintain will discourage modification and updating. The converted style + should retain most of the formatting within the comment and result in a comment that is easier to maintain. For + consistency the option also indents multi-line comments that are not preceded by the '*'. This may slightly modify + the indentation of any commented-out code. +

    +

    + The option "pad-first-paren-out" was fixed to not pad if the following paren is empty. This makes the option consistent + with "pad-paren-out". To fix empty parens that have been padded run with the option "unpad-paren" in addition + to "pad-first-paren-out". This needs to be done only once. +

    +

    + Processing of C++11 raw string literals has been added. +

    +

    + The compiler definition ASTYLE_NO_VCX (no Visual Studio exports) has been changed to ASTYLE_NO_EXPORTS and can + be used with any Windows compiler. The Clang compiler needs this option to avoid errors on dynamic libraries. + It removes the "__declspec(dllexport)" + definition from exported functions. Linux compilers do not use this. +

    +

    + A new shared object (DLL) entry point, AStyleMainUtf16, has been added for processing C# UTF-16 strings. C# does + not have built in functions for converting the UTF-16 strings to UTF-8. This entry point will accept UTF-16 strings, + format the source code, and return UTF-16 strings. The error handling function and version number still use UTF-8 + strings. The C# example program in the "Developer Information" shows the new calling procedure. Changes from the + previous release are marked in the example. +

    +

    + C# strings are UTF-16 on both Windows and Linux. C# does not use the UTF-32 wchar_t strings on Linux. Qt also + uses UTF-16 on both Windows and Linux, but has built in UTF-8 conversion functions. Qt strings can be converted + to UTF-8 by Qt, or the new entry point can be used. There may be other "managed code" applications on Linux that + use UTF-16. +

    +

    + The "Links" page has two new sections for links mentioned in previous versions of Artistic Style. It links to + free software and other information. +

    +

    + The "Developer Information" section has a new example and download for calling Artistic Style from an Objective‑C + program. Since it is another "C" language the only thing needed is to link the program with a library build of + Artistic Style. The example was developed on Windows and Linux using the GNUstep project. Since the example is + a console program the problems with the GNUstep GUI have been avoided. It has not been tested on a Mac, but should + be close to working. The "Developer Information" section also has new page for "Objective‑C on Windows and + Linux" which has information on compiling and running the example on those systems. +

    +

    + The executable included in the Windows distribution was compiled with Visual Studio 2010 (platform toolset v100). + Higher releases contain dependencies on Windows API functions that exist only on Windows Vista, Windows 7, and + Windows 8. This means that applications built with a Visual Studio 2012 C++ compiler would fail to load and execute + on Windows XP. +

    +

    + If you are using Windows Vista or higher, and have a Visual Studio 2012 or higher compiler available, recompiling + will probably result in faster execution. If you use a compiler other than Visual Studio, you can probably get + better execution by compiling using the C++11 standards. Artistic Style uses a lot of string vectors and the new + move semantics will probably result in faster execution. +

    +

    + Thanks to Evmenov Georgiy, Matthew Woehlke, Jiang, Ruzzz, and beta100100 for their contributions. +

    + +

    Artistic Style 2.03  (April 2013)

    + +

    + With a new Artistic Style release some unchanged source files will be formatted because of changes to Artistic + Style. You may want to format your source before making program changes in order to bring it up to date. +

    +

    + A new option, "max-code-length=#" or "xC#", will limit the length of code on a line. A new option "break‑after‑logical", + or "xL", will modify a line break for conditionals. See the documentation for details. +

    +

    + A new option, "pad-first-paren-out" or "xd", will pad only the first paren in a series on the outside. See the + documentation for details. +

    +

    + A new option, "indent=force-tab-tab=#" or "xT#", will allow force tab indents with a tab length that is different + than the indent length. See the documentation for details. +

    +

    + The short option for delete-empty-lines has changed from "xd" to "xe". +

    +

    + The C++11 standard for range-based "for" loops, "enum" with a base type, and rvalue references is now supported. + The formatting of rvalue references is determined from the existing "align-pointer" and "align-reference" + options. +

    +

    + Closing the ending angle brackets of templates is now allowed by the C++11 standard. A new option, "close-templates" + or "xy", will close the whitespace in the angle brackets of template definitions. Be sure your compiler supports + this before making the changes. +

    +

    + The C/C++ keyword 'extern "C"' in a preprocessor no longer causes an extra indent. +

    +

    + Formatting of C++/CLI managed pointers (the '^' character) has been added to the "align-pointer" + option. +

    +

    +  The breaking of switch "default" statements has been fixed. The "default" statements + that have been incorrectly broken will be fixed in this release. +

    +

    + The byte order mark (BOM) has been removed from ASLocalizer.cpp for all platforms. The encoding of the file is + UTF-8. Many Windows editors can now recognize UTF-8 encoding without the BOM. Visual Studio has an option that + needs to be set. With others. such as CodeBlocks, identification is automatic. On Linux, UTF-8 is the default + encoding. +

    +

    + Translations have been added for Dutch, Finnish, Italian, Japanese, Korean, Polish, Portuguese, Russian, Swedish, + and Ukrainian. The translations were done with an automated translation program, Google Translate, so they may + not be the best translation possible. The translations are at the end of ASLocalizer.cpp in the form of an English‑Translation + pair. If you correct a translation, send the source as a bug report and it will be included in the next release. + To add a language, see "Internationalization" in the "General Information" section of the documentation. Send + the addition as a bug report and it will be included in the next release. +

    +

    + There is a new Linux makefile for the Clang Compiler. Clang is a free compiler can be installed as a package on + many Linux distributions. Some of its features are fast compiles, low memory use, expressive diagnostic messages, + and GCC compatibility. It includes a static analyzer tool that finds potential bugs in your source code. An experimental + version can be installed on a Windows platform. There is more information in the Install Information documentation. +

    +

    + Visual Studio automatically creates an import library and an export file when you link a program that contains + exports. It will do this for even a static library if it contains a __declspec(dllexport) definition. The Artistic + Style library (ASTYLE_LIB) build contains such exports which causes an import library and export file to be created + when they may not be needed. A new preprocessor definition, ASTYLE_NO_VCX (no Visual Studio exports) can be declared + to eliminate the files from the output. Use this only for static libraries or when the AStyle source is included + in the compile. Do NOT use this when compiled as a shared (dynamic) library. It is effective only for Visual Studio + 2012. It will NOT work with previous versions. It has no effect with other compilers since they require a separate + option to create the import library and export files. +

    +

    + The executable included in the Windows distribution was compiled with Visual Studio 2010 (platform toolset v100). + Visual Studio 2012 (platform toolset v110) contains dependencies on Windows API functions that exist only on Windows + Vista, Windows 7, and Windows 8. This means that applications built with a Visual Studio 2012 C++ compiler would + fail to load and execute on Windows XP. Artistic Style was therefore compiled with Visual Studio 2010 to work + on computers using Windows XP. +

    +

    + If you are using Windows Vista or higher, and have the Visual Studio 2012 compiler available, recompiling with + Visual Studio 2012 will probably result in faster execution. The Windows distribution has Visual Studio 2012 project + files available. +

    +

    + If you use a compiler other than Visual Studio, you can probably get better execution by compiling using the C++11 + standards. Artistic Style uses a lot of string vectors and the new move semantics will probably result in faster + execution. (To use C++11 on GCC and MinGW use the option --std=c++0x). This may change on future compiler releases.). +

    +

    + The "Developer Information" page has a new example and download for calling Artistic Style from a Python script. + It will run with both Python 2 and Python 3. Using Python 3 shows an example of formatting a Unicode string with + Artistic Style. Unicode strings must be encoded to UTF-8 before formatting and decoded back to Unicode afterward. + The example script shows the technique for doing this. It also shows how to set up the function pointers and allocate + memory in Python. +

    +

    + If you use Visual Studio on Windows, it can now be used for Python development. Python Tools for Visual Studio + (PTVS) is a free and open source plug-in for Visual Studio 2010 that supports Python and Iron Python. Other interpreters + such Jython can be added. It can be easily switched between Python versions or different interpreters. But the + best thing is the Visual Studio debugging support using the .NET debugger and the normal Visual Studio debugger. + It enables you to set break points, step through functions, change the current statement, inspect local variables, + and perform other operations while debugging. It is best to use it with a project file, a minor irritation for + single page scripts. And there are some minor bugs. But overall it works quite well. +

    +

    + Thanks to Christopher Sean Morrison, Keith OHara, louis6g, and J for their contributions. +

    +

    +   +

    +

    + Previous releases are available in the News Archives. +

    +

    +   +

    + +

    + + +

    + +

    +   +

    + + + + + diff --git a/External/Tools/AStyle/doc/newsArchives.html b/External/Tools/AStyle/doc/newsArchives.html new file mode 100644 index 0000000000..791f1e20ad --- /dev/null +++ b/External/Tools/AStyle/doc/newsArchives.html @@ -0,0 +1,1004 @@ + + + + + + Artistic Style - News Archives + + + + + + + + +

    Artistic Style News Archives

    + +

    +   +

    + +

    Artistic Style 2.02  (May 2011)

    + +

    + With a new Artistic Style release some unchanged source files will be formatted because of changes to Artistic + Style. You may want to format your source before making program changes in order to bring it up to date. +

    + +

    Release 2.02.1 - November 2011

    + +

    + This bug fix release is issued because of the length of time required for the some of the changes in the next + release (2.03). Bugs with the breaking of "case" statements and a crash with pointer to pointer (**) in align-pointer=type + have been fixed. The "case" statements that have been incorrectly broken will be fixed in this release. Pointers + and references are now processed for C# files. See the "Release Notes" for more information and additional changes. +

    + +

    The following information is for the original 2.02 release.

    + +

    Translations

    + +

    + A new program module and header, ASLocalizer.cpp and ASLocalizer.h, have been added. These are required for the + console build and are optional for the library builds. It contains language translations for several of the most + common users of Artistic Style. The method used was adapted from the Gnu "gettext" method. +

    +

    + The translation to use is determined from the User Locale for Windows and the LANG environment variable for other + systems. The translation will be done automatically from these settings. If no translation is available it will + default to English. +

    +

    + A new option, "ascii" or "I", will display the text in English regardless of your system settings. This option + must be input from the command line and not an option file. See the documentation for details. +

    +

    + The translations were mostly done with an automated translation program, Google Translate, so they may not be + the best translation possible. The translations are at the end of ASLocalizer.cpp in the form of an English‑Translation + pair. If you correct a translation, send the source as a bug report and it will be included in the next release. +

    +

    + To add a language, add a new translation class to ASLocalizer.h. Add the English‑Translation pair to the + constructor in ASLocalizer.cpp. Update the WinLangCode array, if necessary, and add the language code to the function + setTranslationClass(). The ASLocalizer.cpp program contains comments that give web pages for obtaining the LCIDs + and language codes. Send the source code as a bug report and it will be included in the next release. +

    + +

    Brackets

    + +

    + Since release 1.22 (April 2008) the predefined styles have increased from 5 to 12 and the bracket types have increased + from 4 to 6. Having two different ways of defining bracket styles has resulted in some confusion and unnecessary + duplication. This release starts a redesign of the bracket definitions to simplify the user interface. The predefined + styles and bracket types will be combined into a single option category. +

    +

    + The "Predefined Style" options have been renamed "Bracket Style" options. The "Bracket Options" have been depreciated + and will be removed in a future release. If you are using a "brackets=" option, you should start changing to one + of the "style=" options. There is a "style" option available for every "brackets" option. +

    +

    + All "Bracket Style" options now default to 4 spaces per indent. If you were using a "Predefined Style" with a + default indent other than 4, you will need to add one of the "Tab Options" to maintain the same indentation. The + styles which used indents other than 4 were: +

    +
      +
    • Stroustrup - 5 spaces per indent.
    • +
    • Gnu - 2 spaces per indent.
    • +
    • Linux - 8 spaces per indent.
    • +
    • Horstmann - 3 spaces per indent.
    • +
    +

    + There is a new "Bracket Style" option "style=pico" or "A11". It uses run-in brackets, like Horstmann style, and + attaches the closing bracket to the last line in the block. It sets the options "keep one line blocks" and "keep + one line statements". This is a very compact style and is a good style for small monitors. +

    +

    + Another new "Bracket Style" option is "style=lisp" or "style=python" or "A12". It uses attached brackets, like + Java style, and attaches the closing bracket to the last line in the block. It sets the option "keep one line + statements". This style makes indentation the only way of distinguishing blocks of code, but has the advantage + of containing no uninformative lines. Like Pico, it is also a very compact style. +

    +

    + The option "brackets=horstmann" has been removed. Instead use "style=horstmann" or "A9". The short option "g" + is now equivalent to the new "brackets=run-in". Run-in brackets are used for both Horstmann and Pico styles. +

    +

    + The option "indent-brackets" and short option "B" have been removed. Instead use "style=whitesmith" or "style=banner". +

    +

    + The option "indent-blocks" and short option "G" have been removed. Instead use "style=gnu". +

    +

    + Two new options, "style=break" and "style=attach", have been added for Allman and Java bracket styles respectively. +

    + +

    Other Changes

    + +

    + To allow for future expansion the short options will now allow an "x" prefix to be used. New short options may + start with an "x" and will be followed by another character (e.g. "xa", "xb", "xc" ...). The current options, + with one exception, will still be valid. +

    +

    + The short option for "delete-empty-lines" has been changed from "x" to "xd" to allow for the expansion of short + options. +

    +

    + A new option "align-reference=" (-W#) allows references to be aligned separate from pointers. See the documentation + for details. +

    +

    + Since computer screens are getting wider the maximum value for "max-instatement-indent" has been increased from + 80 to 120. +

    +

    + New options ignore‑exclude‑errors (‑i) and ignore‑exclude‑errors‑x (‑xi) + will allow processing to continue if there are errors in the "exclude" options. This lets the excludes for several + projects to be entered in a single option file. The "ignore" options may be placed in the same option file as + the excludes. The ignore‑exclude‑errors option will display the unmatched excludes, ignore‑exclude‑errors‑x + will not display them. +

    +

    + Artistic Style can now format UTF-16 encoded files, both little and big endian. This encoding is the default for + Visual Studio Unicode files. The file is formatted by converting it to UTF‑8 and then back to UTF‑16. + The conversion process does not add a significant amount of time to the formatting. The UTF-16 file must be encoded + with a byte-order-mark (BOM) to be recognized. Again, this is the Visual Studio default. +

    +

    + The Visual Studio project files now have a solution for both Win32 and x64 compiles. The x64 version will be needed + if you are using an Artistic Style DLL for Java or C# on a Windows 7 platform. Or you may just prefer an + x64 console program. The executable included in the Windows distribution is still Win32. It will work on both + Win32 and x64 systems. +

    +

    + If you use Visual Studio C++ Express the 2010 release has the ability to compile x64 code. But you must use Vista + or Windows 7 and need to install the .NET Framework SDK. I have created a brief instruction page here. Note + that a fix is required if you apply Service Pack 1 after installing the .NET Framework SDK. +

    +

    + The documentation contains a new section "Command-line Only" which lists commands that are not available from + an options file. The options were transferred from the "Other Options" section. +

    +

    + Thanks to Milian Wolff, Johannes Martin, and Arne F?rlie, and Marvin Humphrey for their contributions. The UTF‑8 + and UTF‑16 conversions were obtained from the SciTE source code editor. +

    + +

    Survey Results

    + +

    + The results of the survey posted last release are available at General Information and Artistic Style Options. + Thanks to everyone who took the time to complete it. +

    +

    + Surveys give an indication of how many people are using an option or want certain features. This is information + that is not available in the bug reports. +

    +

    + In the "Enhancements" group there were three items with multiple requests. The most frequent request by far was + to enforce a maximum line length. This is also the oldest request in the bug reports. Another item with multiple + requests was to disable/enable Artistic Style formatting on request within source files. This is the second oldest + request in the bug reports. A third item with multiple requests was to customize namespace brackets independent + of the requested bracket style. I will try to address these in the next release. +

    +

    + Things that stand out to me in the multiple‑choice sections: +

    +
      +
    • The predefined styles and brackets options were each used about 50% each. That will change with this release. +
    • +
    • Over 50% of the survey uses Artistic Style for Windows. I have been working for a couple of years on a new program + based on wxWidgets. I will try to give this more priority in the future.
    • +
    • Over 75% of the survey uses Artistic Style to format entire projects.
    • +
    • About one‑third of the Windows C++ users use Artistic Style for Managed C++.
    • +
    • The most popular option is add‑brackets (60%), which was just recently added.
    • +
    • The attach‑pointer options, in total (70%), are even more popular than add-brackets. They were also recently + added.
    • +
    • The preserve-date option is used by nearly one-third of the survey.
    • +
    • All of the options are used by someone in the survey, even the ones I thought were outdated. The bracket styles + that are not used are probably a result of not having enough response.
    • +
    + +

    Developers

    + +

    + The Artistic Style for Windows program contains a sample GUI using the new bracket style options. The old predefined + styles are now the bracket styles. The bracket options have been removed along with the indent‑brackets + and indent‑blocks options. The new bracket styles all use the same default indent of 4 spaces, therefore + it is not necessary to set an indentation from the bracket style. The new format is available for use with this + release. +

    +

    +   +

    + +

    Artistic Style 2.01  (November 2010)

    + +

    + With a new Artistic Style release some unchanged source files will be formatted because of changes to Artistic + Style. You may want to format your source before making program changes in order to bring it up to date. +

    +

    + A new feature at SourceForge is download maps that show a list of downloads by country. It is available from the + top menu at Develop > Download Stats (Beta), and clicking on the "top country" area. The list of downloads + shows about 75% of Artistic Style downloads are from non English speaking countries. This release is the start + of the internationalization of Artistic Style. +

    +

    + Artistic Style now sets the native local so that characters from the user’s native language will be recognized + in directory names and file names. Artistic Style for Windows has also been changed to use the native locale. + For Linux systems using UTF-8 locales, characters from any language will be recognized and any combination of + languages can be used. For Windows, only languages recognized by the native codepage can be used. For example, + the English locale (codepage 1252) also has French, German, Italian, Portuguese, Spanish, plus several other languages. + Other locals, such as Chinese and Japanese, only support one language. Unicode was not used due to the varying + degree of support by different compilers for console applications. +

    +

    + The locale setting also affects the way numbers are displayed. Language translations may be provided in a future + release. +

    +

    + This is a major release (2.01) because of the internationalization and changes that will occur in the next couple + of releases. Future releases will contain a major change to the bracket options and a rewrite of the file access + method. Some of the requested changes require looking at blocks of code instead of single lines. The current program + has been patched to do this but a rewrite of the file input is needed. These are both major changes but with the + new test framework in place they should be manageable. +

    +

    + There has been a change to the ‑‑min‑conditional‑indent option. Instead of using the number + of spaces it now uses a code expressed in number of indents. This will allow the option to be set independently + of the spaces per indent. If you are using the default setting of two indents, or a setting of zero indents, there + is no change necessary to the input. Otherwise, check the documentation for the new codes. +

    +

    + The --style=linux has been changed to ALWAYS use a minimum conditional indent of one-half the indent length. This + is in the style definition and cannot be changed. If you do not want this setting use the K&R style instead. +

    +

    + The MFC macros BEGIN_DISPATCH_MAP, BEGIN_EVENT_MAP, and BEGIN_PROPPAGEIDS are now formatted. +

    +

    + Checksum verification has been added to source file output that will help assure that no code has been duplicated + or omitted. This is effective only in the debug configuration used for testing. +

    +

    + The test framework has been changed from UnitTest++ to Google Test, which is actively maintained, has a mock object + framework (Google Mock), and good documentation. Regression and system testing have been automated with Python + scripts. Python has also been used for class verification checks and other repetitive procedures. +

    +

    + If you use Visual Studio C++ Express the 2010 release has the ability to create x64 code. But you must use Vista + or Windows 7 and need to install the .NET Framework SDK. I have created a brief instruction page here. +

    +

    + Thanks to Matthew Woehlke, Chris Schwarz, Chang Jiang, and Arseny Solokha for their contributions. +

    + +

    Developers

    + +

    + On the library build of Artistic Style, the second argument of the fpError typedef and the javaErrorHandler declaration + has been changed from "char*" to "const char*". This could cause a compile error if not changed in the source + statements. +

    +

    + There has been a change in the ‑‑min‑conditional‑indent option. Instead of using number + of spaces to indent it now uses a code expressed in number of indents. In the past this option was a problem because + it was also affected by changes in indent length. With this release there is only one variable affected. The option + is not affected by changes in indent length. The minimum conditional indent length is computed automatically by + ASFormatter after all the options have been processed. Refer to the code in astyle_main.cpp to see how the option + is processed. +

    +

    + The --style=linux has been changed to ALWAYS use a minimum conditional indent of one-half the indent length. The + option is set in the function fixOptionVariableConflicts. +

    +

    + The use of locales affects only the command line build. +

    + +

    Artistic Style 1.24  (February 2010)

    + +

    + With a new Artistic Style release some unchanged source files will be formatted because of changes to Artistic + Style. You may want to format your source before making program changes in order to bring it up to date. +

    +

    + A new bracket type option, ‑‑brackets=horstmann (-g), uses broken brackets and places run-in statements + on the same line as an opening bracket. This bracket type has about the same vertical compression as attached + brackets and in addition provides bracket alignment. It is the only style that combines the advantages of saving + space and aligning brackets. The "Tab and Bracket Options" section in the documentation contains the + details. To accommodate Hostmann brackets the "none mode" brackets will now allow run-in statements. + Array formatting has been changed to format run-in statements when required. There have been some general improvements + to array formatting. The minimum value for spaces per tab was changed from one to two. The example programs in + the "Developer Information" section have been changed to Horstmann brackets. +

    +

    + Two new options, ‑‑add‑brackets (-j) and ‑‑add‑one‑line‑brackets + (-J), will add brackets to unbracketed one line conditional statements. The ‑‑add-brackets will add + the brackets according to the currently requested predefined style or bracket type. If no style or bracket type + is requested the brackets will be the attached type. The ‑‑add‑one‑line‑brackets + will add the brackets as single line brackets. This option implies ‑‑keep‑one‑line‑blocks + and will not break single line blocks. +

    +

    + The above options allow two new predefined styles. Horstmann style, ‑‑style=horstmann (-A9), uses + Horstmann brackets and three spaces per indent. The so called "One True Brace Style", ‑‑style=1tbs + or ‑‑style=otbs (-A10), uses linux brackets and the option ‑‑add‑brackets. The basic + criteria for most predefined styles were obtained from the Indent Style discussion at Wikipedia. The "Predefined + Style Options" section in the documentation contains the details. +

    +

    + The spaces per indent can now be changed for any of the predefined styles. In previous releases the option would + be ignored. This will allow any of the ‑‑indent options to be used with a predefined style. If the + spaces per indent is not specified, the default for the style will be used. +

    +

    + A new option, ‑‑pad‑header (‑H), will insert space padding after headers ('if', 'for', + 'while'...). To remove any unwanted current space padding, use the option ‑‑unpad‑paren (‑U). + If both ‑‑pad‑header and ‑‑unpad‑paren are used, the headers will be padded + and the padding will be removed from other parens. This has required a change to the default formatting of paren + headers. They will now be left unchanged instead of automatically inserting space padding, unless the new option + is requested. +

    +

    + New options --align-pointer=type (-k1), ‑‑align‑pointer=middle (-k2), and ‑‑align‑pointer=name + (-k3) will attach a pointer or reference operator (* or &) to either the operator type (left), operator name + (right), or align it between the type and name. The spacing between the type and name will be preserved, if possible. + The recognition of pointers and references has been improved. This resulted in an improvement of the ‑‑pad‑oper + (-p) option. +

    +

    + A new option, ‑‑indent‑col1‑comments (-Y), will indent C++ comments beginning in column + one. By default C++ comments beginning in column one are not indented. This option will allow the comments to + be indented with the code. +

    +

    + New options --lineend=windows (-z1), --lineend=linux (-z2), and --lineend=macold (-z3) will force + use of the specified line end style. Valid options are windows (CRLF), linux (LF), and macold (CR). MacOld style + is the format for OS 9 and earlier. Mac OS X uses the Linux style. Changes in line ends will cause the file to + be updated, even if no other changes occur. If one of these options is not used the line ends will be determined + automatically from the input file. +

    +

    + Default line end processing has been improved to always output consistent line ends. It will use the line ends + that are most frequently used in the input. +

    +

    + The Stroustrup predefined style has been changed to use 5 spaces per indent. This is the indentation used in the + book "The C++ Programming Language" by Bjarne Stroustrup. +

    +

    + The minimum conditional indent for the Linux predefined style has been changed to 4, or one-half the indent-length. + The previous minimum conditional indent was 16 (2 indents). The new value corresponds to the soft tab in the style + description at Wikipedia and gives a better conformance to the definition of the style. And it gives a better + appearance to the continuation lines. +

    +

    + Embedded SQL statements are now formatted correctly. The formatting of the SQL statements will be maintained as + long as the standard hanging indent format is used. If the "exec sql" statement is indented more than the following + statements, the SQL will be aligned in a single column. +

    +

    + Assembler statement processing has been improved to include extended assembly and Microsoft specific assembler + lines and blocks. +

    +

    + The --indent-classes (-C) option has been fixed to indent C++ struct blocks containing access modifiers (public, + protected, and private). The struct block is not indented if there are no access modifiers in the block. +

    +

    + The formatting for C++ class initializer statements has been changed from two indents to one and an in-statement + indent added for continuation lines. +

    +

    + The intermediate .tmp file used in formatting has been eliminated and memory is used instead. In most cases this + should result in a noticeable speed improvement. +

    +

    + Checks for the maximum in-statement indent have been fixed. The indent for some long continuation lines may be + decreased. If you want the previous indentation, increase the ‑‑max‑in‑statement option. +

    +

    + Occasionally, someone will use Artistic Style to format a file encoded with UTF-16 or UTF-32 bit encoding. These + files contain many nul bytes are incompatible with the 8 bit encoding assumed by Artistic Style. Since this rarely + happens, Artistic Style has been changed to list these files as "unformatted" and display a warning message. The + files must have a Byte Order Mark (BOM) for the encoding to be recognized. These files can be changed with the + program iconv and with some text editors such as SciTE. For more information see the Wikipedia discussion on "Comparison + of Unicode encodings", "Compatibility issues". +

    +

    + The Artistic Style documentation has been changed to include a new "Padding Options" section. The padding options + were previously in the "Formatting Options" section. This was done to allow space for additional options in GUIs. +

    +

    + The Scripts page has a couple of new scripts, including a "clean" script in python. +

    +

    + There are new configuration and project files for Visual Studio, and additional files for Visual Studio 2010. + There are instructions in the "Install Information". +

    +

    + The Intel compiler for Linux, release 11.1, has a new procedure for compiles. Read the new "Install Information" + before using this compiler release. +

    +

    + There is now a Subversion repository for Artistic Style. A new Subversion web page describes how to check-out + the files. The source code is under development and some changes take several weeks to complete. And the intermediate + source files have not been through the extensive system tests that are done before each release. Use reasonable + precautions when using source code from the repository. +

    +

    + SourceForge recently made changes to their website which caused a few problems. The web page links should be fixed + with this release. It seems that some bug reports may have been lost. If you have submitted a report that has + not been addressed please check to be sure it is still there. In addition Yahoo closed their GeoCities site which + made the AStyleWin programs temporarily unavailable. The new site is jimp03.zxq.net/. +

    +

    + The release announcements mailing list was discontinued with the new SourceForge system. There is a new astyle-announce + mailing list that will be used instead. This is a low volume list that will be used for new release announcements + and notification of important repository commits. Member postings will not be accepted. Membership in the old + list was not retained so you will need to register for the new list. There is information for subscribing on the + "Bug Reports, Change Requests, Notification" section of the Home page. +

    +

    + Thanks to J P Nurmi (align-pointer), Mario Gleichmann (pad-header), MrTact (lineend), Christian Stimming (<< + and >> operators), Wim Rosseel (Perl script), Colin D Bennett (64-bit code), and Ettl Martin (cppcheck) + for their contributions. +

    +

    + The OpenVMS distribution is prepared by Jim Duff, an OpenVMS Systems Specialist living in Sydney, Australia. His + website is eight‑cubed.com. +

    + +

    Developers

    + +

    + The Artistic Style for Windows program has been updated to support the current release and can be used for an + example GUI. It will run on Linux under WINE. It is available at jimp03.zxq.net +

    +

    + The options --lineend=windows (-z1), --lineend=linux (-z2), and --lineend=macold (-z3) apply only + to the console build. It was not included in the developer builds because developers usually have their own method + for handling line ends. +

    +

    + The option --break-closing-brackets has been moved from Bracket Options to Formatting Options. It was being mistaken + for a bracket type, which it is not. +

    +

    + Rejecting a file for  UTF-16 or UTF-32 bit encoding apply only to the console build. Some class libraries, + such as wxWidgets (and probably Qt), have the methods to convert the files to UTF-8. The handling for these types + of files must be determined by the individual applications. +

    +

    + There has been an additional variable, formattingStyle, added to the ASFormatter class. This is now the ONLY option + that needs to be set to define the style. Setting the individual options is no longer necessary. The individual + options are now set in the fixOptionVariableConflicts function in ASFormatter. The predefined style options will + now override all other options. The order of entry does not matter as in previous versions. +

    +

    +   +

    + +

    Artistic Style 1.23  (February 2009)

    + +

    + With a new Artistic Style release some unchanged source files will be formatted because of changes to Artistic + Style. You may want to format your source before making program changes in order to bring it up to date. +

    +

    + In the last few years the names of indent styles have been somewhat standardized. A typical example is the Indent + Style discussion at Wikipedia. To keep up to date with the industry, changes have been made to the names of two + of the styles. The ANSI style can now also be Allman or BSD, and for the KR or Java style you should now use only + Java. The KR style has always been basically the same as the Java style. The KR style is depreciated and will + be removed sometime in the future. +

    +

    + Four new predefined styles have been added, K&R (with an &), Stroustrup, Whitesmith, and Banner. K&R + style uses Linux type brackets where the depreciated KR style uses attached brackets. Notice that K&R and + KR are two different styles. Stroustrup style uses the new stroustrup brackets described below. Whitesmith has + broken brackets that are indented. Banner has attached brackets that are indented. The following table summarizes + the changes: +

    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    old style    new style
    ansiallman or ansi or bsd
    java or krjava
    gnugnu
    linuxlinux
    nonek&r or k/r
    nonestroustrup
    nonewhitesmith
    nonebanner
    +
    + +

    +   +

    +

    + There is a new Stroustrup style and bracket type. It is similar to the Linux bracket type except that the brackets + are attached to namespaces and classes instead of being broken. It is the style used by Bjarne Stroustrup, the + founding father of C++, in his book "The C++ Programming Language". +

    +

    + Indenting brackets in the Whitesmith and Banner styles causes a 'hanging indent' with switch statements and C++ + class modifiers (public, private, protected). Microsoft Visual Studio avoids this by giving class and switch blocks + an extra indent when brackets are broken (Whitesmith style). Gnu Emacs gives switch blocks an extra indent but + not class blocks. With indented, attached brackets (Banner style), Visual Studio does not use an extra indent + and Emacs does not have the style. Artistic Style uses an extra indent for switch blocks and C++ class blocks + for both Whitesmith and Banner styles. This provides the best appearance in defining the style. If + a different format is wanted, use the individual options instead of the predefined style. You can try indent‑brackets, + indent‑classes, and indent‑swiches on a class or switch block to see the results. +

    +

    + The GNU style and indent‑blocks option have been changed to indent only the blocks within a function body. + The opening bracket for namespaces and classes is no longer indented. The opening bracket for functions remains + not indented. This is the same formatting used by the Emacs editor and is in compliance with the GNU standard. + The GNU style has also been changed to NOT indent namespaces by default. Namespaces can be indented by using the + indent‑namespaces option. This is consistent with the other predefined style options. +

    +

    + The predefined style options will now override all other options. It does not depend on order of entry as in previous + versions. Using a predefined style will give that style regardless of other conflicting entries. The predefined + styles options now define only the bracket placement and sometimes the spaces per tab. This will give users the + option to define the other details according to their preference. The 'Predefined Style Options' section in the + documentation contains the details. +

    +

    + Changes have been made to some of the long options. Most configuration files will NOT allow options to have duplicate + keys (e.g. the Windows registry and wxWidgets). The key is the value before the first '=' sign. If there is no + '=' sign then the entire option is the key. The options were changed to eliminate duplicate keys when + more than one option is allowed. The old options are depreciated but will still be valid until at least the next + release. The short options remain the same. The following options have changed: +

    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    old option    new option
    force-indent=tab=#indent=force-tab=#
    brackets=break-closingbreak-closing-brackets
    pad=operpad-oper
    pad=parenpad-paren
    pad=paren-outpad-paren-out
    pad=paren-inpad-paren-in
    unpad=parenunpad-paren
    one-line=keep-statementskeep-one-line-statements
    one-line=keep-blockskeep-one-line-blocks
    +
    + +

    +   +

    +

    + The "else if" statements will now be placed on a single line by default. This is described as a 'fix' since it + was apparently always supposed to do this. The headers will be broken only if the option 'break‑elseifs' + is specified. Most users want the statements joined since breaking them requires an extra indent. +

    +

    + The convert‑tabs option has been changed to maintain the correct spacing according to the current tab setting. + Previously a tab was replaced by a single space. The current option for spaces per tab is used. It may NOT produce + the expected results if convert‑tabs is used when changing the spaces per tab. The tabs are NOT replaced + in quotes. +

    +

    + The break‑blocks and break‑blocks=all options have finally been fixed. They will no longer break statements + following the block and will keep preceding comments with the block. Many other fixes were required for the options + to work correctly. The "Release Notes" page has the details. +

    +

    + A new delete‑empty‑lines option will delete empty lines within a function or method. If used with + break‑blocks or break‑blocks=all it will delete all lines EXCEPT the lines added by the break‑blocks + options. +

    +

    + There is a new 'formatted' (‑Q) option that displays only the files that have been formatted. Files that + are unchanged are not displayed. +

    +

    + Short options have been added for the predefined styles. +

    +

    + Semi‑colons are now always space padded. All commas are space padded if pad‑oper is used. +

    +

    + The C/C++ keyword 'extern' no longer causes an extra indent. +

    +

    + There have been several important fixes to the indent‑brackets and indent‑blocks options. +

    +

    + There have been several important fixes to C# formatting. +

    +

    + The scripts page has a new Emacs script containing hooks that will set the Emacs style options to the default + options used by Artistic Style. It also defines a Banner style. It can be used to compare output from the two + programs. The files will not be exact but it should be reasonably close. If you can improve the Emacs script I + would like to have the changes. +

    +

    + There are two new projects on the Links page. CodeLite is a C++ development environment with + some useful features, including a template to generate a test program using the excellent tool UnitTest++. target="astyle" + title="open new window">Highlight converts source code to formatted text with syntax highlighting. + It was used it for the source code in the Developer Information section. +

    +

    + I need a Mac OS X user to do testing on new releases. The test usually take 30 minutes at the most. They may need + to be repeated two or three times depending on the results. Programming knowledge is not necessary but will probably + be helpful. Reply to the project email address if you would like to volunteer. +

    +

    + The OpenVMS distribution is prepared by Jim Duff, an OpenVMS Systems Specialist living in Sydney, Australia. His + website is eight‑cubed.com. +

    +

    + Thanks to Eran Ifrah and Max Horn for their contributions. Travis Robinson wrote the original C# interface program. +

    + +

    Developers

    + +

    + There is a new page in the Developer Information that has an example of calling Artistic Style from a C# program. +

    +

    + There was an omission in the peekNextLine function added in the last release which causes it to bypass empty lines. + If you copied the function into a program, the change is at the end of peekNextLine in astyle_main. The line containing + the change is marked with comments. Not correcting it may cause an infrequent line break if the option break‑blocks + or break‑blocks=all is used. The break will occur only if there are empty lines within comment lines that + precede a header. +

    +

    + There has been an additional variable, formattingStyle, added to the ASFormatter class. This is now the ONLY option + that needs to be set to define the style. Setting the individual options is no longer necessary. The individual + options are now set in the fixOptionVariableConflicts function in ASFormatter. +

    +

    + The predefined style options will now override all other options. The order of entry does not matter as in previous + versions. This will be done even if astyle_main is not used by your system. This was done by moving the checks + from astyle_main to ASFormatter. The procedure is in the function fixOptionVariableConflicts in ASFormatter. +

    +

    + The predefined style options now define only the bracket placement and sometimes the spaces per tab. This will + give users the option to define the other details according to their preference. It is best if the other options + are NOT disabled when a predefined style is selected. All options should be left available to modify the style. + The conflicts will be resolved by the fixOptionVariableConflicts function which is called after all options have + been processed. All you need to do is set the options selected by the user. +

    +

    + The Artistic Style for Windows program has been updated to support the current release. It is available at jimp03.zxq.net +

    +

    + I apologize for the unplanned changes this may add to your system. But Artistic Style is starting to mature as + an application and the changes are needed to bring it up to date. If you have any questions or problems, email + me and I will do my best to help you resolve them. +

    +

    +   +

    + +

    Artistic Style 1.22  (April 2008)

    + +

    + This release contains many bug fixes. The emphasis was on formatting fixes for C# files. In the last two releases + there have been over 80 items removed from the bug report. There have been many more fixes which were not reported + but were discovered while testing. The new options in this release exposed many unreported formatting problems. + I will try to fix the ones remaining in the next two or three releases. Some of them will be difficult to fix. + See the Release Notes for a complete list of changes. +

    +

    + Starting with this release, if a file is not changed by Artistic Style a new file and a backup + file are not created. A "make" will not recompile the unchanged file and it will not be committed to a revision + control system. A console message will indicate that the file is unchanged. Note that this is different from using + the ‑‑preserve‑date option. This option retains the date on files that have + changed. In this case the changed files will still be recompiled and committed to revision control. (‑‑preserve‑date + actually changes the time by one unit). +

    +

    + In the rare case when Artistic Style aborts, the file being formatted will no longer be deleted. This is done + by using a temporary output file (.tmp). It should now be safe to manually abort Artistic Style and restart at + any time. The backup of files that were previously formatted will not be replaced. +

    +

    + The console display has been changed. The default now displays one line per file. This will be useful if only + one file is being formatted, such as when Artistic Style is called from a text editor or development environment. + A new ‑‑verbose (‑v) option will display optional information, such as release number and statistical + data. A new ‑‑quiet (-q) option will suppress all output except error messages. Some short options + have changed to accommodate the new options. The short option for ‑‑version is now -V (old -v) and + for ‑‑convert‑tabs is ‑c (old ‑V). +

    +

    + A new ‑‑recursive (-r, or -R) option will process subdirectories recursively. The filename should + contain a wildcard (e.g. "$HOME/astyle/src/*.cpp"). Linux users should place the filename in double quotes so + the shell will not resolve the wildcards. Windows users should not include wildcard object files, + like setargv (Visual C) or wildargs (Borland), in the compiles. Wildcard processing in MinGW was excluded by adding + "int _CRT_glob = 0" as a global variable. (It could also be excluded by linking to CRT_noglob.o). + Artistic Style now does the wildcard processing internally. +

    +

    + When processing directories recursively it is sometimes necessary to exclude certain files or directories. This + can be done using a new exclude (‑‑exclude=file‑or‑directory) option. There is no short + option. Multiple exclude statements are allowed. The Other Options section of the documentation contains the details. +

    +

    + It is always a good idea to create a backup for files that have been formatted. This can cause a problem in that + it creates a lot of excess files in your source directories. There are now new script files available that will + move the files to a backup directory. The original directory structure will be maintained the in the backup. There + is a batch file for Windows and a shell script for everyone else. They are available in the Scripts section of + the home page. +

    +

    + There is a new Links page that lists programs using Artistic Style. In general, they seem to be good quality software. +

    +

    + If you are using a development environment to compile Artistic Style, be sure to read the Compiler Options section + in the Install Information. In particular, you should define NDEBUG in the Release compile to remove the assert + statements. There are quite a few of these and they will slow down processing if NDEBUG is not used. The assert + statements are necessary due to the nature of the program. Also, when reporting bugs it is a good idea to log + in first. Occasionally, more information is needed on a problem. If the poster did not log in there is no way + to contact them. +

    +

    + A Java Native Interface has been added for Java developers. This will allow an Artistic Style shared library (DLL) + to be called from a Java program. A shared library (Dll) using the Java interface can still be called from C, + C++, or C# programs. There is a sample program in the Developer Information. +

    +

    + Developers using Artistic Style in another project should be aware that there are two new functions + that have been added to the ASStreamIterator class (peekNextLine() and peekReset()). These will have to be coded + into source modules which use Artistic Style without astyle_main. In most cases the functions can simply be copied + without the template information. The assert statements may also be removed. A variable will need to be added + to the class and another may need to be modified. If the shared or static library configuration is being used + then no changes are necessary. +

    +

    + The file globing function was obtained from "The Code Project" and was written by Jack Handy. It was modified + slightly to make the comparisons case insensitive for Windows. +

    +

    + The OpenVMS distribution is prepared by Jim Duff, an OpenVMS Systems Specialist living in Sydney, Australia. His + website is eight‑cubed.com. +

    +

    + Thanks to Emilio Guijarro and Jens Krinke for their contributions, and to Sam Cooler for testing the Mac OS X + version. +

    +

    +   +

    + +

    Artistic Style 1.21  (June 2007)

    + +

    + This release contains many bug fixes. Array formatting and indentation has been improved. Arrays and enums are + now formatted by a different procedure than functions. Brackets will now attach to lines with comments. Brackets + will be broken from lines with comments without bringing the comments with them. All comments will remain in their + original column, if possible. The formatting of empty blocks was fixed. The BracketType definition was expanded + and the bracket types are now correctly identified. There are several formatting fixes for Java files. See the + Release Notes for a complete list of changes. +

    +

    + A new option, --preserve-date (-Z), has been added. This will retain the date modified of the original file in + the new formatted file. Otherwise the new file will contain the current date. +

    +

    + The option --errors-to-standard-output has been shortened to --errors-to-stdout. The short options + -c (mode=c) and -j (mode=java) have been removed. The options should seldom be needed since the mode is now set + automatically from the file extension for each source file instead of for each program execution. + A new long option --mode=cs (C#) has been added. Key words are now set for each file depending on the file mode + (C, Java, or C#). This will eliminate formatting problems caused by not being able to identify the source code + language. +

    +

    + There has been a change to the Linux style bracket formatting for C++ header files. In the past brackets have + been broken for function definitions within a class. With this release the brackets will be attached. The brackets + will also be attached for arrays, structs, enums, and other top level objects that are not classes or functions. + The Linux style formatting for Java and C# has not been changed. +

    +

    + This release supports only one platform in each distribution package. In the past all platforms were included + in every package. If you use Artistic Style on more than one platform you will need to download packages for each + platform. The main difference in platforms is the build directory and the line endings. The source code and documentation + are the same for all packages. +

    +

    + There are new instructions about optimizing compiler options in the Install Instructions. If you are compiling + using a development environment you may want to read them. +

    +

    + If you have broken brackets with comments attached to the opening bracket instead of the previous line, do the + following before formatting again with broken brackets. Use the current Artistic Style release + (1.21). Format the source using attached brackets to reattach the brackets and the comments to the previous line. + Then format the source again using broken brackets. This will move the brackets to the next line without the comments. + The comments will now be on the correct line. +

    +

    + There is a new multi-platform GUI program, UniversalIndent, available at sourceforge.net/projects/universalindent. + It allows you to view the effects of the Artistic Style options on your source code without saving the file. You + can review the results of the formatting options before updating the file. It can be used with a test file or + with your actual source code. It supports several other formatting programs. The Artistic Style for Windows + program has been updated to support the current release. It is available at jimp03.zxq.net +

    +

    + There have been a few inquiries about how to customize Artistic Style for an unsupported format. Changes can be + made with Python or another text processing program after formatting the source, or you can modify the Artistic + Style source code itself. The best place to modify the code is usually in ASEnhancer.cpp. The ASEnhancer class + is called after the main formatting has been done so you are getting a formatted file. If you just need to change + the indentation of a few things this is probably the best place to do it. +

    +

    + There is now a distribution package for OpenVMS thanks to Jim Duff, an OpenVMS Systems Specialist living in Sydney + Australia. His website is at eight-cubed.com. +

    +

    + Thanks to Norbert Holzki and Siemens AG, Medical Solutions, Forchheim, Germany for testing the array formatting. +

    +

    + Thanks to Sam Cooler for testing the Mac OS X version. +

    +

    +   +

    + +

    Artistic Style 1.20  (January 2007)

    + +

    + Release 1.20.2 fixed problems with the new stream I/O procedure added in release 1.20.1. Release 1.20.1 improved + the processing for Mac OS X platforms. The compatibility with TextWrangler was improved. There is now a separate + release for Mac. +

    +

    + Artistic Style will now indent message maps for Microsoft Foundation Class (MFC) and event tables for wxWidgets. + The option --brackets=break-closing-headers has been shortened to --brackets=break-closing and a short option + added (-y). There have been short options added for --break-elseifs (-e), --indent-preprocessor (-w), --break-blocks + (-f), and --break-blocks=all (-F). +

    +

    + With this release the Artistic Style license changes from the GNU General Public License (GPL) to the GNU Lesser + General Public License (LGPL). You can use Artistic Style for free or commercial software without charge. Projects + that use Artistic Style do not have to make the their source code available. If Artistic Style itself is modified, + however, the modified Artistic Style source code must be made available. See the GNU Lesser General Public License + for more information. +

    +

    + There is a new preprocessor option to aid developers in using Artistic Style with a Graphical User Interface (GUI). + It is no longer necessary to remove the source module astyle_main.cpp and write embedded code to call the formatter. + It can be compiled as a static library or a shared library (DLL), or the entire source code can be included in + the project. See the Artistic Style Developer Information for the calling procedure and other details. +

    +

    + There is a sample GUI program for Windows available at http://jimp03.zxq.net/. It uses the unmodified Artistic + Style compiled for a GUI. The source code needs some work so it is not available for now. It should work under + Linux using WINE. Future enhancements and platform support will depend on the response to the sample program. +

    +

    + To support the new Artistic Style preprocessor option there are new makefiles and project files. Windows users + have a project file for Microsoft Visual C++ 2003 (version 7). Linux users have a new makefile that has several + new options. The location of both files is in the build directory. Be sure to read the "Artistic Style Install + Information" for the details. +

    +

    + Intel® is now offering it's C++ and Fortran compilers free for non-commercial use. Information is available + at the Intel® Software Development Products website. Click on the "Free Non-Commercial Download" link to see + if you qualify. The Intel Compilers on Windows and Linux require that other compilers be installed (Microsoft + Visual C++ or GNU gcc respectively). This is because the Intel Compilers require the header files, runtime libraries + and linkers distributed as part of these other compilers. If you want to use this compiler there is now a makefile + (makeintel) included with the project. See "Artistic Style Install Information" for instructions. +

    +

    +   +

    + +

    Artistic Style 1.19  (July 2006)

    + +

    + Most changes this release were again concerned with the options pad=oper and pad=paren. The formatting still worked + a little different if both options were declared than if only one was used. The problems with distinguishing the + multiplication operator from pointers, and of separating an object from the member access pointer (->) were + fixed. +

    +

    + A new option, unpad=paren, was added. This will undo the pad=paren, pad=paren-out and pad=paren-in options. It + can be used alone or with pad=paren-out or pad=paren-in. If used alone it will unpad all parens that have been + previously padded. If used with a paren padding option, the paren padding option will take precedence and only + the unnecessary padding will be removed. This will enable the paren padding to be changed in one formatting run. +

    +

    + Padding to paren headers (e.g. "if", "for", "while") was reinstated. This was done in previous releases if pad=oper + was used. Since most people used this option, the headers were usually padded. The general opinion was that they + looked better padded, especially in the case of "else if" statements. Since it is a minor point, it was not made + an option. +

    +

    + This is the third release of Artistic Style in the last four months. The reason for the frequent releases was + the number of pervasive errors in the formatting. In the future there will probably be two or three new releases + per year, or one every four to six months. It will take about three years to make all the changes that are planned + at this time.; The releases will be a combination of fixes, changes to formatting, and new features. +

    +

    +   +

    + + + + diff --git a/External/Tools/AStyle/doc/notes.html b/External/Tools/AStyle/doc/notes.html new file mode 100644 index 0000000000..0c59056303 --- /dev/null +++ b/External/Tools/AStyle/doc/notes.html @@ -0,0 +1,284 @@ + + + + + + Artistic Style - Release Notes + + + + + + + + +

    Artistic Style Release Notes

    + +

    +   +

    + +

    Artistic Style 2.06  (Pending)

    + +
      +
    • Add new Objective‑C options "pad-return-type" (-xq) and "unpad-return-type" (-xr).
    • +
    • Add new option pad-comma (#100).
    • +
    • Add removing spaces before a comma (#100).
    • +
    • Add formatting of C++14 single-quote digit separators (#337).
    • +
    • Improve align-method-colon to applied to Objective‑C method calls.
    • +
    • Improve recognition of C++11 uniform initializer brackets (#381).
    • +
    • Change align-method-colon short first line to align on the longest line instead of the first line.
    • +
    • Fix attaching "if" statements to a #else preprocessor directive (#356).
    • +
    • Fix not clearing global variables for a new file (#364).
    • +
    • Fix C# to recognize "using" as a header.
    • +
    • Fix C# to always recognize "forever" as a header.
    • +
    • Fix end of line comments for "pad-method-prefix" and "unpad-method-prefix".
    • +
    • Fix end of line comments for "pad-method-colon".
    • +
    • Refactoring: +
        +
      • Consolidate scattered ASFormatter conditional statements into a padParenObjC method.
      • +
      • Remove ASBase methods from being inlined as class definitions.
      • +
      • Portability changes for additional compiler support (#352).
      • +
      +
    • +
    + +

    Artistic Style 2.05.1  (December 2014)

    + +
      +
    • Fix incorrectly reporting files containing disabled formatting as being formatted.
    • +
    • Fix incorrect handling of quoted arguments in the options file (#321).
    • +
    • Fix error in identifying an enum return type as an enumeration (#322, 323).
    • +
    • Fix error in identifying an enum argument as an enumeration (#327).
    • +
    • Fix recognition of Qt keywords when used as variables in C++ (#329).
    • +
    • Fix recognition of a pointer in a C++ cast (#316).
    • +
    • Fix removing trailing whitespace after a changed pointer or reference cast.
    • +
    + +

    Artistic Style 2.05  (November 2014)

    + +
      +
    • Add new bracket style option "style=vtk" (#155).
    • +
    • Add new option "indent-preproc-block" to indent blocks of preprocessor directives (#21, #114, #229, + #242, #294).
    • +
    • Add new option, "dry-run", to run AStyle without updating the files (#184, #285).
    • +
    • Add new options, "html" (-!") and "html=###", to display the HTML help documentation in the default browser. +
    • +
    • Add tags "*INDENT-OFF*" and "*INDENT_ON*" to disable formatting of source code blocks + (#2, #47, #55, #78, #110, #176).
    • +
    • Add tag *NOPAD* to disable selected formatting on a single line.
    • +
    • Add '__attribute__ ((visibility ("default")))' to Linux exported functions.
    • +
    • Remove option "style=ansi" and make it depreciated (#146).
    • +
    • Remove fix for broken 'case' statements from release 2.02.1, Nov 21, 2011.
    • +
    • Improve Korean translation (#256).
    • +
    • Change shared libraries to include the version number as part of the file name (#264)
    • +
    • Change "help" display to stdout to allow piping and redirection (#63).
    • +
    • Change "version" display to stdout.
    • +
    • Change headers to include foreach, forever, Q_FOREACH, and Q_FOREVER (#98, #154).
    • +
    • Change compiler definition ASTYLE_NO_VCX (no Visual Studio exports) to ASTYLE_NO_EXPORTS.
    • +
    • Change shared library error handler argument from "char*" to "const char*".
    • +
    • Fix not recognizing noexcept, interrupt, and autoreleasepool as pre-command headers (#225, #259).
    • +
    • Fix formatting of C++11 uniform initializer brackets (#253, #257, #260, #284).
    • +
    • Fix to not automatically space pad C++11 uniform initializer brackets (#275).
    • +
    • Fix formatting of enums with leading commas (#159, #179, #270).
    • +
    • Fix formatting of logical && operator in class initializers (#290).
    • +
    • Fix flagging a 'const' variable as a 'const' method (#275).
    • +
    • Fix piping and redirection adding an extra character to the output (#245, #252, #305).
    • +
    • Fix "indent-modifiers" to attach class access modifiers to Horstmann style brackets.
    • +
    • Fix ASFormatter to correctly recognize the end of a C++ raw string literal (#261).
    • +
    • Fix to recognize C++11 "enum class" as an enum (#303).
    • +
    • Fix indent of C++11 "noexecpt" statements within a class (#260, #304).
    • +
    • Fix not resetting templateDepth when a template was not found (#295).
    • +
    • Fix formatting of multiplication in a block paren (#144).
    • +
    • Fix whitespace padding when formatting an rvalue references (#297).
    • +
    • Fix to recognize an rvalue reference without a name (#265).
    • +
    • Fix to not identify an operator overload method as a calculation (#296).
    • +
    • Fix concatenating multiplication with a pointer dereference (#291).
    • +
    • Fix recognition of a pointer dereference following a question mark (#213).
    • +
    • Fix extra space after a trailing reference type (#300).
    • +
    • Fix _asm blocks not being identified as a block opener and the variable not cleared on exit (#163).
    • +
    • Fix indentation of line comments before a "class" opening bracket.
    • +
    • Fix indentation of line comments before a "namespace" opening bracket.
    • +
    • Fix isBracketType() method to correctly process a NULL_TYPE.
    • +
    • Fix unpad-paren to recognize additional variables (#43, #132, #143).
    • +
    • Fix indentation of C# "let" statements.
    • +
    • Fix a few omissions with "fill-empty-lines".
    • +
    • Fix file read to read 64K blocks of data.
    • +
    • Refactor to un-obfuscate (clarify) the code, and improve design and decomposition: +
        +
      • Extract class Utf8_16 from ASConsole.
      • +
      • Replace Linux dependency on iconv with a Utf8_16 class for ASLibrary.
      • +
      • Move global "using" statements to the astyle namespace in astyle.h and ASLocalizer.h.
      • +
      • Move shared library declarations from astyle.h to astyle_main.h.
      • +
      • Move indentable macros from ASEnhancer to ASResource and create static pairs.
      • +
      • Simplify ASBeautifier procedure to identify the colon (:) type.
      • +
      • Major refactoring in ASBeautifier to create separate variables for an enum, a class statement and a class initializer.
        + This was needed to fix the processing of C++11 uniform initializers in a class initializer. +
      • +
      • Minor changes to ASFormatter and ASBeautifier based on results of the Clang analyzer.
      • +
      • Change several methods in astyle_main to "const".
      • +
      +
    • +
    + +

    Artistic Style 2.04  (November 2013)

    + +
      +
    • Add new programming language Objective‑C.
    • +
    • Add new bracket style option "style=google" (-A14).
    • +
    • Add new option "indent-preproc-cond" (xw) to indent preprocessor conditional statements (#118).
    • +
    • Add new bracket modify options "attach-namespaces", "attach-classes", "attach-inlines", and "attach-extern-c". +
    • +
    • Add new option "indent-modifiers" (-xG) to indent class access modifiers one-half indent (#130).
    • +
    • Add new option "remove-brackets" (-xj) to remove brackets from single line conditional statements.
    • +
    • Add new option "remove-comment-prefix" (-xp) to remove the leading '*' from multi-line comments.
    • +
    • Add new option "align-method-colon" (-xM) to align Objective‑C method colons.
    • +
    • Add new option "pad-method-colon=#" (-xP#) to space pad Objective‑C method colons.
    • +
    • Add new options "pad-method-prefix" (-xQ), and "unpad-method-prefix" (-xR) to pad the Objective‑C "-" and + "+" method prefix.
    • +
    • Add new dll entry point AStyleMainUtf16 for processing C# UTF-16 strings.
    • +
    • Add formatting of C++11 raw string literals (#222).
    • +
    • Add "style=knf" as an alternative to "style=linux".
    • +
    • Remove depreciated "bracket=" options.
    • +
    • Improve recognition and formatting of pointers and references (#174 and other changes).
    • +
    • Improve the recognition of block-opening brackets.
    • +
    • Improve code using a static code analyzer (#195).
    • +
    • Change "max-code-length" to include Objective‑C methods.
    • +
    • Change "indent-elseifs" and "break-blocks" to look ahead only if in command-type brackets (speed improvement). +
    • +
    • Fix linux bracket styles to break the opening bracket in inline function definitions (#185).
    • +
    • Fix indentation of switch block comments (#164).
    • +
    • Fix enums to indent with tabs when requested (#92, #121).
    • +
    • Fix formatting of rvalue reference without a name in a declaration (#219).
    • +
    • Fix "pad-first-paren-out" to not pad if the following parens are empty (#232).
    • +
    • Fix end-of-statement reset when comments follow closing bracket.
    • +
    • Fix the ASBeautifier active and waiting stacks to delete the ASBeautifier objects before deleting the pointers. +
    • +
    • Fix ASBeautifier "init" to delete the tempStack vectors before deleting the tempStack.
    • +
    • Fix Linux piping problem by changing "cin" input to build a stringstream before formatting.
    • +
    • Fix to identify the correct bracket type when 'extern "C"' is part of the enum definition.
    • +
    • Fix to clear 'extern "C"' variables when the block is closed.
    • +
    • Fix unindented 'extern "C"' to not indent when in a #else preprocessor directive.
    • +
    • Fix not always correctly formatting linux type brackets for enum blocks.
    • +
    • Fix align-pointer in a range-based for statement (#217).
    • +
    • Fix pointer-reference argument alignment to correctly position a following comment (#235).
    • +
    • Fix to not attach a bracket to a line ending in a backslash '\' (#186, #214, #220).
    • +
    • Fix to recognize templates using multiple lines (#85, #87, #136).
    • +
    • Fix formatting of template continuation lines (#85, #87, #136).
    • +
    • Fix to allow '^' as an array operator (#233).
    • +
    • Fix an "enum" argument being mistaken for an enumeration (#211).
    • +
    • Fix to recognize a non-instatement array after a "},{" sequence.
    • +
    • Fix "pad-oper" to not pad before a following comma.
    • +
    • Fix recognition of an operator when the calculation contains a bitwise "not" '~' (#166).
    • +
    • Fix to allow a preprocessor statement within a preprocessor define (#238).
    • +
    • Fix preprocessor comparison to check for whole words (#246).
    • +
    • Fix "add-brackets" when a line contains more than one paren pairs (#181).
    • +
    • Fix to allow Mac old CR line endings in the options file (#129).
    • +
    • Refactor to aid debugging and improve design and decomposition: +
        +
      • Move ALL preliminary indentation calculations to computePreliminaryIndentation() in ASBeautifier.
      • +
      • Move calculation of 'force tab' indents to preLineWS() in ASBeautifier.
      • +
      • Combine methods init() and init(ASSourceIterator*) in ASBeautifier.
      • +
      • Extract method adjustParsedLineIndentation() in ASBeautifier.
      • +
      • Extract method parseCurrentLine() in ASEnhancer. 
      • +
      • Remove astyle_main.cpp unused functions getFilesUnchanged, getOptionsFileRequired, and setOptionsFileRequired. +
      • +
      +
    • +
    + +

    Artistic Style 2.03  (April 2013)

    + +
      +
    • Add new option "indent=force-tab-x=#" (-xT#) to allow a tab length that different from the indent length (3430662). +
    • +
    • Add new option, "pad-first-paren-out" (xd), to pad only the first paren in a series on the outside (3350356). +
    • +
    • Add new option "max-code-length=#" (-xC#) to limit the length of code on a line.
    • +
    • Add new option "break-after-logical" (-xL) to modify a "max-code-length" line break for conditionals.
    • +
    • Add new option "close-templates" (-xy) to close whitespace in the angle brackets ">" of template + definitions.
    • +
    • Add formatting of C++ rvalue references (&&) using the existing "align-pointer" and "align-reference" + options.
    • +
    • Add formatting of C++/CLI managed pointers (the "^" character) to the "align-pointer" option.
    • +
    • Add translations for Dutch, Finnish, Italian, Japanese, Korean, Polish, Portuguese, Russian, Swedish, and Ukrainian. +
    • +
    • Remove byte-order-mark from ASLocalizer.cpp.
    • +
    • Change the short option for delete-empty-lines from "xd" to "xe".
    • +
    • Change the ASTYLE_LIB option to remove __declspec for a Visual C static library when ASTYLE_NO_VCX is also declared. +
    • +
    • Change to remove any space padding in  a pointer to pointer (**).
    • +
    • Fix "break-elseifs" to format one-line "if" and "else" statements the same as when the option is not used. +
    • +
    • Fix "break-elseifs" to break else-if statements when "keep-one-line-statements" also is requested.
    • +
    • Fix "break-elseifs" to correctly format comments preceding the else-if.
    • +
    • Fix C# not correctly identifying lambda expressions as a command-type bracket.
    • +
    • Fix C# preprocessor statements adding extra empty lines when "break-blocks" is used.
    • +
    • Fix C# padding "get" and "set" statements that are not headers when "break-blocks" is used.
    • +
    • Fix C# to recognize the "#line" statement.
    • +
    • Fix C++11 standard for range-based "for" loops (3458402, 3480095).
    • +
    • Fix C++11 standard for "enum" with a base type (3458402).
    • +
    • Fix C++11 standard for template closing angle brackets (no space required) (3495192).
    • +
    • Fix C/C++ keyword 'extern "C"' in a preprocessor causing an extra indent (1514844, 2953388, 2963382, 3093842, + 3467479).
    • +
    • Fix breaking after a switch "default" statement when "break-elseifs" is used without "keep-one-line-statements" + (3559365).
    • +
    • Fix in-statement arrays to indent correctly when they exceed the "max-instatement-indent".
    • +
    • Fix quote continuation sometimes being processed as a preprocessor directive (3445475).
    • +
    • Fix formatting of some conditional statements on a continuation-line.
    • +
    • Fix Java formatting of generics with wildcards (3428140).
    • +
    • Fix formatting of pointers and references to work with the new "max-code-length" option.
    • +
    • Fix formatting of pointers and references after a template close.
    • +
    • Fix formatting of empty attached brackets (3505002).
    • +
    • Fix C comments beginning a line breaking if they follow a semi-colon (3502700).
    • +
    • Fix "pad-header" not padding "return" and "throw" statements (3509134).
    • +
    • Fix recognition problems with templates.
    • +
    • Fix "struct" return type being mistaken for a struct.
    • +
    • Fix "pad-oper" in java for-each loop.
    • +
    • Fix recognition of a macro multi-line comment (3414970).
    • +
    • Fix bracketTypeStack entries added by #if and #else if the # is separated from the word.
    • +
    • Fix C++ breaking a line on an access modifier in a one-line block when "keep-one-line-blocks" is used. +
    • +
    • Fix memory leak when "ascii" option is used.
    • +
    • Fix memory leak when a preprocessor statement is used without a closing #endif.
    • +
    • Fix preprocessor directive to allow compiling with mingw-x64 compiler.
    • +
    • Fix redirection on Windows so it does not hang when Linux line ends are used (3514712).
    • +
    • Fix redirection on Linux to output the correct line ends (3514712).
    • +
    • Fix non-portable return value on locale name (3452574).
    • +
    • Fix assert errors caused by not checking the text length on the return from peekNextText().
    • +
    • Fix spelling of "depreciated" in help message (3454735).
    • +
    • Refactor to improve design and decomposition: +
        +
      • Fix warning messages from Visual Studio static code analysis.
      • +
      • Fix warning messages from cppcheck, except for constructor uninitialized variables (false positive).
      • +
      • Remove astyle_main.h dependency from ASLocalizer.h
      • +
      • Remove appendChar() from the inline functions.
      • +
      • Extract methods for pointer or reference alignment in ASFormatter.
      • +
      +
    • +
    + +

    +   +

    +

    + Previous releases are available in the Release + Notes Archives. +

    +

    +   +

    + +

    + + +

    + +

    +   +

    + + + + + diff --git a/External/Tools/AStyle/doc/notesArchives.html b/External/Tools/AStyle/doc/notesArchives.html new file mode 100644 index 0000000000..5bb695c030 --- /dev/null +++ b/External/Tools/AStyle/doc/notesArchives.html @@ -0,0 +1,1215 @@ + + + + + + Artistic Style - Release Notes Archives + + + + + + + + +

    Artistic Style Release Notes Archives

    + +

    +   +

    + +

    Artistic Style 2.02.1  (November 2011)

    + +
      +
    • Add to C# the recognition of pointers and address-of operators.
    • +
    • Improve recognition of pointers and references (3,314,499, 3,298,204, and 2,990,608).
    • +
    • Improve alignment of a reference to a pointer (*&).
    • +
    • Fix crash with "align-pointer=type" when pointer to pointer (**) starts a new line (3,431,431).
    • +
    • Fix breaking after a "case" statement when "break-elseifs" is used without "keep-one-line-statements" (3,421,577, + and 3,314,247).
    • +
    • Fix "pad-oper" used with "keep-one-line-statements" not padding operators in a one-line "case" statement. +
    • +
    • Fix not recognizing a "pointer dereference" or "address of" that follows a comment (3,431,431).
    • +
    • Fix "break-blocks" used with "delete-empty-lines" not correctly breaking blocks on the first run.
    • +
    • Fix "pad-oper" not padding the alternate comparison operators "and" and "or" (3,342,373).
    • +
    + +

    Artistic Style 2.02  (May 2011)

    + +
      +
    • Add new program module, ASLocalizer, containing language translations.
    • +
    • Add new short option prefix "x" to allow for expansion of short options.
    • +
    • Add new command line only option "ascii" (-I).
    • +
    • Add new bracket style, "style=pico" (-A11).
    • +
    • Add new bracket style, "style=lisp" (-A12).
    • +
    • Add new option "align-reference=" (-W#) (3,136,744).
    • +
    • Add new options ignore-exclude-errors (-i) and ignore-exclude-errors-x (-xi) (3,259,910).
    • +
    • Add new option "style=break" for Allman style brackets.
    • +
    • Add new option "style=attach" for Java style brackets.
    • +
    • Add processing of UTF-16 files by converting to UTF-8 and back to UTF-16.
    • +
    • Add Microsoft C++ extensions for try-finally and try-except statements (3,222,216).
    • +
    • Add "override" and "sealed" modifiers (Visual C specific) to preCommandHeaders vector (3,167,978).
    • +
    • Add "case" and "default" to the list of formatters in ASFormatter (3,276,212).
    • +
    • Remove "indent-brackets" and "indent-blocks" from the valid options.
    • +
    • Remove "volatile" from headers and remove comparisons in ASBeautifier.
    • +
    • Change "delete-empty-lines" short option from "x" to "xd".
    • +
    • Change "max-instatement-indent" maximum value from 80 to 120 (3,255,930).
    • +
    • Change "brackets=horstman" to "brackets=run-in", used for both Horstmann and Pico styles.
    • +
    • Change C enumerations to allow in-statement indents (3,280,454).
    • +
    • Change functions setting the "indent-brackets" and "indent-blocks" variables from public to protected.
    • +
    • Change to indent lines beginning with an assignment operator (3,292,880).
    • +
    • Change to abort if UTF-32 files are detected.
    • +
    • Change "Cannot set native locale" error message from cout to cerr (3,139,873).
    • +
    • Fix Linux infinite loop when a directory name is entered instead of a file name.
    • +
    • Fix trying to process directories as files when a wildcard is used without recursive (3,134,108).
    • +
    • Fix processing a "const" variable as a "const" method when it follows a header (3,168,156).
    • +
    • Fix indentation of a one-line block that follows a header.
    • +
    • Fix breaking a preprocessor define that has code after a comment end (3,132,531).
    • +
    • Fix "pad-oper" padding a dereference that follows a C-style cast (3,259,713).
    • +
    • Fix "unpad-parens" not recognizing an xor (^) operator (3,285,639).
    • +
    • Fix "break-blocks" procedure for "case" and "default" headers.
    • +
    • Fix "add-brackets" adding brackets to the "while" of a "do-while" loop (3,267,880).
    • +
    • Fix "add-brackets" adding brackets to an empty statement.
    • +
    • Fix "pad-paren" used with "align-pointer=name" incorrectly adding an extra space.
    • +
    • Fix not clearing a flag when a "?" conditional is included in an "if" statement (2,989,638).
    • +
    • Fix incorrect indentation when "volatile" modifier is used (3,279,856).
    • +
    • Fix indentation for Microsoft "#pragma region" and "#pragma endregion" preprocessor directives.
    • +
    • Fix not printing a zero for formatted numbers.
    • +
    • Fix indentation of a class opening bracket followed by a class modifier on the same line when indent‑namespaces + and indent‑classes are used.
    • +
    • Refactor to aid debugging, improve speed, and improve the design and decomposition: +
        +
      • Extract method processProcessor() from beautify() in ASBeautifier.
      • +
      • Extract method computePreliminaryIndentation() from beautify() in ASBeautifier.
      • +
      • Extract method parseCurrentLine() from beautify() in ASBeautifier.
      • +
      • Remove unnecessary copies to outBuffer variable in ASBeautifier.
      • +
      • Add preCommandHeaders vector to ASBeautifier and remove the "const" modifier comparisons.
      • +
      • Change static vectors to member variables.
      • +
      • Add isDigit() function to avoid the assert statements in Visual C.
      • +
      +
    • +
    + +

    Artistic Style 2.01  (November 2010)

    + +
      +
    • Add recognition of language characters supported by the native locale.
    • +
    • Add formatting of numbers according to the native locale.
    • +
    • Add checksum verification to source file output.
    • +
    • Add formatting of MFC macros BEGIN_DISPATCH_MAP, BEGIN_EVENT_MAP, and BEGIN_PROPPAGEIDS.
    • +
    • Add error message if --recursive is used without a wildcard in the file name.
    • +
    • Add private (unusable) copy constructors for classes with dynamic allocation.
    • +
    • Add error message if the "cin" stream cannot be processed because a pipe is used.
    • +
    • Improve recognition of ARRAY_TYPE brackets.
    • +
    • Improve formatting of multi-line comments when the number of leading spaces must be changed.
    • +
    • Improve formatting of embedded SQL when the number of leading spaces must be changed.
    • +
    • Improve recognition of C++ templates.
    • +
    • Change --style=linux to always use a minimum conditional indent of one-half the indent length.
    • +
    • Change --pad-oper to pad operators in block parens.
    • +
    • Change to indent OpenMP pragmas with the code.
    • +
    • Change to display all (instead of one) option errors before abort.
    • +
    • Change the second argument of the fpError typedef from "char*" to "const char*".
    • +
    • Change Linux Makefiles to allow external values for CFLAGS and LDFLAGS.
    • +
    • Change all destructors to virtual.
    • +
    • Fix crash when --break-blocks is used and there is no closing bracket.
    • +
    • Fix deleting the previous line when a closing bracket follows a comment close.
    • +
    • Fix not recognizing text in quotes when identifying struct access modifiers.
    • +
    • Fix not popping the paren stack when a bracket precedes an end of line comment.
    • +
    • Fix not breaking a closing bracket when empty parens are enclosed in a single line block.
    • +
    • Fix indenting of C# anonymous statement closing bracket.
    • +
    • Fix recognition of C# non in-statement arrays.
    • +
    • Fix breaking single line blocks for C# abstract methods.
    • +
    • Fix not always clearing isNonInStatementArray flag.
    • +
    • Fix indenting "case" statements in a preprocessor definition when --indent-preprocessor is not requested.
    • +
    • Fix not recognizing the "volatile" type qualifier as a keyword.
    • +
    • Fix class initializers not being recognized as an in-statement indent.
    • +
    • Fix indenting Java abstract methods when "new" starts the line and brackets are broken.
    • +
    • Fix broken initializer lines (ending with comma) when there is more than one space after the type.
    • +
    • Fix --brackets=attach inserting a bracket inside comments following a preprocessor statement.
    • +
    • Fix --brackets=attach attaching an array bracket from a one line block to the previous line.
    • +
    • Fix --brackets=horstmann not breaking a comment line when the comment ends the line with a bracket.
    • +
    • Fix --pad-oper to recognize all * and & operators within a function call.
    • +
    • Fix --unpad-paren to recognize * and & operators within a function call.
    • +
    • Fix --pad-paren used with --delete-empty-lines causing a space to be added at end of line in some cases.
    • +
    • Fix --pad-paren padding a closing paren followed by a block paren.
    • +
    • Fix --add-brackets when a header is followed by a semi-colon.
    • +
    • Fix --align-pointer to pad or unpad pointers followed by parens or comments.
    • +
    • Fix --align-pointer to pad or unpad pointers following a scope resolution operator.
    • +
    • Fix --align-pointer to pad or unpad pointers that end the line.
    • +
    • Fix --align-pointer used with --pad-parens-out causing a space to be padded for each run.
    • +
    • Fix --break-blocks used with --delete-empty-lines causing an assert error when end of file is reached.
    • +
    • Fix --break-blocks used with --delete-empty-lines causing an assert error for some combinations of comment lines. +
    • +
    • Fix --break-blocks used with --delete-empty-lines causing a duplicate line in some cases.
    • +
    • Fix --break-blocks used with --delete-empty-lines not always breaking opening blocks.
    • +
    • Fix --break-blocks used with --delete-empty-lines not always deleting empty lines for closing blocks.
    • +
    • Fix --break-blocks used with --fill-empty-lines not always correctly filling empty lines in a switch statement. +
    • +
    • Fix --unpad-paren used with --pad-paren-in not padding between opening parens when multiple parens are used. +
    • +
    • Fix --pad-oper incorrectly padding a template with a default parameter.
    • +
    • Fix ASBeautifier findOperator() method to recognize a C# lambda (=>) operator.
    • +
    • Fix ASFormatter nextLine() method to output an entire operator instead of individual characters.
    • +
    • Fix incorrectly identifying "*" as pointers in block parens.
    • +
    • Fix MinGW -Wshadow warnings.
    • +
    • Fix VS2010 "string subscript out of range" asserts.
    • +
    • Refactor: +
        +
      • Remove template definition for parseOptions() by using a vector reference instead of iterators as function arguments. +
      • +
      • New ASOptions class to encapsulate global functions used by both the console and library builds.
      • +
      • Replace argc and argv in processOptions() with a vector to simplify test cases.
      • +
      • Replace IS_OPTION and IS_OPTIONS macros with ASOptions methods.
      • +
      • Replace GET_PARAM and GET_PARAMS macros with ASOptions methods.
      • +
      • Extract ASFormatter methods checkIfTemplateOpener() and isClosingHeader().
      • +
      +
    • +
    + +

    Artistic Style 1.24  (February 2010)

    + +
      +
    • Add new option ‑‑brackets=horstmann (-g) to place run‑in statements on the same line as an opening + bracket.
    • +
    • Add new style --style=horstmann (-A9) using horstmann brackets to predefined styles.
    • +
    • Add new option ‑‑add-brackets (-j) and --add-one-line-brackets (-J) to place brackets around one line + statements.
    • +
    • Add new style --style=1tbs and --style=otbs (-A10) using linux brackets and the --add-brackets option to predefined + styles.
    • +
    • Add new option ‑‑pad‑header (‑H) from Mario Gleichmann to insert space padding after paren + headers.
    • +
    • Add new option ‑‑align‑pointer=type (-k1), ‑‑align‑pointer=middle (-k2) and + ‑‑align‑pointer=name (-k3) from J P Nurmi.
    • +
    • Add new option ‑‑lineend=windows (-z1), ‑‑lineend=linux (-z2) and ‑‑lineend=macold + (-z3) from MrTact.
    • +
    • Add new option ‑‑indent‑col1‑comments (-Y) to indent C++ comments beginning in column + one.
    • +
    • Add formatting of embedded SQL statements in C/C++.
    • +
    • Add rejecting 16 or 32 bit file encoding and display a warning message.
    • +
    • Remove .tmp file by using ostringstream instead of ofstream.  
    • +
    • Remove depreciated option style=kr.
    • +
    • Remove trace file from ASFormatter and use 'cout' instead.
    • +
    • Improve assembler statement processing to include extended assembly.
    • +
    • Improve assembler statement processing to include Microsoft specific lines and blocks.
    • +
    • Improve recognition of pointers and references vs. arithmetic operators.
    • +
    • Improve recognition of arithmetic operators for --pad-oper (-p) option.
    • +
    • Change "class" initializer statement to one indent.
    • +
    • Change "class" initializer statement continuation lines to align on the first initializer.
    • +
    • Change predefined styles to allow changes to spaces per indent.
    • +
    • Change --style=stroustrup to 5 spaces per indent.
    • +
    • Change --style=linux default minimum conditional indent to 4.
    • +
    • Change default formatting to leave paren headers unchanged instead of inserting space padding.
    • +
    • Change ‑‑unpad‑paren to unpad headers unless padding is requested.
    • +
    • Change NONE_MODE brackets to allow run-in statements from horstmann type brackets.
    • +
    • Change array brackets to allow run-in statements from horstmann type brackets.
    • +
    • Change --min-conditional-indent to allow for statements preceded by a bracket (horstmann brackets).
    • +
    • Change ASBeautifier and ASFormatter to output an entire comment line instead of characters.
    • +
    • Change quote formatting in ASFormatter to output the entire string instead of single characters.
    • +
    • Change from Ettl Martin for cppcheck compliance.
    • +
    • Change space padding of line end comments to one space when the proper alignment cannot be maintained.
    • +
    • Change spaces per tab minimum value from 1 to 2.
    • +
    • Change the help display of "Formatting Options" to "Formatting Options" and "Padding Options".
    • +
    • Fix MinGW file globing by moving the _CRT_glob variable outside the astyle namespace.
    • +
    • Fix default line end processing to always output consistent line ends.
    • +
    • Fix identification of pointer dereferences and address-of indicators.
    • +
    • Fix memory leaks by changing static vectors to static vector pointers so the object can be deleted.
    • +
    • Fix console build trying to use Unicode character set.
    • +
    • Fix stringEndsWith method when end is longer than the string.
    • +
    • Fix --exclude option rejecting a full file path.
    • +
    • Fix --verbose option when used with --quiet.
    • +
    • Fix --quiet option for excluded files and directories.
    • +
    • Fix --indent-classes for C++ structs containing access modifiers.
    • +
    • Fix formatting of variable types with multiple names.
    • +
    • Fix from Christian Stimming for alignment of << and >> operators.
    • +
    • Fix in-statement indent of "enum class".
    • +
    • Fix 'if' statement following an 'else' sometimes attaching to a comment.
    • +
    • Fix recognition of non-indent line comments in the first two lines of a source file.
    • +
    • Fix non-instatement array to recognize an empty bracket.
    • +
    • Fix indenting non-indent line comments in an event table or message map.
    • +
    • Fix to move comments when breaking one line blocks and -keep-one-line-statements is used.
    • +
    • Fix to recognize parens in template definitions.
    • +
    • Fix recognition of class initializer when class description contains multiple lines.
    • +
    • Fix from Colin D Bennett for 64-bit comparison.
    • +
    • Fix console error procedure to terminate on an error.
    • +
    • Fix 'return' statement for padding or not padding arithmetic operators.
    • +
    • Fix C# 'delegate' and 'unchecked' not being identified as keywords.
    • +
    • Fix occasional array formatting problem with one-line blocks when indent-brackets is used.
    • +
    • Fix to check for max-instatement-indent when the previous line ends with an opening paren.
    • +
    • Fix predefined style options to allow the use of --indent=tab (-t) and --indent=force-tab (-T) options.
    • +
    • Fix --in-statement indent to allow for non-indentation tabs in the line.
    • +
    • Fix formatting problems with non in-statement arrays.
    • +
    • Fix infinite loop when preprocessor #else is missing #if.
    • +
    • Fix Borland string compares to check for comparison past the end of string.
    • +
    • Fix ‑‑fill‑empty‑lines when ‑‑indent=force‑tab is also used.
    • +
    • Fix break-blocks formatting with preceding mixed comments and line comments.
    • +
    • Fix not breaking a closing bracket following a comment.
    • +
    • Fix attached brackets to not change empty brackets when both are on the same line.
    • +
    • Fix attached brackets sometimes deleting a previous comment line when the bracket cannot be attached.
    • +
    • Fix attached brackets attaching a closing header to a single line block.
    • +
    • Fix broken brackets breaking a single line block before a comment.
    • +
    • Fix 'extern' keyword using in-statement indents instead of tab indents.
    • +
    • Fix errno checking problem on old OpenVMS versions.
    • +
    • Fix deleting a space before a line end comment when attaching 'else' to a closing bracket.
    • +
    • Fix adding a space before a line end comment when the comment is preceded by a tab.
    • +
    • Fix to leave tab indentation on no-indent line comments.
    • +
    • Fix comments when a bracket is added or removed from a line.
    • +
    • Fix indenting preprocessor statements in a wxWidgets or MFC macro.
    • +
    • Fix memory leak reporting of global and static class member vectors.
    • +
    • Refactor to implement unit testing and improve design and decomposition: +
        +
      • Replace multiple line conditional statements with a method to eliminate complex "not" (!) logic.
      • +
      • Change to call standardizePath when a vector entry is built.
      • +
      • Change g_console from an object to an object pointer to allow rebuilding the object.
      • +
      • Change ASConsole variables to private with getters and setters.
      • +
      • Change processOptions method to return to main instead of exiting.
      • +
      • Move formatFile call from getFilePaths to main.
      • +
      • Move peekNextChar function from ASBeautifier to ASBase.
      • +
      • Move multi-line comment alignment from ASBeautifier to ASFormatter.
      • +
      • Encapsulate global variable isModeManuallySet.
      • +
      • Extract methods formatOpeningBracket, formatClosingBracket and isCurrentBracketBroken.
      • +
      • Extract methods formatCommentOpener and formatCommentBody.
      • +
      • Extract methods formatLineCommentOpener and formatLineCommentBody.
      • +
      • Extract methods formatQuoteOpener and formatQuoteBody.
      • +
      • Extract methods processFiles and writeOutputFile.
      • +
      • Extract methods processSwitchBlock and findCaseColon.
      • +
      • Extract method updateExcludeVector.
      • +
      • Extract method copyTempStacks.
      • +
      • Extract method formatCinToCout.
      • +
      • Extract method isLineBreakBeforeClosingHeader.
      • +
      +
    • +
    + +

    Artistic Style 1.23  (February 2009)

    + +
      +
    • Add --brackets=stroustrup (-u) to bracket types.
    • +
    • Add --style=stroustrup to predefined styles.
    • +
    • Add --style=whitesmith to predefined styles.
    • +
    • Add --style=banner to predefined styles.
    • +
    • Add --style=k&r and --style=k/r to predefined styles.
    • +
    • Add --style=allman and --style=bsd to predefined styles.
    • +
    • Change --style=kr to --style=java.
    • +
    • Add short options -A1 thru -A8 for predefined styles.
    • +
    • Change the following long options to eliminate duplicate keys (the short options have not changed). +
        +
      • --force-indent=tab=# changed to --indent=force-tab=#
      • +
      • --brackets=break-closing changed to --break-closing-brackets
      • +
      • --pad=oper changed to --pad-oper
      • +
      • --pad=paren changed to --pad-paren
      • +
      • --pad=paren-out changed to --pad-paren-out
      • +
      • --pad=paren-out changed to --pad-paren-in
      • +
      • --unpad=paren changed to --unpad-paren
      • +
      • --one-line=keep-statement changed to --keep-one-line-statements
      • +
      • --one-line=keep-blocks changed to --keep-one-line-blocks
      • +
      +
    • +
    • Add new option --indent=force-tab (assumes tab setting is 4).
    • +
    • Add new option --delete‑empty‑lines to delete the empty lines within a function.
    • +
    • Add new option --formatted (-Q) to display only the files that are formatted.
    • +
    • Change --convert-tabs to replace tabs with spaces and maintain the correct spacing.
    • +
    • Change --indent-blocks to indent only blocks within a function.
    • +
    • Change --indent-blocks to NOT indent the opening bracket for namespaces, classes, and interfaces.
    • +
    • Change --indent-blocks and --indent-brackets to NOT indent namespaces unless --indent-namespaces is used.
    • +
    • Change --indent-blocks and --indent-brackets to always break closing headers so the 'else' aligns with the corresponding + 'if'.
    • +
    • Change --indent-blocks and --indent-brackets to be mutually exclusive (--indent‑blocks will be used). +
    • +
    • Fix --indent-blocks indenting a java 'interface' statement. 
    • +
    • Fix --indent-blocks to indenting opening brackets in a java method containing a 'throws' clause.
    • +
    • Fix --indent-blocks indenting opening brackets in a java static constructor.
    • +
    • Fix --indent-blocks formatting in a C++ const function.
    • +
    • Fix --indent‑brackets indenting brackets within comments.
    • +
    • Move set-up of predefined styles to ASFormatter so the style options will override all other options.
    • +
    • Fix --else-if statements to join by default.
    • +
    • Fix to always space pad after semi‑colons.
    • +
    • Fix --pad-oper to space pad all commas.
    • +
    • Fix --break‑blocks and --break‑blocks=all options. +
        +
      • Fix to recognize a semi‑colon as end of block when brackets are not used.
      • +
      • Fix to break comments preceding a block so that comments are kept with the block.
      • +
      • Fix 'for' statement semi‑colons being mistaken for the end of a statement.
      • +
      • Fix bracketFormatMode of  NONE_MODE to break closing headers.
      • +
      • Fix incorrect breaking of a block that follows a comment.
      • +
      • Fix breaking of opening and closing headers preceded by a comment.
      • +
      • Fix breaking of statements when comments follow a header block.
      • +
      • Fix incorrectly breaking blocks for namespaces, interfaces, and classes.
      • +
      • Fix incorrectly breaking blocks for access modifiers when keep-one-line-statements is used.
      • +
      • Fix to NOT break single line blocks.
      • +
      • Fix breaking a closing 'while' statement in a do-while block.
      • +
      • Fix preprocessor directives not resetting all variables.
      • +
      • Fix peekNextText function not correctly identifying an end of file condition.
      • +
      +
    • +
    • Add C# lambda expression arrow '=>' to list of operators so pad‑oper will not separate.
    • +
    • Add C# '??' to list of operators so pad‑oper will not separate.
    • +
    • Fix C# to identify 'add' and 'remove' methods as command type brackets.
    • +
    • Fix C# indentation of closing headers 'set' and 'remove'.
    • +
    • Fix C# to identify methods containing a 'where' keyword as block headers. 
    • +
    • Fix C# files to recognize preprocessor statements.
    • +
    • Fix C# indentation following a #region statement containing a keyword.
    • +
    • Fix C# to recognize nullable types so --pad‑paren will not separate (e.g. 'int?').
    • +
    • Fix C# to recognize non-generic default values (e.g. 'default(int)').
    • +
    • Fix C# indentation when a class declaration contains multiple class statements.
    • +
    • Fix C# linux bracket placement for an  interface statement.
    • +
    • Fix C# --break-elseifs also breaking 'catch' statements.
    • +
    • Fix C# --break-blocks breaking of 'set' and 'remove' statements.
    • +
    • Fix Java static constructor not being identified as a command type bracket.
    • +
    • Fix Java 'new' array not having an in statement indent.
    • +
    • Refactor NONE_MODE in ASFormatter to use common procedures with other bracket types.
    • +
    • Refactor astyle_main to improve maintainability. +
        +
      • New class ASConsole to encapsulate console variables.
      • +
      • New header file astyle_main.h
      • +
      • Move console only functions to ASConsole class.
      • +
      • New functions processOptions and processFilePath to improve decomposition.
      • +
      +
    • +
    • Apply patches from Eran Ifrah to remove memory leaks.
    • +
    • Apply patches from Max Horn for the unary plus operator.
    • +
    • Fix initialization of vector stack objects to remove memory leaks.
    • +
    • Add comma (,) to valid options separators in the options file.
    • +
    • Change to display all (instead of one) --exclude errors before abort.
    • +
    • Change astyle namespace to include all of astyle_main except the functions called externally.
    • +
    • Change licensing comments from LGPL version 2.1 to LGPL version 3.
    • +
    • Change JNI function call from GetVersion to AStyleGetVersion.
    • +
    • Remove 'extern' keyword from headers, nonParenHeaders, PreBlockStatements, and  PreCommandHeaders. +
    • +
    • Fix not always space padding a closing bracket.
    • +
    • Fix not space padding a closing header when breaking one line statements.
    • +
    • Fix --keep-one-line-blocks breaking closing headers on broken brackets.
    • +
    • Fix incorrectly attaching a bracket inside a comment after the end of a statement.
    • +
    • Add number of output lines processed to the --verbose option display.
    • +
    • Remove trace file from ASEnhancer and use 'cout' instead.
    • +
    • Replace INIT_CONTAINER and DELETE_CONTAINER macros with template functions.
    • +
    • Replace IS_A macro with isBracketType function.
    • +
    • Add GCC extended operators '<?' and '>?' (min and max) to list of operators.
    • +
    • Fix indentation and breaking of lines in struct and class bit fields.
    • +
    • Fix indentation of struct definitions.
    • +
    • Add 'union' to preDefinitionHeaders.
    • +
    • Change preBlockStatements and preDefinitionHeaders to be dependent on file type.
    • +
    • Fix a single quote mark used as an apostrophe in preprocessor directives being processed as a quotation.
    • +
    • Fix linux bracket formatting in nested namespaces.  
    • +
    • Fix --pad‑paren‑in not converting a tab to spaces if convert‑tabs is requested.
    • +
    • Fix incorrectly breaking a closing bracket when a header is not present.
    • +
    • Fix inserting duplicate bracketTypeStack entries when preprocessor directives contain unmatched brackets.
    • +
    • Fix bracketFormatMode of  NONE_MODE to correctly break single line blocks. 
    • +
    • Fix --keep‑one‑line‑blocks breaking 'if' statements when --break‑elseifs is used.
    • +
    • Remove inefficiencies for speed improvement. +
        +
      • Reduce calls to frequently used functions by first checking for specific requirements.
      • +
      • New class ASBase to inline frequently used functions and eliminate duplication between classes.
      • +
      • Change ASEnhancer from inherited to embedded to eliminate scope resolution requirements.
      • +
      • Change ASFormatter to output words instead of characters.
      • +
      • Resequence operator vectors and add new findHeader and findOperator functions.
      • +
      +
    • +
    • Fix NONE_MODE brackets to break a statement on the same line as an opening broken bracket.
    • +
    • Add 'errno' message for file and directory errors in the Linux build.
    • +
    • Add error checking for file remove and rename procedure.
    • +
    • Fix Linux abort for file sizes over 2 GB.
    • +
    • Fix searching the entire directory when only one file is requested.
    • +
    • Change --preserve-date increment to 2 units for Visual Studio 2008.
    • +
    + +

    Artistic Style 1.22  (April 2008)

    + +
      +
    • New --recursive (-r, -R) option to recursively process sub directories.
    • +
    • New --exclude option to exclude files and sub directories from processing.
    • +
    • New --verbose (-v) option to display optional information, such as release number and statistical data.
    • +
    • New --quiet (-q) option to suppress all informational messages.
    • +
    • Change --version short option to -V.
    • +
    • Change --convert‑tabs short option to -c.
    • +
    • Change to NOT write a new or backup file if a file contents has not changed, 
    • +
    • Change console file input procedure to create a .tmp file and preserve the input file on a crash.
    • +
    • Add Java Native Interface (JNI) for developers.
    • +
    • New peekNextLine and peekReset functions in ASStreamIterator.
    • +
    • Change ASEnhancer static variables to class member variables and reset them in the init() function.
    • +
    • Patch from Jens Krinke to fix stack underrun when the number of closing brackets exceed opening brackets.
    • +
    • Fix stack underrun when the number of closing parens exceed opening parens.
    • +
    • Fix processing of C/C++ string literal continuation lines.
    • +
    • Patch from Emilio Guijarro to correct padding and formatting of C# 'foreach' statements.
    • +
    • Fix C# to correctly identify accessor calls as not being headers.
    • +
    • Fix C# accessors (get and set) to break when breaking single line blocks.
    • +
    • Modify template procedure to process C# generics.
    • +
    • Fix processing of C# verbatim string literals.
    • +
    • Fix indentation of C# methods containing 'base' or 'this' keywords.
    • +
    • Fix indentation of C# methods containing generics.
    • +
    • Fix indentation of C# enums containing a type.
    • +
    • Fix indentation of C# catch blocks when 'catch' is a non-paren header.
    • +
    • Fix C# breaking of linux style brackets for methods containing generics and methods containing accessors.
    • +
    • Allow @ as a C# identifier prefix.
    • +
    • Fix assert error on C# UTF-8 files when the byte-order mark (BOM) is not followed by a space or a comment. +
    • +
    • Fix nested preprocessor formatting by adding waitingBeautifierStack, activeBeautifierStack, waitingBeautifierStackLengthStack, + and activeBeautifierStackLengthStack to the ASBeautifier copy constructor and class destructor.
    • +
    • Fix ASStreamIterator end of file procedure for ASTYLE_LIB option.
    • +
    • Add pragma statements for Intel compiler to disable specific warning messages.
    • +
    • Move line number accumulators from ASSourceIterator class to private in ASStreamIterator class.
    • +
    • Fix reset of ASFormatter isInPreprocessor flag when \ is followed by a blank line.
    • +
    • Fix cin, cout, and cerr continuation lines to be indented.
    • +
    • Fix indentation of inner classes that inherit a base class.
    • +
    • Add astyle_main.cpp function declarations to astyle_main.cpp.
    • +
    • Change global variable prefix from '_' to 'g_'.
    • +
    • Inline selected ASStreamIterator functions.
    • +
    • Fix brackets=attach from attaching a bracket to a preprocessor directive.
    • +
    • Fix brackets=attach and brackets=linux breaking in an array immediately after a preprocessor directive.
    • +
    • Modify Jack Handy's wildcmp() function to make Windows comparisons case insensitive.
    • +
    • Fix not indenting a bracket when an attached bracket is broken and the following line is a no-indent comment. +
    • +
    • Add error message if 'options=' file cannot be opened.
    • +
    • Bypass colon enclosed in quotes when processing 'case' statements.
    • +
    • Fix brackets=none not always breaking a closing bracket when breaking single line blocks.
    • +
    • Fix padding of header words that are in a definition (array).
    • +
    • Fix indentation of line immediately after a case statement where the object is enclosed in parens.
    • +
    • Fix breaking of multiple case statements when the object is enclosed in parens.
    • +
    • Fix indentation when there is more than one case statement on a line.
    • +
    • Remove processing for shouldBreakLineAfterComments (no longer used).
    • +
    • Fix brackets=break not breaking if before a comment that is not at end of line.
    • +
    • Fix brackets=none not space padding before a bracket.
    • +
    • Fix brackets=break and brackets=none not breaking comments following a bracket.
    • +
    • Fix blank line not being trimmed if inside a comment.
    • +
    • Fix brackets=break incorrectly space padding a preceding preprocessor statement line.
    • +
    • Fix brackets=attach attaching two consecutive opening brackets before an end-of-line comment.
    • +
    • Fix break-blocks not inserting a blank line if a bracket preceding a comment was moved to the following line. +
    • +
    • Add 'X' to selected ASEnhancer variables to prevent conflict with ASBeautifier.
    • +
    • Fix brackets=none not space padding after a closing bracket that precedes a closing header.
    • +
    • Change minimum indent edit from 2 spaces to 1 space.
    • +
    • Change to check for preprocessor definitions in C/C++ files only.
    • +
    • Fix padding of template definitions when pad=oper is used.
    • +
    • Fix comment formatting in nested preprocessor definitions.
    • +
    • Fix header dependencies and warning messages for Linux GCC 4.3.
    • +
    • Use file name from disk for output to maintain correct case in Windows.
    • +
    • Fix pad=operator padding a negative value in a case statement.
    • +
    • Fix incorrect identification of bracket type following a struct statement.
    • +
    • Fix indentation of blank lines outside of brackets when --fill‑empty‑lines is used with --indent‑blocks + or --indent‑brackets.
    • +
    • Fix ASFormatter not identifying comments in preprocessor directives.
    • +
    • Fix brackets=attach deleting a preceding blank line in array type brackets.
    • +
    + +

    Artistic Style 1.21  (June 2007)

    + +
      +
    • New function, formatArrayBrackets, to improve array formatting and indentation.
    • +
    • Attach brackets to lines with end-of-line comments.
    • +
    • Break brackets from lines with end-of-line comments without bringing the comments with them.
    • +
    • Move ASFormatter and ASBeautifier static initialization from constructor to "init" function to allow for changes + in the file type.
    • +
    • Add --preserve-date (-Z) option.
    • +
    • New functions formatBrackets, padOperators and PadParens to improve decomposition.
    • +
    • Add identification of file mode (C, C#, or Java) to file open procedure.
    • +
    • Keywords in headers now depend on file mode (C, C#, or Java) and object type (formatter or beautifier).
    • +
    • Remove short options -c (mode=c) and -j (mode=java) since the mode is now set automatically from the file extension. +
    • +
    • Change Linux bracket formatting for header files.
    • +
    • Fix formatting of empty blocks.
    • +
    • Expand BracketType definition.
    • +
    • Fix "do not change" bracket mode inconsistencies with other bracket formatting.
    • +
    • Remove mode=java from Java predefined style.
    • +
    • Change long option --errors-to-standard-output to --errors-to-stdout.
    • +
    • Fix breaking of struct variable declaration.
    • +
    • Add support for OpenVMS compiler.
    • +
    • Inline the ASBeautifier function isLegalNameChar.
    • +
    • Fix no-indent of block comments starting in column 1 or 2.
    • +
    • Fix formatting of Java anonymous class defined as a method call parameter (bracket within a paren).
    • +
    • Fix indentation for Java "for each" statement.
    • +
    • Fix bracket being attached to a preprocessor directive.
    • +
    • Fix extra indent of single line blocks when a previous line probation header is found.
    • +
    • Fix formatting of block comments when continuation lines have different leading whitespace characters.
    • +
    • Fix deleting a blank line before a bracket when brackets=attach.
    • +
    • Fix segmentation fault on preprocessor continuation line followed by an empty line.
    • +
    • Fix bad bracket indent that sometimes occurs when brackets=attach and it cannot be attached.
    • +
    • Fix trimming of comment lines.
    • +
    • Fix incorrect identification of "new" operator pointers as calculations.
    • +
    • Fix incorrect identification of assignments as command type bracket.
    • +
    • Fix incorrect indentation of pointers following a dot operator or pointer.
    • +
    • Fix attaching "else if" statements to a single line block.
    • +
    • Fix header recognition problem when header is proceeded by a tab instead of a space.
    • +
    • Fix line break when colon is followed by a comment.
    • +
    • Fix ASBeautifier not identifying a template definition.
    • +
    • Change indents around the end of line to two indents.
    • +
    • Change header includes to fix header dependencies for Linux GCC 4.3.
    • +
    • Add output line number for debugging.
    • +
    • Add filename to trace output.
    • +
    • Add trace for arrays.
    • +
    • Add trace for bracketType.
    • +
    • Fix no-indent comment in a #else preprocessor directive.
    • +
    • Fix block comment continuation line indent when block comments do not start the line.
    • +
    • Adjust position of block comments (/*) when padding is added or deleted.
    • +
    • Fix incorrect formatting if "return" is included in a function name.
    • +
    • Fix incorrect padding if template depth is greater that one and pad=oper is used.
    • +
    • Fix incorrect bracket type identification when bracket is followed by a comment.
    • +
    • Fix incorrect bracket type identification when a "const" method is declared.
    • +
    • Fix incorrect bracket type identification when pre-definition header is inside a paren.
    • +
    • Fix deleting a space when attaching a bracket with line comments.
    • +
    • Fix indentation when the conditional "?" operator is used in a single line statement.
    • +
    • Fix indentation when single line "if" statement is used.
    • +
    • Add pointers, multiply operators, and selected variables to do not unpad in paren unpad procedure.
    • +
    • Return exit code 0 for --version and --help.
    • +
    + +

    Artistic Style 1.20.2  (February 2007)

    + +
      +
    • Fix problems with the new stream I/O procedure added in release 1.20.1: +
        +
      • Fix adding an extra blank line at end of document.
      • +
      • Fix line ending on last line when cin and cout option is used.
      • +
      +
    • +
    + +

    Artistic Style 1.20.1  (January 2007)

    + +
      +
    • The following changes were made to improve processing for Mac OS X platforms: +
        +
      • Remove Makefile linker option -s and add a separate "strip" command.
      • +
      • Open console input and output streams as binary to allow Linux line ends on a Windows platform.
      • +
      • Change stream I/O procedure to allow for Mac OS 9 line endings.
      • +
      • Change output stream end of line from endl so output stream is not flushed with each write.
      • +
      • Change information messages from cerr to cout.
      • +
      • Removed messages when I/O is to cin and cout to accommodate TextWrangler.
      • +
      +
    • +
    + +

    Artistic Style 1.20  (January 2007)

    + +
      +
    • Call importOptions() from function AStyleMain() to allow slop in options parameters.
    • +
    • New makefiles for GCC and Intel with new compile options.
    • +
    • New project file for Visual C with new compile options.
    • +
    • Change comments to reflect the GNU Lesser General Public License.
    • +
    • Indent message maps for MFC and event tables for wxWidgets.
    • +
    • Fix incorrect formatting for an empty comment.
    • +
    • Fix "Unknown option" in default options file when last line does not contain CR or LF.
    • +
    • Patch from Dieter Bayer to fix case indent when a scope resolution operator is used.
    • +
    • Change long option --brackets=break-closing-headers to --brackets=break-closing.
    • +
    • Add short option -y for --brackets=break-closing.
    • +
    • Add short option -e for --break-elseifs.
    • +
    • Add short option -w for --indent-preprocessor.
    • +
    • Add short option -f for --break-blocks.
    • +
    • Add short option -F for --break-blocks=all.
    • +
    • Remove the backup file after formatting when --suffix=none.
    • +
    • Show total time at end of job.
    • +
    • Improved error handling for invalid options with ASTYLE_LIB.
    • +
    • Add function AStyleGetVersion() to ASTYLE_LIB option.
    • +
    • Change preprocessor macro from ASTYLE_GUI to ASTYLE_LIB.
    • +
    • Add astyle namespace to ASEnhancer.
    • +
    • Add #include <ctype.h> for Red Hat distribution of GCC 3.2 (prior to Jan 2004).
    • +
    • Remove commented-out code.
    • +
    + +

    Artistic Style 1.19  (July 2006)

    + +
      +
    • Add unpad=paren option.
    • +
    • Always pad paren headers (e.g. 'if', 'for', 'while').
    • +
    • Fix problem of pad=oper working different if pad=paren is declared.
    • +
    • Add additional tests to distinguish the multiplication operator from pointers.
    • +
    • Fix padding parens before a member access pointer (->).
    • +
    • If space padding has changed, move end-of-line comments to the original column, if possible.
    • +
    • Move potential calculation decision to outside of operator padding function.
    • +
    • Fix duplication of last line of source if a final endline is not present.
    • +
    • Fix class initializer not indented on last line if bracket is attached.
    • +
    • Fix identification of templates contained in parens.
    • +
    • Fix one line block occurring before end of class.
    • +
    • Fix line added after one line block with bracketFormatMode = NONE_MODE.
    • +
    • Add needed variables to ASBeautifier copy constructor.
    • +
    • Trim end of line for multi-line comments.
    • +
    • Add a breakLine before paren checks (needed for unpad=paren option).
    • +
    • Add trace file to ASFormatter.
    • +
    • Move formatting message from end to beginning of formatting.
    • +
    • Move the building of vectors to ASResource. Vectors for classes ASBeautifier and ASFormatter should now have the + same values.
    • +
    • Move debugging variable inLineNumber from ASFormatter to ASBeautifier.
    • +
    • Bypass char processing for UTF8 characters in ASBeautifier.
    • +
    • Move switchVariables struct from ASEnhancer to the header file.
    • +
    • Remove preprocessorHeader vector (not used).
    • +
    • Remove variable isInConst (not used).
    • +
    • Remove commented-out code.
    • +
    + +

    Artistic Style 1.18  (June 2006)

    + +
      +
    • The following changes were made for the option pad=oper: +
        +
      • Does not remove extra spaces from formatted expressions.
      • +
      • Does not pad opening parens on the outside.
      • +
      • Does not remove leading spaces from multi-line comments.
      • +
      • Does not pad negative numbers.
      • +
      • Does not add a space to the end of preprocessor directives.
      • +
      • Will not pad operators inside block parens [].
      • +
      +
    • +
    • The following changes were made for the option pad=paren: +
        +
      • Formats correctly with or without pad=oper.
      • +
      • Does not add a space for each additional run if pad=oper is not used.
      • +
      • Outside of opening paren is padded correctly.
      • +
      • Inside of closing paren is padded correctly.
      • +
      • Does not pad block parens [].
      • +
      • Added short option P, previously used for pad=all.
      • +
      +
    • +
    • Added new options pad=paren-out (d) and pad=paren-in (D).
    • +
    • Removed option pad=all.
    • +
    • Add short option V for convert-tabs.
    • +
    • Added bounds checking to options containing parameters.
    • +
    • Display a message when a default options file is used.
    • +
    • Replaced IS_PARAM_OPTION(S) macros with overloaded isParamOption. Fixed compare problem with short param options. +
    • +
    • Fix EOF problem with default options file.
    • +
    + +

    Artistic Style 1.17  (May 2006)

    + +
      +
    • The following changes were made for processing bracketFormatMode = NONE_MODE: +
        +
      • Removed the function isFormattingEnabled() and always performed the formatting.
      • +
      • Removed the formatting bypass for NONE_MODE.
      • +
      • Fix brackets always being broken in the 2 cases where NONE_MODE formatting was done.
      • +
      • Added new functions to support the processing of NONE_MODE brackets.
      • +
      • Made other minor changes necessary for correct NONE_MODE processing.
      • +
      +
    • +
    • Changed indent cases option to indent the entire case block.
    • +
    • Changed to output Windows or Linux line endings.
    • +
    • Added ASEnhancer module for case statement indenting.
    • +
    • Corrected errors in identifying options indent=tab=, and force-indent=tab=.
    • +
    • Corrected errors in identifying options min-conditional-indent=, and max-instatement-indent=.
    • +
    • Improved error and information messages.
    • +
    • Added capability to compile as a console program, shared library, or static library.
    • +
    • Fixed problem with semicolons and parens being put on a line by themselves.
    • +
    • Fixed spaces being added before a line comment.
    • +
    • Fixed blank line added after some preprocessor statements.
    • +
    • Fixed preprocessor statements not being trimmed.
    • +
    • Do not indent line comments that begin in column 1 or 2.
    • +
    • Fixed indentation problem with ending }; of class statements.
    • +
    • Changed nextLine() function to eliminate char buffer limits.
    • +
    • Moved Windows default options file to %USERPROFILE%.
    • +
    • Removed NEW operators to prevent memory leaks.
    • +
    • Fixed space before the semicolon in return ; statement.
    • +
    • Fixed extra space that was sometimes added when pad operators was used.
    • +
    • Removed string parameter from IS_PARAM_OPTION.
    • +
    • Added forward declaration of parseOption() to eliminate compile error.
    • +
    • Added input line number counter for debugging.
    • +
    • Add statements to check for markers if break-blocks or break-blocks=all is used.
    • +
    • Remove warnings for signed/unsigned mismatch.
    • +
    • Removed COMPARE macro and used string compare.
    • +
    • Removed compiler_defines.h.
    • +
    • Removed USES_NAMESPACE declaration.
    • +
    + +

    Artistic Style 1.16

    + +
    + There was no release 1.16. +
    + +

    Artistic Style 1.15.3 (7 March 2002)

    + +
      +
    • Bug fix in handling of brackets after line-comments.
    • +
    • Bug fix: C# add/remove event property headers now properly formatted.
    • +
    + +

    Artistic Style 1.15.2 (2 March 2002)

    + +
      +
    • Bug fixes in exception handling phrases, e.g. multiple catches and try..finally.
    • +
    + +

    Artistic Style 1.15.1 (2 March 2002)

    + +
      +
    • Bug fix: C# properties are now formatted properly.
    • +
    + +

    Artistic Style 1.15.0 (2 March 2002)

    + +
      +
    • Added support for C#.
    • +
    • Artistic Style is now licensed only under the GNU Public License (GPL).
    • +
    • Compilation under G++ 3.0 now works properly.
    • +
    • Bug fix: Opening brackets that appear at the beginning of a line immediately after an empty line comment are now + handled properly, and not appended as part of the line comment.
    • +
    • Bug fix: Brackets inside comments are now not mis-indented within the comment.
    • +
    + +

    Artistic Style 1.14.1 (2 June 2001)

    + +
      +
    • Bug fix: : '<' and '>' symbols within template declarations (e.g. 'foo<bar*, xoo>') are now left unpadded + in the padding modes.
    • +
    • Bug fix: Fixed false recognizing of headers within larger words (e.g. 'catch' in 'gcatch').
    • +
    + +

    Artistic Style 1.14.0 (1 June 2001)

    + +
      +
    • Bug fix: Fixed indentation of statements within preprocessor '#if...' statements.
    • +
    • Bug fix: Templates are now not broken from their bodies.
    • +
    • Bug fix: '<' and '>' symbols within template definitions (e.g. 'template<class T>') are now left unpadded + in the padding modes.
    • +
    + +

    Artistic Style 1.13.8 (13 April 2001)

    + +
      +
    • Bug fix: Fixed indentation of multiple nested non-block brackets, such as in multi bracketed static array declarations. +
    • +
    + +

    Artistic Style 1.13.7 (6 April 2001)

    + +
      +
    • New option:'--force-indent=tab=#' (or 'T#') instructs astyle to indent using tabs in all the pre-statement white + space, including areas astyle's '--indent=tab' prefers to indent using spaces, such as white space in multi-line + statements.
    • +
    • Bug fix: Fixed unwanted empty line insertions between empty blocks (e.g. '{}') and closing brackets that come + immediately after them.
    • +
    • Bug fix: Fixed unwanted empty line insertions immediately after colons (e.g. 'default:', 'label:', ...)
    • +
    + +

    Artistic Style 1.13.6 (24 January 2001)

    + +
      +
    • Bug fix: Preprocessor lines now remain unpadded in padding modes.
    • +
    + +

    Artistic Style 1.13.5 (24 January 2001)

    + +
      +
    • Bug fix: Fixed the insertion of phantom empty lines immediately after {} blocks.
    • +
    • Bug fix: Bare open brackets ('{') with no preceding headers are now broken appropriately from their preceding + code lines in the 'attach' and 'linux' bracketmodes.
    • +
    • Bug fix: Fixed operator recognition for long operators such as '>>=', '<<= '.
    • +
    + +

    Artistic Style 1.13.4 (24 January 2001)

    + +
      +
    • Bug fix: L" unicode strings are now handled properly in padding modes.
    • +
    • Bug fix: Fixed the padding around '-' operators (which went sour somewhere in the past).
    • +
    • Bug fix: Fixed the handling of exponent numbers (e.g. 12.2e+2) in padding modes. The fix enables 'e+' to be regarded + as part of the exponent.
    • +
    + +

    Artistic Style 1.13.3 (23 January 2001)

    + +
      +
    • Line that contain both headers and their following non-header code (e.g. 'if (isFoo) doBar();') are now broken + by default into multiple lines. To keep these lines as single lines, use '--one-line= keep-statements'.
    • +
    • Added the new option '--break-elseifs' which breaks 'else if()' statements into multiple lines.
    • +
    • The option block breaking options now works properly with the padding options.
    • +
    • Various minor bug fixes.
    • +
    + +

    Artistic Style 1.13.2 (21 January 2001)

    + +
      +
    • Added the new option '--brackets=break-closing-headers'. When this option is added to either '--brackets=attach' + or '--brackets= linux', astyle breaks closing headers (e.g. 'else', 'catch') from their preceding closing brackets. +
    • +
    • '--break-blocks' and '--break-blocks= all' now correctly handle blocks that appear immediately before closing + brackets, and do not append empty lines between them and the closing brackets.
    • +
    + +

    Artistic Style 1.13.0 (27 September 1999)

    + +
      +
    • Moved back to odd-minor-numbered development versions, and even-minor-numbered stable versions.
    • +
    • Added the new option '--break-blocks' which breaks apart unrelated blocks, labels, classes, etc.
    • +
    • Added the new option '--break-blocks=all' which also breaks apart blocks of closing headers, such as 'else', 'catch', + etc.
    • +
    • Fixed indentation handling of labels and class-definition identifiers such as 'public:', 'protected:', ... (thanks + to Daryn Adler for his patch)
    • +
    • Fixed indentation of nested class definitions. (thanks to Daryn Adler for his patch)
    • +
    • Added the new option '--indent-preprocessor' which (surprisingly) tries to reindent C/C++ preprocessor macro lines. + Astyle should do an pretty nice indentation job if the macro code is sane, but don't expect miracles for horrid + macro definitions...
    • +
    + +

    Artistic Style 1.11.6 (27 September 1999)

    + +
      +
    • Improved indentation of lines containing single-line blocks.
    • +
    + +

    Artistic Style 1.11.5 (25 September 1999)

    + +
      +
    • Improved the bug fix for a 'const' keyword bug which resulted in wrong indentation of methods that are declared + const.
    • +
    + +

    Artistic Style 1.11.4 (18 September 1999)

    + +
      +
    • Improved handling of single colons (':') in class headers, e.g. class Foo : public Bar { ... }
    • +
    • Improved handling of single colons (':') in method (constructor) headers, e.g. Foo::Foo(int a) : Bar(a)
    • +
    + +

    Artistic Style 1.11.3 (16 September 1999)

    + +
      +
    • Fixed a serious bug in the formatting of brackets, introduced in 1.11.2.
    • +
    + +

    Artistic Style 1.11.2 (10 September 1999)

    + +
      +
    • Fixed an indentation bug in statements that contain the 'const', that resulted in wrong indentation of array blocks + that where declared const. (Thanks Daniel!)
    • +
    • Fixed an indentation bug that could arise in lines that appear immediately after several preprocessor commands. + (Thanks Daniel!).
    • +
    • Fixed a bug that inserted an empty line after closing brackets if a comment appeared immediately prior to the + closing bracket. (Thanks Ed!)
    • +
    • Fixed a bug that eliminated empty lines between closing brackets and immediately following opening brackets. (Thanks + Ed!)
    • +
    + +

    Artistic Style 1.11.1 (3 September 1999)

    + +
      +
    • Fixed a bug that inserted an empty line at the begining of source files.
    • +
    + +

    Artistic Style 1.11.0 (3 September 1999)

    + +
      +
    • Astyle now filters out line-feeds ('\r') before begining to parse lines. This should take care of bizarre formatting + that existed when moving source files from Windows (which breaks lines with a linefeed AND newline ("\r\n") to + unix (which breaks lines only with newlines).
    • +
    • The "struct", "static" and "synchronized" keywords are now finally handled correctly in both the contexts of block + headers AND simple keywords.
    • +
    • Better treatment of precompiler lines that end with backslashes, and the lines that immediately follow them. +
    • +
    • The '--indent-classes' (or '-C') option now works correctly (again...).
    • +
    • Series of short command-line options (e.g. "-b -s4 -C") are now parsed correctly.
    • +
    + +

    Artistic Style 1.10.4  (27 July 1999)

    + +
      +
    • Fixed a MAJOR bug (inserted in 1.10.3) that resulted wrong handling of double-colons ('::') in C++.
    • +
    + +

    Artistic Style 1.10.3 (24 July 1999)

    + +
      +
    • Fixed a bug (inserted yesterday) that resulted in unwanted line breaks before closing-brackets.
    • +
    • Fixed a bug in the handling of 'static' blocks in java.
    • +
    • Added the new option '--indent-cases' (or '-K') for indenting 'case XXX:' lines so they are flush with their following + code lines.
    • +
    • Added the new option '--fill-empty-lines' (or '-E') which fills empty lines with the white-space of their previous + line.
    • +
    + +

    Artistic Style 1.10.2 (23 July 1999)

    + +
      +
    • Fixed a series of related bugs that resulted in certain cases of lacking line breaks after close-brackets, and + colons. Thanks Jeroen!
    • +
    + +

    Artistic Style 1.10.1 (18 July 1999)

    + +
      +
    • Fixed a bug (introduced in astyle 1.10.0) that can result in missing line breaks before closing brackets if they + appear immediately after comments. Thanks Larry!
    • +
    + +

    Artistic Style 1.10.0 Release (14 July 1999)

    + +
      +
    • Improved handling of empty bracket blocks ( e.g.{ } ). Thanks Michael!
    • +
    + +

    Artistic Style 1.10.0 Prerelease (4 July 1999)

    + +
      +
    • Fixed a bug in the in-statement indentation algorithm which resulted in sub-optimal indentation of multiple-line + conditional statements that immediately follow headers such as 'if', 'else if', 'while', etc... As a result, the + current in-statement indentation is finally what it should have been long ago - MUCH better then in the last stable + versions.
    • +
    • The "linux" bracket style (in which definition brackets are broken while code brackets are attached) has been + fixed, and should finally work correctly.
    • +
    • Artistic Style can now parse both C/C++ and Java files in the same command. Unless a specific language mode is + specified (e.g. --style=java or --style=c), astyle will now automatically set the language mode according to each + file's suffix (java mode for the '.java' suffix , c mode otherwise).
    • +
    • Multiple statements in a single line (e.g. aaa; bbb; fff;) are now broken up by default.
    • +
    • Added the option '--one-line=keep-statements' (or '-o') that keeps multiple + statements in a single line attached, thus countering the default break detailed above.
    • +
    • Changed the option previously called '--keep-one-line-blocks' to '--one-line=keep-blocks', + for similarity with the new option above.
    • +
    • Changed the short option name of the option '--errors-to-standard-output' from '-o' + to '-X'.
    • +
    • Up to now, Artistic Style always inserted a minimal indent of twice the current selected indent + size inside multi-line conditional headers ('if', 'while' ...), so that it would be clear where the headers end + and the code after them begins. The current version adds the option '--min-conditional-indent=#' + (or '-m#') that sets the absolute minimal indent between conditional headers and their multiple-line + conditional statements. If this option is not specified, the default indent remains twice the current selected + indent size.
      + For example, This option should come very handy in code that already has brackets after EVERY conditional statement + (even if just one line is in that bracket...) - in such a case, it would be wise to set --min-conditional-indent=0 + since the brackets already make it clear where the header ends and the code begins...
    • +
    • Added the ability to set the assumed tab size when in '--indent-tab' mode by using '--indent-tab=#' + or '-t#' and replacing the # with the wanted size. If the size is not specified, + the size of each tab is assumed to be 4 spaces long.
    • +
    + +

    Artistic Style 1.8.2 (18 March 1999)

    + +
      +
    • Fixed pointer handling problems in ASBeautifier that led to crashes when parsing preprocessor commands.
    • +
    • Fixed the problem in locating the default options file in the directory pointed to by $HOME or %HOMEPATH% when + these system variables do not contain an '/' (or '\' ...) at their end.
    • +
    • Fixed inverse insertion of spaces vs. tabs when in -t mode. (Thanks Brian!)
    • +
    • Got rid of those pesky C4786 warnings when compiling under Visual C++ (Thanks John!)
    • +
    + +

    Artistic Style 1.8.1 (9 March 1999)

    + +
      +
    • Changed the '--style=k&r' option to '--style= kr' , so that linux/unix machines don't misinterpret the '&' + as a background processing command.
    • +
    + +

    Artistic Style 1.8.0 (3 March 1999)

    + +
      +
    • Added support for predefined styles. Current supported styles are: ansi, k&r, linux, gnu, java. + these can be set by using '--style=THESTYLE' (e.g. '--style=linux').
    • +
    • Added '--indent-blocks' (or -G) option, which adds indentation to entire blocks, including their + brackets, in similar fashion to the standard gnu style.
    • +
    • Added option '--brackets=linux' (or '-l') which breaks definition-block brackets, but attaches command-block + brackets.
    • +
    • Padding can now be set separately for operators alone('-p' or '--pad=oper'), parentheses alone ('--pad=paren) + or both ('-P' or '--pad=all').
    • +
    • Artistic Style looks for a default options file in the following order:
      + 1. The contents of the ARTISTIC_STYLE_OPTIONS environment variable if it exists.
      + 2. The file called .astylerc in the directory pointed to by the HOME environment variable ( i.e. + $HOME/.astylerc ).
      + 3. The file called .astylerc in the directory pointed to by the HOMEPATH environment variable + ( i.e. %HOMEPATH%\.astylerc ).
      + If a default options file is found, the options in this file will be parsed BEFORE the command-line options. Options + within the default option file may be written without the preliminary '-' or '--'. Indentation within #if , #else + and #endif precompiler commands now works correctly even if the program lines between these precompiler commands + contain non-pared brackets.
    • +
    • Improved handling of labels (e.g. 'exit:'). By default, labels are now flushed completely to the left. Labels + can also be indented to one indent LESS than current standard indentation by using the new option '--indent-labels' + (or '-L') .
    • +
    • Fixed handling of the 'operator' keyword when it is preceded by a non space character (such as '&' or '*'). +
    • +
    • Fixed wrong bracket handling after 'throws' statements.
    • +
    • Fixed wrong indentation of single-line blocks. These where indented 1 indent to much.
    • +
    • Fixed wrong indentation of headers in internal classes (java mode). These where indented 1 indent to little. +
    • +
    • The option ' --errors-to-standard-output' now has the one-letter option '-o'.
    • +
    • Fixed bug which resulted in an unneeded indent in function-declarations in which function-variables are declared + before the function declaration and are preceded by the 'static' keyword. Thanks Scott.
    • +
    + +

    Artistic Style 1.6.0 (5 January 1999)

    + +
      +
    • Fixed zero indentation that resulted when a '-suffix' option was set after a '--indent=spaces' (or '-s') option. +
    • +
    • Wrong options are now announced.
    • +
    • Changed default indentation to NOT automatically indent class blocks and switch blocks. Instead, the new options + '--indent-classes' (or '-C') and '--indent-switches' (or '-S') should be used. The option '--indent-switches' + replaces the old option '--flush-switches'.
    • +
    + +

    Artistic Style 1.4.1 (4 January 1999)

    + +
      +
    • Fixed ability to write options without the preceding '--' in the default options file.
    • +
    • Added one-letter options to most options that had only long-options in version 1.4.0.
    • +
    • Added a '-v' or '--version' option that writes the current Artistic Style version.
    • +
    + +

    Artistic Style 1.4.0 (3 January 1999)

    + +
      +
    • MAJOR NEW CHANGE IN THE FORMAT OF OPTIONS:
      + Options are now either short one-letter options starting with '-', or long multi-letter options + starting with '--'. The Short one-letter options MAY BE ATTACHED TOGETHER. Thus, writing '-bps4' is the same as + writing '-b -p -s4'.
      + Many options that have up to now had a 2 letter format now retain only their long format. I truly believe that + the combination of attached-one-letter options PLUS a default option's file containing long-letter-options related + to style will be much easier to work with than the previous setup.
    • +
    • Added support for a default options file (pointed to by the ARTISTIC_STYLE_OPTIONS environment + variable).
    • +
    • Changed downloading method from the server. From now, there will be specific directories containing the latest + stable sources, stable binaries, and development sources.
    • +
    • Space padding ('-p' or '--pad') now works correctly (1) around semicolons and commas, (2) between headers that + require parentheses after them (such as 'if', 'while'...)and those parentheses, and (3) after parentheses (unless + immediately followed by a ';' or ',' or '.').
    • +
    • From now on, namespace blocks are NOT indented by default. To indent namespace blocks use the new '--indent-namespaces' + option.
    • +
    • Added options '--errors-to-standard-output' for redirection of standard-error to standard-output from within Artistic + Style, and '--suffix=' for specifying a suffix other than '.orig' to append to original filenames.
    • +
    • Corrected indentation of 'default' in switch statements. (Up to now, this only worked correctly in java mode...). +
    • +
    + +

    Artistic Style 1.2.0 (19 December 1998)

    + +
      +
    • Artistic Style 1.2.0 is the first stable result of a new version numbering, in which development versions are + numbered with an odd minor number (such as 1.1.x), and stable versions are numbered with an even number (1.2.x). + Thus, version 1.2.0 accumulates all the additions/changes of the 1.1.x development versions of Artistic Style. +
    • +
    • A new '-ol' formatting mode that eliminates breaking of one-line blocks.
    • +
    • Fixed a SERIOUS bug, which resulted in wrong formatting of brackets ('{', '}') that came IMMEDIATELY AFTER definition + type brackets, (e.g. brackets that come right after 'class', 'interface', 'name-space', etc ...). This bug was + mistakenly introduced when I set out to correctly space-pad pointer and reference signs, somewhere in version + 0.9.x.
    • +
    • Fixed unwanted elimination of final empty lines.
    • +
    • Fixed broken indentation of virgin opening-brackets that occur immediately after a previous closing-bracket. +
    • +
    • Fixed space-padding to not insert a space in front of ':' characters unless they are a part of a '? ... : ' statement. +
    • +
    + +

    Artistic Style 1.0.5  (11 December 1998)

    + +
      +
    • 'extern' blocks now handled correctly.
    • +
    • Fixed handling of ^= in '-p' mode.
    • +
    • Win32 executables now contain wildcard expansion. *** Look at the README.TXT for info + on how to include wildcard expansion abilities when compiling Artistic Style under Win32. (Thanks for the info + on wildcard-expansion enabling, Nat!!!)
    • +
    + +

    Artistic Style 1.0.4  (2 December 1998)

    + +
      +
    • Fixed unwanted space-padding around urinary minuses and '-' symbols within exponents + (e.g. 2.5E-5) when using the '-p' option.
    • +
    + +

    Artistic Style 1.0.3  (1 December 1998)

    + +
      +
    • Control characters now remain in the indented file.
    • +
    • Fixed a bug in which long quoted white-space sequences where mistakenly eliminated + in the '-p' mode.
    • +
    • Fixed unwanted line-breaks in '-ab -p' mode, that in some cases occurred between '//' + and the rest of a line comment.
    • +
    • Fixed handling of '>>=', '<<= ' in '-p' mode.
    • +
    + +

    Artistic Style 1.0.2 (27 November 1998)

    + +
      +
    • Fixed a SERIOUS bug of missing needed line-breaks in lines immediately after line-comments + when in '-ab' mode.
    • +
    • Support for the 'finally' header.
    • +
    • lines that contain only white-space now become empty lines.
    • +
    + +

    Artistic Style 1.0.1  (26 November 1998)

    + +
      +
    • Fixed a SERIOUS bug, which lacked a needed line-break between closing brackets and + the headers that follow them (e.g. '} else') when in '-bb' mode. In fixing the bug, I used a variation on a patch + sent by Richard Bullington - THANKS!
    • +
    • Fixed a set of SERIOUS bugs which inserted an empty line into both the start and end + of the reindented file.
    • +
    • Improved documentation of formatting options in the file astyle.html .
    • +
    + +

    Artistic Style 1.0.0 (24 November 1998)

    + +
      +
    • Indented files now retain the original file name, while the original + pre-indented file is saved with a ".orig"at its end. Thus, after the call "astyle -bb foo.cpp", + the newly indented file will be called "foo.cpp", while a file called "foo.cpp.orig" + will contain the original pre-indented file.
    • +
    • Artistic Style may now be used and /or modified and/or distributed under EITHER + the "Artistic License", or the GNU General Public License (GPL).
    • +
    • Methods with headers that end with 'const' are now properly indented.
    • +
    • Cleaner, more robust, and better documented source code.
    • +
    + +

    Artistic Style 0.9.2

    + +
      +
    • Fixed a serious bug which led to a maximal supported source code line size of 128 + characters!!!
    • +
    • Maximal supported line size is now 1024 characters.
    • +
    • Fixed a serious bug in the handling of brackets inside '#define' statements.
    • +
    • Fixed a serious bug in which '#include' files containing slashes (i.e. #include <foo_dir/foo> ) where space-padded + when using option '-p' on C, C++ files.
    • +
    + +

    Artistic Style 0.9.1

    + +
      +
    • Much improved space-padding around pointers ('*') and references ('&') and the + 'operator' key-word in C and C++ source files when using the '-p' space padding option.
    • +
    • Fixed several pointer handling bugs which led to potential core dumps.
    • +
    • Version 0.9.1 now includes all the abilities I am planning for the final 1.0 version, and should be looked + at as the first pre-release version of Artistic Style.
    • +
    + +

    Artistic Style 0.9.0

    + +
      +
    • Added a formatting layer (ASFormatter.cpp) around the indentation + layer (ASBeautifier.cpp). +
    • +
    • As a result, the following formatting capabilities have been added: +
        +
      • Bracket ('{' and '}') placement in either ANSI C style or Java style.
      • +
      • Space padding around operators, i.e. (1+2)*3-4 becomes ( 1 + 2 ) * 3 - 4.
      • +
      +
    • +
    • Fixed the 'tab' elimination bug introduced in ASBeautifier 0.8.2.
    • +
    • Fixed a bug which under-indented class headers containing inheritance info.
    • +
    + +

    ASBeautifier 0.8.2

    + +
      +
    • Fixed indentation problem in brackets around 'struct', and 'union' blocks.
    • +
    • Added recognition for '\' characters in the end of lines.
    • +
    • Improved indentation of post-method-declaration variable initializations.
    • +
    • Several minor bug fixes.
    • +
    + +

    ASBeautifier 0.8.1

    + +
      +
    • Fixed an important bug in pointer arithmetic which resulted both in phantom indentation errors, and in core-dumps + when trying to indent java files.
    • +
    + +

    ASBeautifier 0.8.0

    + +
      +
    • This is the first public release of ASBeautifier. It is a direct port to C++ of JSBeautifier + 1.1.1, PLUS extensions to for C++ indentation.
    • +
    • So far, very little beta-testing has been done for the C++ extensions. This should + change extremely with the open-source release (this was the case with JSBeautifier...), so expect ASBeautifier + to become bug-free fast!!!
    • +
    • The C++ source code is not yet written in optimal quality. I rushed a little so that I could release this initial + release as soon as possible. This will soon change.
    • +
    +

    +   +

    + + + + diff --git a/External/Tools/AStyle/doc/scripts.html b/External/Tools/AStyle/doc/scripts.html new file mode 100644 index 0000000000..21841178c7 --- /dev/null +++ b/External/Tools/AStyle/doc/scripts.html @@ -0,0 +1,94 @@ + + + + + + Artistic Style - Scripts + + + + + + + + +

    Artistic Style Scripts

    + +

    +   +

    +

    + The following are scripts to support the Artistic Style program. They are in various computer languages for multiple + platforms. +

    + +

    Scripts

    + +

    + + astyle-clean.py  is a Python script to clean a directory tree by + moving Artistic Style backup files to a separate directory. This allows Artistic Style to create backup files + without cluttering your source directories. There are four variables at the start of the script that need to be + set for each application. The script will move or copy backup files to a backup directory maintaining the original + directory structure. New backup files will be copied over the old so you will always have the most current backup. +

    +

    + + astyle-clean.sh  is a Linux shell script to clean a directory tree + by moving Artistic Style backup files to a separate directory. This allows Artistic Style to create backup files + without cluttering your source directories. There are four variables at the start of the script that need to be + set for each application. The script will move or copy backup files to a backup directory maintaining the original + directory structure. New backup files will be copied over the old so you will always have the most current backup. +

    +

    + + astyle-clean.bat  is a Windows batch file to clean a directory + tree by moving Artistic Style backup files to a separate directory. This allows Artistic Style to create backup + files without cluttering your source directories. There are four variables at the start of the script that need + to be set for each application. The script will move or copy backup files to a backup directory maintaining the + original directory structure. New backup files will be copied over the old so you will always have the most current + backup. +

    +

    + + astyle.pl  is a Mac Perl script to indent source files in TextWrangler + and BBEdit using Artistic Style. Selected text from the editor can be passed to Artistic Style and replaced with + the reformatted text. Save the script in the "Unix Filters" directory (you need to restart TextWrangler to see + new scripts). Then simply highlight the text you would like to indent, choose the script from the Shebang (#!) + menu, and the text will be immaculately formatted. You can add Artistic Style options to the "my $astyle" line + in the script. +

    +

    + + indent-commit.pl  is a Perl script to integrate Artistic Style + with a CVS repository check-in. Before code is checked in, Artistic Style is automatically called so that the + repository files have a consistent style. This script was posted on the web site several years ago and probably + needs to be updated. +

    +

    + + astyle-hooks.el  is an Emacs Lisp script containing hooks to convert + Emacs default styles to Artistic Style default styles. There are hooks for C++, Java, and C# files. The C# hook + requires the csharp-mode.el file from + csharpmode on Google Project Hosting. For best results Artistic Style should use the options ‑‑min‑conditional‑indent=0 + (‑m0) and ‑‑max‑instatement‑indent=50 (‑M50). Emacs does not seem to have + an option equivalent to these. The formatting for Emacs and Artistic Style will not be identical but should be + reasonably close. +

    +

    +   +

    + +

    + + +

    + +

    +   +

    + + + + + diff --git a/External/Tools/AStyle/doc/styles.css b/External/Tools/AStyle/doc/styles.css new file mode 100644 index 0000000000..892ca1c93a --- /dev/null +++ b/External/Tools/AStyle/doc/styles.css @@ -0,0 +1,35 @@ + +/* h1 is a title + * h2 is a subtitle + * h3 is a hanging text title + * h4 is a non-hanging text title + * p.noindent is non-hanging text (text without a title) + * p.contents entries are for the table of contents + * a.contents are table of contents links (not underlined) + * a.links are links (underlined) + * img does not have a border + * pre is a predefined format for formatting code + */ + + +body { background-color: white; margin-top: 0.5in; margin-right: 0.8in; margin-bottom: 0.5in; margin-left: 1.3in; } + +h1 { color: #0000A0; text-align: center; font-style: italic; margin-top: 18pt; margin-left: -0.5in; } +h2.large { color: #0000A0; text-align: center; font-size: x-large; margin-top: 0.4in; margin-left: -0.5in; } +h2 { color: #0000A0; text-align: center; font-size: larger; margin-top: 0.4in; margin-left: -0.5in; } +h3 { color: #0000A0; margin-top: 0.4in; margin-left: -0.4in; } +h4 { color: #0000A0; margin-top: 0.3in; } + +p.noindent { margin-left: -0.4in; } +p.contents1 { font-size: 105%; margin-top: 0in; margin-left: 0in; margin-bottom: 0in; margin-right: 0in; } +p.contents2 { margin-top: 0in; margin-left: .4in; margin-bottom: 0in; margin-right: .4in; } +/* p.contents3 { margin-top:0in; margin-left:.8in; margin-bottom:0in; margin-right:.8in; } */ +a.contents:link, a.contents:visited { color: #0000A0; text-decoration: none; } +a.contents:hover { color: #F00000; text-decoration: none; } + +a:link, a:visited { color: #0000A0; text-decoration: underline; } +a:hover { color: #F00000; text-decoration: underline; } + +img { border: none; } + +pre { margin-left: 0.3in; color: navy; font-weight: bold; } diff --git a/External/Tools/AStyle/doc/subversion.html b/External/Tools/AStyle/doc/subversion.html new file mode 100644 index 0000000000..6b09ce1a6b --- /dev/null +++ b/External/Tools/AStyle/doc/subversion.html @@ -0,0 +1,99 @@ + + + + + + Artistic Style - Subversion + + + + + + + + +

    Artistic Style Subversion Repository

    + +

    +   +

    + +

    Artistic Style

    + +

    + The latest development source is in the Artistic Style repository at SourceForge. It can be checked out using + Subversion. The source code is under development and some changes take several weeks to complete. The intermediate + source files have not been through the extensive system tests that are done before each release. Use reasonable + precautions when using source code from the repository. +

    +

    + The current version is in the "trunk/AStyle" branch of the repository. The file and directory names are case sensitive. +

    +

    + A sample checkout is:
    + svn  checkout  "https://svn.code.sf.net/p/astyle/code/trunk/AStyle"  "$HOME/astyle" +

    +

    + You can also browse the subversion repository. + The current development release is in the "trunk" directory. This gives you a view into the current status of + the project's code without actually checking-out the files. +

    +

    +   +

    + +

    Other Projects

    + +

    + Two additional Artistic Style projects are available in the repository. They are not maintained for the general + public but are available if you want them. You may have to create your own project files and scripts to use them. + These projects require the Artistic Style project above. They are an extension that requires the Artistic Style + source. All projects, and any additional source required, should be installed in the same top level folder. +

    + +

    AStyleDev

    + +

    + AStyleDev contains the development files that are made available in the "Developer Information" section. Refer + to that section for more information. +

    +

    + A sample checkout is:
    + svn  checkout  "https://svn.code.sf.net/p/astyle/code/trunk/AStyleDev"  "$HOME/astyledev" +

    + +

    AStyleTest

    + +

    + AStyleTest contains the unit test programs and test scripts for Artistic Style. There are over 2000 tests in the + main test program. +

    +

    + A sample checkout is:
    + svn  checkout  "https://svn.code.sf.net/p/astyle/code/trunk/AStyleTest"  "$HOME/astyletest" +

    +

    + In addition to the Artistic Style source the test program requires + Google Mock. This is the Google multi-platform framework for writing + C++ unit tests. The main Artistic Style test project, AStyleTest, actually uses "integration" tests + instead of "unit" tests. This type of testing can be effective for programs that were written without + unit tests to begin with. +

    +

    +   +

    + +

    + + +

    + +

    +   +

    + + + + + diff --git a/External/Tools/AStyle/doc/vsinstall.html b/External/Tools/AStyle/doc/vsinstall.html new file mode 100644 index 0000000000..149132e9da --- /dev/null +++ b/External/Tools/AStyle/doc/vsinstall.html @@ -0,0 +1,108 @@ + + + + + + .NET Framework SDK + + + + + + + + +

    Visual Studio 2010 C++ Express

    + +

    Install Instructions for .NET Framework SDK

    + +

    +   +

    + +

    + Following are instructions for installing the .NET Framework SDK in Visual Studio 2010 Express and adding x64 + platforms to an existing project in a manner similar to the more expensive Visual Studio editions. +

    + +

    Installing .NET Framework SDK

    + +

    + 64-bit tools are not available on the Visual Studio 2010 C++ Express Edition by default. To enable 64-bit targets, + install the .NET Framework SDK in addition to the Visual Studio 2010 Express Edition. Otherwise, the x64 solution + platform is not available and a warning will occur if you open a project containing a 64-bit target. +

    +

    + Install the + Windows SDK appropriate for your operating system. Use the "Install Now" link to get the SDK. You can + optionally install the Windows Performance Toolkit, Debugging Tools, and Application Verifier. The Help is also + optional. +

    +

    + After installing this package the x64 configurations can be created. +

    +

    + IMPORTANT: If Visual Studio 2010 Service Pack 1 is applied after the .NET Framework SDK install, an additional + update is required to restore the Visual C++ compilers and libraries that may have been removed. Information is + available here. +

    + + +

    Adding x64 to Project Files

    + +

    + Open a Win32 project. Open the Configuration Manager from the Build menu. In the Active Solution Platform select + New. For the New Platform select x64. You will need to “Copy settings from Win32” and check + “Create new project platforms”. +

    +

    + Open the Properties from the Project menu. There is a new configuration property that needs to be set for the + linker to find the system libraries. Be sure the x64 platform is selected and change "Configuration Properties + > General + > Platform Toolset", to Windows7.1SDK. Otherwise you will get linker errors + such as "LINK : fatal error LNK1104: cannot open file 'kernel32.lib'". This setting can also optionally be used + for the Win32 platform. +

    +

    + The x64 configuration can now be compiled, but the compiles will place the files in the same directories as the + Win32 compiles. To correct this the x64 compiles should be placed in an x64 directory using the $(Platform) + macro. +

    +

    + Add the $(Platform) macro to “Configuration Properties > General > Output directory” so the + entry becomes $(SolutionDir)$(Platform)\$(Configuration)\. +

    +

    + Leave “Configuration Properties  > General> Intermediate Directory” at the default which + should be $(Platform)\$(Configuration)\. +

    +

    + Check the x64 Debug configuration “Configuration Properties > Linker > Debugging > Generate Program + Database File” for $(TargetDir)$(TargetName).pdb. +

    +

    + Compile the project. If there are compile errors you may need to add the $(Platform) macro + to other settings as well. For example, if there are user library files the macro may need to be added to + “Configuration Properties > Linker > General > Additional Library Directories”. +

    +

    + You should now be able to compile both Win32 and x64 platforms in a manner similar to the more expensive Visual + Studio editions. +

    +

    +   +

    + +

    + + +

    + +

    +   +

    + + + + + diff --git a/External/Tools/AStyle/src/ASBeautifier.cpp b/External/Tools/AStyle/src/ASBeautifier.cpp new file mode 100644 index 0000000000..da90599f9b --- /dev/null +++ b/External/Tools/AStyle/src/ASBeautifier.cpp @@ -0,0 +1,3486 @@ +// ASBeautifier.cpp +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. +// License.txt describes the conditions under which this software may be distributed. + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- + +#include "astyle.h" + +#include + +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- + +namespace astyle { +// +// this must be global +static int g_preprocessorCppExternCBracket; + +//----------------------------------------------------------------------------- +// ASBeautifier class +//----------------------------------------------------------------------------- + +/** + * ASBeautifier's constructor + * This constructor is called only once for each source file. + * The cloned ASBeautifier objects are created with the copy constructor. + */ +ASBeautifier::ASBeautifier() +{ + waitingBeautifierStack = NULL; + activeBeautifierStack = NULL; + waitingBeautifierStackLengthStack = NULL; + activeBeautifierStackLengthStack = NULL; + + headerStack = NULL; + tempStacks = NULL; + blockParenDepthStack = NULL; + blockStatementStack = NULL; + parenStatementStack = NULL; + bracketBlockStateStack = NULL; + inStatementIndentStack = NULL; + inStatementIndentStackSizeStack = NULL; + parenIndentStack = NULL; + preprocIndentStack = NULL; + sourceIterator = NULL; + isModeManuallySet = false; + shouldForceTabIndentation = false; + setSpaceIndentation(4); + setMinConditionalIndentOption(MINCOND_TWO); + setMaxInStatementIndentLength(40); + classInitializerIndents = 1; + tabLength = 0; + setClassIndent(false); + setModifierIndent(false); + setSwitchIndent(false); + setCaseIndent(false); + setBlockIndent(false); + setBracketIndent(false); + setBracketIndentVtk(false); + setNamespaceIndent(false); + setLabelIndent(false); + setEmptyLineFill(false); + setCStyle(); + setPreprocDefineIndent(false); + setPreprocConditionalIndent(false); + setAlignMethodColon(false); + + // initialize ASBeautifier member vectors + beautifierFileType = 9; // reset to an invalid type + headers = new vector; + nonParenHeaders = new vector; + assignmentOperators = new vector; + nonAssignmentOperators = new vector; + preBlockStatements = new vector; + preCommandHeaders = new vector; + indentableHeaders = new vector; +} + +/** + * ASBeautifier's copy constructor + * Copy the vector objects to vectors in the new ASBeautifier + * object so the new object can be destroyed without deleting + * the vector objects in the copied vector. + * This is the reason a copy constructor is needed. + * + * Must explicitly call the base class copy constructor. + */ +ASBeautifier::ASBeautifier(const ASBeautifier& other) : ASBase(other) +{ + // these don't need to copy the stack + waitingBeautifierStack = NULL; + activeBeautifierStack = NULL; + waitingBeautifierStackLengthStack = NULL; + activeBeautifierStackLengthStack = NULL; + + // vector '=' operator performs a DEEP copy of all elements in the vector + + headerStack = new vector; + *headerStack = *other.headerStack; + + tempStacks = copyTempStacks(other); + + blockParenDepthStack = new vector; + *blockParenDepthStack = *other.blockParenDepthStack; + + blockStatementStack = new vector; + *blockStatementStack = *other.blockStatementStack; + + parenStatementStack = new vector; + *parenStatementStack = *other.parenStatementStack; + + bracketBlockStateStack = new vector; + *bracketBlockStateStack = *other.bracketBlockStateStack; + + inStatementIndentStack = new vector; + *inStatementIndentStack = *other.inStatementIndentStack; + + inStatementIndentStackSizeStack = new vector; + *inStatementIndentStackSizeStack = *other.inStatementIndentStackSizeStack; + + parenIndentStack = new vector; + *parenIndentStack = *other.parenIndentStack; + + preprocIndentStack = new vector >; + *preprocIndentStack = *other.preprocIndentStack; + + // Copy the pointers to vectors. + // This is ok because the original ASBeautifier object + // is not deleted until end of job. + beautifierFileType = other.beautifierFileType; + headers = other.headers; + nonParenHeaders = other.nonParenHeaders; + assignmentOperators = other.assignmentOperators; + nonAssignmentOperators = other.nonAssignmentOperators; + preBlockStatements = other.preBlockStatements; + preCommandHeaders = other.preCommandHeaders; + indentableHeaders = other.indentableHeaders; + + // protected variables + // variables set by ASFormatter + // must also be updated in activeBeautifierStack + inLineNumber = other.inLineNumber; + horstmannIndentInStatement = other.horstmannIndentInStatement; + nonInStatementBracket = other.nonInStatementBracket; + objCColonAlignSubsequent = other.objCColonAlignSubsequent; + lineCommentNoBeautify = other.lineCommentNoBeautify; + isElseHeaderIndent = other.isElseHeaderIndent; + isCaseHeaderCommentIndent = other.isCaseHeaderCommentIndent; + isNonInStatementArray = other.isNonInStatementArray; + isSharpAccessor = other.isSharpAccessor; + isSharpDelegate = other.isSharpDelegate; + isInExternC = other.isInExternC; + isInBeautifySQL = other.isInBeautifySQL; + isInIndentableStruct = other.isInIndentableStruct; + isInIndentablePreproc = other.isInIndentablePreproc; + + // private variables + sourceIterator = other.sourceIterator; + currentHeader = other.currentHeader; + previousLastLineHeader = other.previousLastLineHeader; + probationHeader = other.probationHeader; + lastLineHeader = other.lastLineHeader; + indentString = other.indentString; + verbatimDelimiter = other.verbatimDelimiter; + isInQuote = other.isInQuote; + isInVerbatimQuote = other.isInVerbatimQuote; + haveLineContinuationChar = other.haveLineContinuationChar; + isInAsm = other.isInAsm; + isInAsmOneLine = other.isInAsmOneLine; + isInAsmBlock = other.isInAsmBlock; + isInComment = other.isInComment; + isInPreprocessorComment = other.isInPreprocessorComment; + isInHorstmannComment = other.isInHorstmannComment; + isInCase = other.isInCase; + isInQuestion = other.isInQuestion; + isInStatement = other.isInStatement; + isInHeader = other.isInHeader; + isInTemplate = other.isInTemplate; + isInDefine = other.isInDefine; + isInDefineDefinition = other.isInDefineDefinition; + classIndent = other.classIndent; + isIndentModeOff = other.isIndentModeOff; + isInClassHeader = other.isInClassHeader; + isInClassHeaderTab = other.isInClassHeaderTab; + isInClassInitializer = other.isInClassInitializer; + isInClass = other.isInClass; + isInObjCMethodDefinition = other.isInObjCMethodDefinition; + isImmediatelyPostObjCMethodDefinition = other.isImmediatelyPostObjCMethodDefinition; + isInIndentablePreprocBlock = other.isInIndentablePreprocBlock; + isInObjCInterface = other.isInObjCInterface; + isInEnum = other.isInEnum; + isInEnumTypeID = other.isInEnumTypeID; + isInLet = other.isInLet; + modifierIndent = other.modifierIndent; + switchIndent = other.switchIndent; + caseIndent = other.caseIndent; + namespaceIndent = other.namespaceIndent; + bracketIndent = other.bracketIndent; + bracketIndentVtk = other.bracketIndentVtk; + blockIndent = other.blockIndent; + labelIndent = other.labelIndent; + isInConditional = other.isInConditional; + isModeManuallySet = other.isModeManuallySet; + shouldForceTabIndentation = other.shouldForceTabIndentation; + emptyLineFill = other.emptyLineFill; + lineOpensWithLineComment = other.lineOpensWithLineComment; + lineOpensWithComment = other.lineOpensWithComment; + lineStartsInComment = other.lineStartsInComment; + backslashEndsPrevLine = other.backslashEndsPrevLine; + blockCommentNoIndent = other.blockCommentNoIndent; + blockCommentNoBeautify = other.blockCommentNoBeautify; + previousLineProbationTab = other.previousLineProbationTab; + lineBeginsWithOpenBracket = other.lineBeginsWithOpenBracket; + lineBeginsWithCloseBracket = other.lineBeginsWithCloseBracket; + lineBeginsWithComma = other.lineBeginsWithComma; + lineIsCommentOnly = other.lineIsCommentOnly; + lineIsLineCommentOnly = other.lineIsLineCommentOnly; + shouldIndentBrackettedLine = other.shouldIndentBrackettedLine; + isInSwitch = other.isInSwitch; + foundPreCommandHeader = other.foundPreCommandHeader; + foundPreCommandMacro = other.foundPreCommandMacro; + shouldAlignMethodColon = other.shouldAlignMethodColon; + shouldIndentPreprocDefine = other.shouldIndentPreprocDefine; + shouldIndentPreprocConditional = other.shouldIndentPreprocConditional; + indentCount = other.indentCount; + spaceIndentCount = other.spaceIndentCount; + spaceIndentObjCMethodDefinition = other.spaceIndentObjCMethodDefinition; + colonIndentObjCMethodDefinition = other.colonIndentObjCMethodDefinition; + lineOpeningBlocksNum = other.lineOpeningBlocksNum; + lineClosingBlocksNum = other.lineClosingBlocksNum; + fileType = other.fileType; + minConditionalOption = other.minConditionalOption; + minConditionalIndent = other.minConditionalIndent; + parenDepth = other.parenDepth; + indentLength = other.indentLength; + tabLength = other.tabLength; + blockTabCount = other.blockTabCount; + maxInStatementIndent = other.maxInStatementIndent; + classInitializerIndents = other.classInitializerIndents; + templateDepth = other.templateDepth; + squareBracketCount = other.squareBracketCount; + prevFinalLineSpaceIndentCount = other.prevFinalLineSpaceIndentCount; + prevFinalLineIndentCount = other.prevFinalLineIndentCount; + defineIndentCount = other.defineIndentCount; + preprocBlockIndent = other.preprocBlockIndent; + quoteChar = other.quoteChar; + prevNonSpaceCh = other.prevNonSpaceCh; + currentNonSpaceCh = other.currentNonSpaceCh; + currentNonLegalCh = other.currentNonLegalCh; + prevNonLegalCh = other.prevNonLegalCh; +} + +/** + * ASBeautifier's destructor + */ +ASBeautifier::~ASBeautifier() +{ + deleteBeautifierContainer(waitingBeautifierStack); + deleteBeautifierContainer(activeBeautifierStack); + deleteContainer(waitingBeautifierStackLengthStack); + deleteContainer(activeBeautifierStackLengthStack); + deleteContainer(headerStack); + deleteTempStacksContainer(tempStacks); + deleteContainer(blockParenDepthStack); + deleteContainer(blockStatementStack); + deleteContainer(parenStatementStack); + deleteContainer(bracketBlockStateStack); + deleteContainer(inStatementIndentStack); + deleteContainer(inStatementIndentStackSizeStack); + deleteContainer(parenIndentStack); + deleteContainer(preprocIndentStack); +} + +/** + * initialize the ASBeautifier. + * + * This init() should be called every time a ABeautifier object is to start + * beautifying a NEW source file. + * It is called only when a new ASFormatter object is created. + * init() receives a pointer to a ASSourceIterator object that will be + * used to iterate through the source code. + * + * @param iter a pointer to the ASSourceIterator or ASStreamIterator object. + */ +void ASBeautifier::init(ASSourceIterator* iter) +{ + sourceIterator = iter; + initVectors(); + ASBase::init(getFileType()); + g_preprocessorCppExternCBracket = 0; + + initContainer(waitingBeautifierStack, new vector); + initContainer(activeBeautifierStack, new vector); + + initContainer(waitingBeautifierStackLengthStack, new vector); + initContainer(activeBeautifierStackLengthStack, new vector); + + initContainer(headerStack, new vector); + + initTempStacksContainer(tempStacks, new vector*>); + tempStacks->push_back(new vector); + + initContainer(blockParenDepthStack, new vector); + initContainer(blockStatementStack, new vector); + initContainer(parenStatementStack, new vector); + initContainer(bracketBlockStateStack, new vector); + bracketBlockStateStack->push_back(true); + initContainer(inStatementIndentStack, new vector); + initContainer(inStatementIndentStackSizeStack, new vector); + inStatementIndentStackSizeStack->push_back(0); + initContainer(parenIndentStack, new vector); + initContainer(preprocIndentStack, new vector >); + + previousLastLineHeader = NULL; + currentHeader = NULL; + + isInQuote = false; + isInVerbatimQuote = false; + haveLineContinuationChar = false; + isInAsm = false; + isInAsmOneLine = false; + isInAsmBlock = false; + isInComment = false; + isInPreprocessorComment = false; + isInHorstmannComment = false; + isInStatement = false; + isInCase = false; + isInQuestion = false; + isIndentModeOff = false; + isInClassHeader = false; + isInClassHeaderTab = false; + isInClassInitializer = false; + isInClass = false; + isInObjCMethodDefinition = false; + isImmediatelyPostObjCMethodDefinition = false; + isInIndentablePreprocBlock = false; + isInObjCInterface = false; + isInEnum = false; + isInEnumTypeID = false; + isInLet = false; + isInHeader = false; + isInTemplate = false; + isInConditional = false; + + indentCount = 0; + spaceIndentCount = 0; + spaceIndentObjCMethodDefinition = 0; + colonIndentObjCMethodDefinition = 0; + lineOpeningBlocksNum = 0; + lineClosingBlocksNum = 0; + templateDepth = 0; + squareBracketCount = 0; + parenDepth = 0; + blockTabCount = 0; + prevFinalLineSpaceIndentCount = 0; + prevFinalLineIndentCount = 0; + defineIndentCount = 0; + preprocBlockIndent = 0; + prevNonSpaceCh = '{'; + currentNonSpaceCh = '{'; + prevNonLegalCh = '{'; + currentNonLegalCh = '{'; + quoteChar = ' '; + probationHeader = NULL; + lastLineHeader = NULL; + backslashEndsPrevLine = false; + lineOpensWithLineComment = false; + lineOpensWithComment = false; + lineStartsInComment = false; + isInDefine = false; + isInDefineDefinition = false; + lineCommentNoBeautify = false; + isElseHeaderIndent = false; + isCaseHeaderCommentIndent = false; + blockCommentNoIndent = false; + blockCommentNoBeautify = false; + previousLineProbationTab = false; + lineBeginsWithOpenBracket = false; + lineBeginsWithCloseBracket = false; + lineBeginsWithComma = false; + lineIsCommentOnly = false; + lineIsLineCommentOnly = false; + shouldIndentBrackettedLine = true; + isInSwitch = false; + foundPreCommandHeader = false; + foundPreCommandMacro = false; + + isNonInStatementArray = false; + isSharpAccessor = false; + isSharpDelegate = false; + isInExternC = false; + isInBeautifySQL = false; + isInIndentableStruct = false; + isInIndentablePreproc = false; + inLineNumber = 0; + horstmannIndentInStatement = 0; + nonInStatementBracket = 0; + objCColonAlignSubsequent = 0; +} + +/* + * initialize the vectors + */ +void ASBeautifier::initVectors() +{ + if (fileType == beautifierFileType) // don't build unless necessary + return; + + beautifierFileType = fileType; + + headers->clear(); + nonParenHeaders->clear(); + assignmentOperators->clear(); + nonAssignmentOperators->clear(); + preBlockStatements->clear(); + preCommandHeaders->clear(); + indentableHeaders->clear(); + + ASResource::buildHeaders(headers, fileType, true); + ASResource::buildNonParenHeaders(nonParenHeaders, fileType, true); + ASResource::buildAssignmentOperators(assignmentOperators); + ASResource::buildNonAssignmentOperators(nonAssignmentOperators); + ASResource::buildPreBlockStatements(preBlockStatements, fileType); + ASResource::buildPreCommandHeaders(preCommandHeaders, fileType); + ASResource::buildIndentableHeaders(indentableHeaders); +} + +/** + * set indentation style to C/C++. + */ +void ASBeautifier::setCStyle() +{ + fileType = C_TYPE; +} + +/** + * set indentation style to Java. + */ +void ASBeautifier::setJavaStyle() +{ + fileType = JAVA_TYPE; +} + +/** + * set indentation style to C#. + */ +void ASBeautifier::setSharpStyle() +{ + fileType = SHARP_TYPE; +} + +/** + * set mode manually set flag + */ +void ASBeautifier::setModeManuallySet(bool state) +{ + isModeManuallySet = state; +} + +/** + * set tabLength equal to indentLength. + * This is done when tabLength is not explicitly set by + * "indent=force-tab-x" + * + */ +void ASBeautifier::setDefaultTabLength() +{ + tabLength = indentLength; +} + +/** + * indent using a different tab setting for indent=force-tab + * + * @param length number of spaces per tab. + */ +void ASBeautifier::setForceTabXIndentation(int length) +{ + // set tabLength instead of indentLength + indentString = "\t"; + tabLength = length; + shouldForceTabIndentation = true; +} + +/** + * indent using one tab per indentation + */ +void ASBeautifier::setTabIndentation(int length, bool forceTabs) +{ + indentString = "\t"; + indentLength = length; + shouldForceTabIndentation = forceTabs; +} + +/** + * indent using a number of spaces per indentation. + * + * @param length number of spaces per indent. + */ +void ASBeautifier::setSpaceIndentation(int length) +{ + indentString = string(length, ' '); + indentLength = length; +} + +/** + * set the maximum indentation between two lines in a multi-line statement. + * + * @param max maximum indentation length. + */ +void ASBeautifier::setMaxInStatementIndentLength(int max) +{ + maxInStatementIndent = max; +} + +/** + * set the minimum conditional indentation option. + * + * @param min minimal indentation option. + */ +void ASBeautifier::setMinConditionalIndentOption(int min) +{ + minConditionalOption = min; +} + +/** + * set minConditionalIndent from the minConditionalOption. + */ +void ASBeautifier::setMinConditionalIndentLength() +{ + if (minConditionalOption == MINCOND_ZERO) + minConditionalIndent = 0; + else if (minConditionalOption == MINCOND_ONE) + minConditionalIndent = indentLength; + else if (minConditionalOption == MINCOND_ONEHALF) + minConditionalIndent = indentLength / 2; + // minConditionalOption = INDENT_TWO + else + minConditionalIndent = indentLength * 2; +} + +/** + * set the state of the bracket indent option. If true, brackets will + * be indented one additional indent. + * + * @param state state of option. + */ +void ASBeautifier::setBracketIndent(bool state) +{ + bracketIndent = state; +} + +/** +* set the state of the bracket indent VTK option. If true, brackets will +* be indented one additional indent, except for the opening bracket. +* +* @param state state of option. +*/ +void ASBeautifier::setBracketIndentVtk(bool state) +{ + // need to set both of these + setBracketIndent(state); + bracketIndentVtk = state; +} + +/** + * set the state of the block indentation option. If true, entire blocks + * will be indented one additional indent, similar to the GNU indent style. + * + * @param state state of option. + */ +void ASBeautifier::setBlockIndent(bool state) +{ + blockIndent = state; +} + +/** + * set the state of the class indentation option. If true, C++ class + * definitions will be indented one additional indent. + * + * @param state state of option. + */ +void ASBeautifier::setClassIndent(bool state) +{ + classIndent = state; +} + +/** + * set the state of the modifier indentation option. If true, C++ class + * access modifiers will be indented one-half an indent. + * + * @param state state of option. + */ +void ASBeautifier::setModifierIndent(bool state) +{ + modifierIndent = state; +} + +/** + * set the state of the switch indentation option. If true, blocks of 'switch' + * statements will be indented one additional indent. + * + * @param state state of option. + */ +void ASBeautifier::setSwitchIndent(bool state) +{ + switchIndent = state; +} + +/** + * set the state of the case indentation option. If true, lines of 'case' + * statements will be indented one additional indent. + * + * @param state state of option. + */ +void ASBeautifier::setCaseIndent(bool state) +{ + caseIndent = state; +} + +/** + * set the state of the namespace indentation option. + * If true, blocks of 'namespace' statements will be indented one + * additional indent. Otherwise, NO indentation will be added. + * + * @param state state of option. + */ +void ASBeautifier::setNamespaceIndent(bool state) +{ + namespaceIndent = state; +} + +/** + * set the state of the label indentation option. + * If true, labels will be indented one indent LESS than the + * current indentation level. + * If false, labels will be flushed to the left with NO + * indent at all. + * + * @param state state of option. + */ +void ASBeautifier::setLabelIndent(bool state) +{ + labelIndent = state; +} + +/** + * set the state of the preprocessor indentation option. + * If true, multi-line #define statements will be indented. + * + * @param state state of option. + */ +void ASBeautifier::setPreprocDefineIndent(bool state) +{ + shouldIndentPreprocDefine = state; +} + +void ASBeautifier::setPreprocConditionalIndent(bool state) +{ + shouldIndentPreprocConditional = state; +} + +/** + * set the state of the empty line fill option. + * If true, empty lines will be filled with the whitespace. + * of their previous lines. + * If false, these lines will remain empty. + * + * @param state state of option. + */ +void ASBeautifier::setEmptyLineFill(bool state) +{ + emptyLineFill = state; +} + +void ASBeautifier::setAlignMethodColon(bool state) +{ + shouldAlignMethodColon = state; +} + +/** + * get the file type. + */ +int ASBeautifier::getFileType() const +{ + return fileType; +} + +/** + * get the number of spaces per indent + * + * @return value of indentLength option. + */ +int ASBeautifier::getIndentLength(void) const +{ + return indentLength; +} + +/** + * get the char used for indentation, space or tab + * + * @return the char used for indentation. + */ +string ASBeautifier::getIndentString(void) const +{ + return indentString; +} + +/** + * get mode manually set flag + */ +bool ASBeautifier::getModeManuallySet() const +{ + return isModeManuallySet; +} + +/** + * get the state of the force tab indentation option. + * + * @return state of force tab indentation. + */ +bool ASBeautifier::getForceTabIndentation(void) const +{ + return shouldForceTabIndentation; +} + +/** +* Get the state of the Objective-C align method colon option. +* +* @return state of shouldAlignMethodColon option. +*/ +bool ASBeautifier::getAlignMethodColon(void) const +{ + return shouldAlignMethodColon; +} + +/** + * get the state of the block indentation option. + * + * @return state of blockIndent option. + */ +bool ASBeautifier::getBlockIndent(void) const +{ + return blockIndent; +} + +/** + * get the state of the bracket indentation option. + * + * @return state of bracketIndent option. + */ +bool ASBeautifier::getBracketIndent(void) const +{ + return bracketIndent; +} + +/** +* Get the state of the namespace indentation option. If true, blocks +* of the 'namespace' statement will be indented one additional indent. +* +* @return state of namespaceIndent option. +*/ +bool ASBeautifier::getNamespaceIndent(void) const +{ + return namespaceIndent; +} + +/** + * Get the state of the class indentation option. If true, blocks of + * the 'class' statement will be indented one additional indent. + * + * @return state of classIndent option. + */ +bool ASBeautifier::getClassIndent(void) const +{ + return classIndent; +} + +/** + * Get the state of the class access modifier indentation option. + * If true, the class access modifiers will be indented one-half indent. + * + * @return state of modifierIndent option. + */ +bool ASBeautifier::getModifierIndent(void) const +{ + return modifierIndent; +} + +/** + * get the state of the switch indentation option. If true, blocks of + * the 'switch' statement will be indented one additional indent. + * + * @return state of switchIndent option. + */ +bool ASBeautifier::getSwitchIndent(void) const +{ + return switchIndent; +} + +/** + * get the state of the case indentation option. If true, lines of 'case' + * statements will be indented one additional indent. + * + * @return state of caseIndent option. + */ +bool ASBeautifier::getCaseIndent(void) const +{ + return caseIndent; +} + +/** + * get the state of the empty line fill option. + * If true, empty lines will be filled with the whitespace. + * of their previous lines. + * If false, these lines will remain empty. + * + * @return state of emptyLineFill option. + */ +bool ASBeautifier::getEmptyLineFill(void) const +{ + return emptyLineFill; +} + +/** + * get the state of the preprocessor indentation option. + * If true, preprocessor "define" lines will be indented. + * If false, preprocessor "define" lines will be unchanged. + * + * @return state of shouldIndentPreprocDefine option. + */ +bool ASBeautifier::getPreprocDefineIndent(void) const +{ + return shouldIndentPreprocDefine; +} + +/** + * get the length of the tab indentation option. + * + * @return length of tab indent option. + */ +int ASBeautifier::getTabLength(void) const +{ + return tabLength; +} + +/** + * beautify a line of source code. + * every line of source code in a source code file should be sent + * one after the other to the beautify method. + * + * @return the indented line. + * @param originalLine the original unindented line. + */ +string ASBeautifier::beautify(const string& originalLine) +{ + string line; + bool isInQuoteContinuation = isInVerbatimQuote | haveLineContinuationChar; + + currentHeader = NULL; + lastLineHeader = NULL; + blockCommentNoBeautify = blockCommentNoIndent; + isInClass = false; + isInSwitch = false; + lineBeginsWithOpenBracket = false; + lineBeginsWithCloseBracket = false; + lineBeginsWithComma = false; + lineIsCommentOnly = false; + lineIsLineCommentOnly = false; + shouldIndentBrackettedLine = true; + isInAsmOneLine = false; + lineOpensWithLineComment = false; + lineOpensWithComment = false; + lineStartsInComment = isInComment; + previousLineProbationTab = false; + haveLineContinuationChar = false; + lineOpeningBlocksNum = 0; + lineClosingBlocksNum = 0; + if (isImmediatelyPostObjCMethodDefinition) + clearObjCMethodDefinitionAlignment(); + + // handle and remove white spaces around the line: + // If not in comment, first find out size of white space before line, + // so that possible comments starting in the line continue in + // relation to the preliminary white-space. + if (isInQuoteContinuation) + { + // trim a single space added by ASFormatter, otherwise leave it alone + if (!(originalLine.length() == 1 && originalLine[0] == ' ')) + line = originalLine; + } + else if (isInComment || isInBeautifySQL) + { + // trim the end of comment and SQL lines + line = originalLine; + size_t trimEnd = line.find_last_not_of(" \t"); + if (trimEnd == string::npos) + trimEnd = 0; + else + trimEnd++; + if (trimEnd < line.length()) + line.erase(trimEnd); + // does a bracket open the line + size_t firstChar = line.find_first_not_of(" \t"); + if (firstChar != string::npos) + { + if (line[firstChar] == '{') + lineBeginsWithOpenBracket = true; + else if (line[firstChar] == '}') + lineBeginsWithCloseBracket = true; + else if (line[firstChar] == ',') + lineBeginsWithComma = true; + } + } + else + { + line = trim(originalLine); + if (line.length() > 0) + { + if (line[0] == '{') + lineBeginsWithOpenBracket = true; + else if (line[0] == '}') + lineBeginsWithCloseBracket = true; + else if (line[0] == ',') + lineBeginsWithComma = true; + else if (line.compare(0, 2, "//") == 0) + lineIsLineCommentOnly = true; + else if (line.compare(0, 2, "/*") == 0) + { + if (line.find("*/", 2) != string::npos) + lineIsCommentOnly = true; + } + } + + isInHorstmannComment = false; + size_t j = line.find_first_not_of(" \t{"); + if (j != string::npos && line.compare(j, 2, "//") == 0) + lineOpensWithLineComment = true; + if (j != string::npos && line.compare(j, 2, "/*") == 0) + { + lineOpensWithComment = true; + size_t k = line.find_first_not_of(" \t"); + if (k != string::npos && line.compare(k, 1, "{") == 0) + isInHorstmannComment = true; + } + } + + // When indent is OFF the lines must still be processed by ASBeautifier. + // Otherwise the lines immediately following may not be indented correctly. + if ((lineIsLineCommentOnly || lineIsCommentOnly) + && line.find("*INDENT-OFF*", 0) != string::npos) + isIndentModeOff = true; + + if (line.length() == 0) + { + if (backslashEndsPrevLine) + { + backslashEndsPrevLine = false; + isInDefine = false; + isInDefineDefinition = false; + } + if (emptyLineFill && !isInQuoteContinuation) + { + if (isInIndentablePreprocBlock) + return preLineWS(preprocBlockIndent, 0); + else if (!headerStack->empty() || isInEnum) + return preLineWS(prevFinalLineIndentCount, prevFinalLineSpaceIndentCount); + // must fall thru here + } + else + return line; + } + + // handle preprocessor commands + if (isInIndentablePreprocBlock + && line.length() > 0 + && line[0] != '#') + { + string indentedLine; + if (isInClassHeaderTab || isInClassInitializer) + { + // parsing is turned off in ASFormatter by indent-off + // the originalLine will probably never be returned here + indentedLine = preLineWS(prevFinalLineIndentCount, prevFinalLineSpaceIndentCount) + line; + return getIndentedLineReturn(indentedLine, originalLine); + } + else + { + indentedLine = preLineWS(preprocBlockIndent, 0) + line; + return getIndentedLineReturn(indentedLine, originalLine); + } + } + if (!isInComment + && !isInQuoteContinuation + && line.length() > 0 + && ((line[0] == '#' && !isIndentedPreprocessor(line, 0)) + || backslashEndsPrevLine)) + { + if (line[0] == '#' && !isInDefine) + { + string preproc = extractPreprocessorStatement(line); + processPreprocessor(preproc, line); + if (isInIndentablePreprocBlock || isInIndentablePreproc) + { + string indentedLine; + if ((preproc.length() >= 2 && preproc.substr(0, 2) == "if")) // #if, #ifdef, #ifndef + { + indentedLine = preLineWS(preprocBlockIndent, 0) + line; + preprocBlockIndent += 1; + isInIndentablePreprocBlock = true; + } + else if (preproc == "else" || preproc == "elif" || preproc == "elseif") + { + indentedLine = preLineWS(preprocBlockIndent - 1, 0) + line; + } + else if (preproc == "endif" || preproc == "end") + { + preprocBlockIndent -= 1; + indentedLine = preLineWS(preprocBlockIndent, 0) + line; + if (preprocBlockIndent == 0) + isInIndentablePreprocBlock = false; + } + else + indentedLine = preLineWS(preprocBlockIndent, 0) + line; + return getIndentedLineReturn(indentedLine, originalLine); + } + if (shouldIndentPreprocConditional && preproc.length() > 0) + { + string indentedLine; + if (preproc.length() >= 2 && preproc.substr(0, 2) == "if") // #if, #ifdef, #ifndef + { + pair entry; // indentCount, spaceIndentCount + if (!isInDefine && activeBeautifierStack != NULL && !activeBeautifierStack->empty()) + entry = activeBeautifierStack->back()->computePreprocessorIndent(); + else + entry = computePreprocessorIndent(); + preprocIndentStack->push_back(entry); + indentedLine = preLineWS(preprocIndentStack->back().first, + preprocIndentStack->back().second) + line; + return getIndentedLineReturn(indentedLine, originalLine); + } + else if (preproc == "else" || preproc == "elif" || preproc == "elseif") + { + if (preprocIndentStack->size() > 0) // if no entry don't indent + { + indentedLine = preLineWS(preprocIndentStack->back().first, + preprocIndentStack->back().second) + line; + return getIndentedLineReturn(indentedLine, originalLine); + } + } + else if (preproc == "endif" || preproc == "end") + { + if (preprocIndentStack->size() > 0) // if no entry don't indent + { + indentedLine = preLineWS(preprocIndentStack->back().first, + preprocIndentStack->back().second) + line; + preprocIndentStack->pop_back(); + return getIndentedLineReturn(indentedLine, originalLine); + } + } + } + } + + // check if the last char is a backslash + if (line.length() > 0) + backslashEndsPrevLine = (line[line.length() - 1] == '\\'); + // comments within the definition line can be continued without the backslash + if (isInPreprocessorUnterminatedComment(line)) + backslashEndsPrevLine = true; + + // check if this line ends a multi-line #define + // if so, use the #define's cloned beautifier for the line's indentation + // and then remove it from the active beautifier stack and delete it. + if (!backslashEndsPrevLine && isInDefineDefinition && !isInDefine) + { + isInDefineDefinition = false; + ASBeautifier* defineBeautifier = activeBeautifierStack->back(); + activeBeautifierStack->pop_back(); + + string indentedLine = defineBeautifier->beautify(line); + delete defineBeautifier; + return getIndentedLineReturn(indentedLine, originalLine); + } + + // unless this is a multi-line #define, return this precompiler line as is. + if (!isInDefine && !isInDefineDefinition) + return originalLine; + } + + // if there exists any worker beautifier in the activeBeautifierStack, + // then use it instead of me to indent the current line. + // variables set by ASFormatter must be updated. + if (!isInDefine && activeBeautifierStack != NULL && !activeBeautifierStack->empty()) + { + activeBeautifierStack->back()->inLineNumber = inLineNumber; + activeBeautifierStack->back()->horstmannIndentInStatement = horstmannIndentInStatement; + activeBeautifierStack->back()->nonInStatementBracket = nonInStatementBracket; + activeBeautifierStack->back()->objCColonAlignSubsequent = objCColonAlignSubsequent; + activeBeautifierStack->back()->lineCommentNoBeautify = lineCommentNoBeautify; + activeBeautifierStack->back()->isElseHeaderIndent = isElseHeaderIndent; + activeBeautifierStack->back()->isCaseHeaderCommentIndent = isCaseHeaderCommentIndent; + activeBeautifierStack->back()->isNonInStatementArray = isNonInStatementArray; + activeBeautifierStack->back()->isSharpAccessor = isSharpAccessor; + activeBeautifierStack->back()->isSharpDelegate = isSharpDelegate; + activeBeautifierStack->back()->isInExternC = isInExternC; + activeBeautifierStack->back()->isInBeautifySQL = isInBeautifySQL; + activeBeautifierStack->back()->isInIndentableStruct = isInIndentableStruct; + activeBeautifierStack->back()->isInIndentablePreproc = isInIndentablePreproc; + // must return originalLine not the trimmed line + return activeBeautifierStack->back()->beautify(originalLine); + } + + // Flag an indented header in case this line is a one-line block. + // The header in the header stack will be deleted by a one-line block. + bool isInExtraHeaderIndent = false; + if (!headerStack->empty() + && lineBeginsWithOpenBracket + && (headerStack->back() != &AS_OPEN_BRACKET + || probationHeader != NULL)) + isInExtraHeaderIndent = true; + + size_t iPrelim = headerStack->size(); + + // calculate preliminary indentation based on headerStack and data from past lines + computePreliminaryIndentation(); + + // parse characters in the current line. + parseCurrentLine(line); + + // handle special cases of indentation + adjustParsedLineIndentation(iPrelim, isInExtraHeaderIndent); + + // Objective-C continuation line + if (isInObjCMethodDefinition) + { + // register indent for Objective-C continuation line + if (line.length() > 0 + && (line[0] == '-' || line[0] == '+')) + { + if (shouldAlignMethodColon) + { + colonIndentObjCMethodDefinition = line.find(':'); + int objCColonAlignSubsequentIndent = objCColonAlignSubsequent + indentLength; + if (objCColonAlignSubsequentIndent > colonIndentObjCMethodDefinition) + colonIndentObjCMethodDefinition = objCColonAlignSubsequentIndent; + } + else if (inStatementIndentStack->empty() + || inStatementIndentStack->back() == 0) + { + inStatementIndentStack->push_back(indentLength); + isInStatement = true; + } + } + // set indent for last definition line + else if (!lineBeginsWithOpenBracket) + { + if (shouldAlignMethodColon) + spaceIndentCount = computeObjCColonAlignment(line, colonIndentObjCMethodDefinition); + else if (inStatementIndentStack->empty()) + spaceIndentCount = spaceIndentObjCMethodDefinition; + } + } + + if (isInDefine) + { + if (line.length() > 0 && line[0] == '#') + { + // the 'define' does not have to be attached to the '#' + string preproc = trim(line.substr(1)); + if (preproc.compare(0, 6, "define") == 0) + { + if (!inStatementIndentStack->empty() + && inStatementIndentStack->back() > 0) + { + defineIndentCount = indentCount; + } + else + { + defineIndentCount = indentCount - 1; + --indentCount; + } + } + } + + indentCount -= defineIndentCount; + } + + if (indentCount < 0) + indentCount = 0; + + if (lineCommentNoBeautify || blockCommentNoBeautify || isInQuoteContinuation) + indentCount = spaceIndentCount = 0; + + // finally, insert indentations into beginning of line + + string indentedLine = preLineWS(indentCount, spaceIndentCount) + line; + indentedLine = getIndentedLineReturn(indentedLine, originalLine); + + prevFinalLineSpaceIndentCount = spaceIndentCount; + prevFinalLineIndentCount = indentCount; + + if (lastLineHeader != NULL) + previousLastLineHeader = lastLineHeader; + + if ((lineIsLineCommentOnly || lineIsCommentOnly) + && line.find("*INDENT-ON*", 0) != string::npos) + isIndentModeOff = false; + + return indentedLine; +} + +string& ASBeautifier::getIndentedLineReturn(string& newLine, const string& originalLine) const +{ + if (isIndentModeOff) + return const_cast(originalLine); + return newLine; +} + +string ASBeautifier::preLineWS(int lineIndentCount, int lineSpaceIndentCount) const +{ + if (shouldForceTabIndentation) + { + if (tabLength != indentLength) + { + // adjust for different tab length + int indentCountOrig = lineIndentCount; + int spaceIndentCountOrig = lineSpaceIndentCount; + lineIndentCount = ((indentCountOrig * indentLength) + spaceIndentCountOrig) / tabLength; + lineSpaceIndentCount = ((indentCountOrig * indentLength) + spaceIndentCountOrig) % tabLength; + } + else + { + lineIndentCount += lineSpaceIndentCount / indentLength; + lineSpaceIndentCount = lineSpaceIndentCount % indentLength; + } + } + + string ws; + for (int i = 0; i < lineIndentCount; i++) + ws += indentString; + while ((lineSpaceIndentCount--) > 0) + ws += string(" "); + return ws; +} + +/** + * register an in-statement indent. + */ +void ASBeautifier::registerInStatementIndent(const string& line, int i, int spaceTabCount_, + int tabIncrementIn, int minIndent, bool updateParenStack) +{ + int remainingCharNum = line.length() - i; + int nextNonWSChar = getNextProgramCharDistance(line, i); + + // if indent is around the last char in the line, indent instead one indent from the previous indent + if (nextNonWSChar == remainingCharNum) + { + int previousIndent = spaceTabCount_; + if (!inStatementIndentStack->empty()) + previousIndent = inStatementIndentStack->back(); + int currIndent = /*2*/ indentLength + previousIndent; + if (currIndent > maxInStatementIndent + && line[i] != '{') + currIndent = indentLength * 2 + spaceTabCount_; + inStatementIndentStack->push_back(currIndent); + if (updateParenStack) + parenIndentStack->push_back(previousIndent); + return; + } + + if (updateParenStack) + parenIndentStack->push_back(i + spaceTabCount_ - horstmannIndentInStatement); + + int tabIncrement = tabIncrementIn; + + // check for following tabs + for (int j = i + 1; j < (i + nextNonWSChar); j++) + { + if (line[j] == '\t') + tabIncrement += convertTabToSpaces(j, tabIncrement); + } + + int inStatementIndent = i + nextNonWSChar + spaceTabCount_ + tabIncrement; + + // check for run-in statement + if (i > 0 && line[0] == '{') + inStatementIndent -= indentLength; + + if (inStatementIndent < minIndent) + inStatementIndent = minIndent + spaceTabCount_; + + // this is not done for an in-statement array + if (inStatementIndent > maxInStatementIndent + && !(prevNonLegalCh == '=' && currentNonLegalCh == '{')) + inStatementIndent = indentLength * 2 + spaceTabCount_; + + if (!inStatementIndentStack->empty() + && inStatementIndent < inStatementIndentStack->back()) + inStatementIndent = inStatementIndentStack->back(); + + // the block opener is not indented for a NonInStatementArray + if (isNonInStatementArray && !isInEnum && !bracketBlockStateStack->empty() && bracketBlockStateStack->back()) + inStatementIndent = 0; + + inStatementIndentStack->push_back(inStatementIndent); +} + +/** +* Register an in-statement indent for a class header or a class initializer colon. +*/ +void ASBeautifier::registerInStatementIndentColon(const string& line, int i, int tabIncrementIn) +{ + assert(line[i] == ':'); + assert(isInClassInitializer || isInClassHeaderTab); + + // register indent at first word after the colon + size_t firstChar = line.find_first_not_of(" \t"); + if (firstChar == (size_t)i) // firstChar is ':' + { + size_t firstWord = line.find_first_not_of(" \t", firstChar + 1); + if (firstChar != string::npos) + { + int inStatementIndent = firstWord + spaceIndentCount + tabIncrementIn; + inStatementIndentStack->push_back(inStatementIndent); + isInStatement = true; + } + } +} + +/** + * Compute indentation for a preprocessor #if statement. + * This may be called for the activeBeautiferStack + * instead of the active ASBeautifier object. + */ +pair ASBeautifier::computePreprocessorIndent() +{ + computePreliminaryIndentation(); + pair entry(indentCount, spaceIndentCount); + if (!headerStack->empty() + && entry.first > 0 + && (headerStack->back() == &AS_IF + || headerStack->back() == &AS_ELSE + || headerStack->back() == &AS_FOR + || headerStack->back() == &AS_WHILE)) + --entry.first; + return entry; +} + +/** + * get distance to the next non-white space, non-comment character in the line. + * if no such character exists, return the length remaining to the end of the line. + */ +int ASBeautifier::getNextProgramCharDistance(const string& line, int i) const +{ + bool inComment = false; + int remainingCharNum = line.length() - i; + int charDistance; + char ch; + + for (charDistance = 1; charDistance < remainingCharNum; charDistance++) + { + ch = line[i + charDistance]; + if (inComment) + { + if (line.compare(i + charDistance, 2, "*/") == 0) + { + charDistance++; + inComment = false; + } + continue; + } + else if (isWhiteSpace(ch)) + continue; + else if (ch == '/') + { + if (line.compare(i + charDistance, 2, "//") == 0) + return remainingCharNum; + else if (line.compare(i + charDistance, 2, "/*") == 0) + { + charDistance++; + inComment = true; + } + } + else + return charDistance; + } + + return charDistance; +} + +// check if a specific line position contains a header. +const string* ASBeautifier::findHeader(const string& line, int i, + const vector* possibleHeaders) const +{ + assert(isCharPotentialHeader(line, i)); + // check the word + size_t maxHeaders = possibleHeaders->size(); + for (size_t p = 0; p < maxHeaders; p++) + { + const string* header = (*possibleHeaders)[p]; + const size_t wordEnd = i + header->length(); + if (wordEnd > line.length()) + continue; + int result = (line.compare(i, header->length(), *header)); + if (result > 0) + continue; + if (result < 0) + break; + // check that this is not part of a longer word + if (wordEnd == line.length()) + return header; + if (isLegalNameChar(line[wordEnd])) + continue; + const char peekChar = peekNextChar(line, wordEnd - 1); + // is not a header if part of a definition + if (peekChar == ',' || peekChar == ')') + break; + // the following accessor definitions are NOT headers + // goto default; is NOT a header + // default(int) keyword in C# is NOT a header + else if ((header == &AS_GET || header == &AS_SET || header == &AS_DEFAULT) + && (peekChar == ';' || peekChar == '(' || peekChar == '=')) + break; + return header; + } + return NULL; +} + +// check if a specific line position contains an operator. +const string* ASBeautifier::findOperator(const string& line, int i, + const vector* possibleOperators) const +{ + assert(isCharPotentialOperator(line[i])); + // find the operator in the vector + // the vector contains the LONGEST operators first + // must loop thru the entire vector + size_t maxOperators = possibleOperators->size(); + for (size_t p = 0; p < maxOperators; p++) + { + const size_t wordEnd = i + (*(*possibleOperators)[p]).length(); + if (wordEnd > line.length()) + continue; + if (line.compare(i, (*(*possibleOperators)[p]).length(), *(*possibleOperators)[p]) == 0) + return (*possibleOperators)[p]; + } + return NULL; +} + +/** + * find the index number of a string element in a container of strings + * + * @return the index number of element in the container. -1 if element not found. + * @param container a vector of strings. + * @param element the element to find . + */ +int ASBeautifier::indexOf(vector& container, const string* element) const +{ + vector::const_iterator where; + + where = find(container.begin(), container.end(), element); + if (where == container.end()) + return -1; + else + return (int) (where - container.begin()); +} + +/** + * convert tabs to spaces. + * i is the position of the character to convert to spaces. + * tabIncrementIn is the increment that must be added for tab indent characters + * to get the correct column for the current tab. + */ +int ASBeautifier::convertTabToSpaces(int i, int tabIncrementIn) const +{ + int tabToSpacesAdjustment = indentLength - 1 - ((tabIncrementIn + i) % indentLength); + return tabToSpacesAdjustment; +} + +/** + * trim removes the white space surrounding a line. + * + * @return the trimmed line. + * @param str the line to trim. + */ +string ASBeautifier::trim(const string& str) const +{ + int start = 0; + int end = str.length() - 1; + + while (start < end && isWhiteSpace(str[start])) + start++; + + while (start <= end && isWhiteSpace(str[end])) + end--; + + // don't trim if it ends in a continuation + if (end > -1 && str[end] == '\\') + end = str.length() - 1; + + string returnStr(str, start, end + 1 - start); + return returnStr; +} + +/** + * rtrim removes the white space from the end of a line. + * + * @return the trimmed line. + * @param str the line to trim. + */ +string ASBeautifier::rtrim(const string& str) const +{ + size_t len = str.length(); + size_t end = str.find_last_not_of(" \t"); + if (end == string::npos + || end == len - 1) + return str; + string returnStr(str, 0, end + 1); + return returnStr; +} + +/** + * Copy tempStacks for the copy constructor. + * The value of the vectors must also be copied. + */ +vector*>* ASBeautifier::copyTempStacks(const ASBeautifier& other) const +{ + vector*>* tempStacksNew = new vector*>; + vector*>::iterator iter; + for (iter = other.tempStacks->begin(); + iter != other.tempStacks->end(); + ++iter) + { + vector* newVec = new vector; + *newVec = **iter; + tempStacksNew->push_back(newVec); + } + return tempStacksNew; +} + +/** + * delete a member vectors to eliminate memory leak reporting + */ +void ASBeautifier::deleteBeautifierVectors() +{ + beautifierFileType = 9; // reset to an invalid type + delete headers; + delete nonParenHeaders; + delete preBlockStatements; + delete preCommandHeaders; + delete assignmentOperators; + delete nonAssignmentOperators; + delete indentableHeaders; +} + +/** + * delete a vector object + * T is the type of vector + * used for all vectors except tempStacks + */ +template +void ASBeautifier::deleteContainer(T& container) +{ + if (container != NULL) + { + container->clear(); + delete (container); + container = NULL; + } +} + +/** + * Delete the ASBeautifier vector object. + * This is a vector of pointers to ASBeautifier objects allocated with the 'new' operator. + * Therefore the ASBeautifier objects have to be deleted in addition to the + * ASBeautifier pointer entries. + */ +void ASBeautifier::deleteBeautifierContainer(vector*& container) +{ + if (container != NULL) + { + vector::iterator iter = container->begin(); + while (iter < container->end()) + { + delete *iter; + ++iter; + } + container->clear(); + delete (container); + container = NULL; + } +} + +/** + * Delete the tempStacks vector object. + * The tempStacks is a vector of pointers to strings allocated with the 'new' operator. + * Therefore the strings have to be deleted in addition to the tempStacks entries. + */ +void ASBeautifier::deleteTempStacksContainer(vector*>*& container) +{ + if (container != NULL) + { + vector*>::iterator iter = container->begin(); + while (iter < container->end()) + { + delete *iter; + ++iter; + } + container->clear(); + delete (container); + container = NULL; + } +} + +/** + * initialize a vector object + * T is the type of vector used for all vectors + */ +template +void ASBeautifier::initContainer(T& container, T value) +{ + // since the ASFormatter object is never deleted, + // the existing vectors must be deleted before creating new ones + if (container != NULL) + deleteContainer(container); + container = value; +} + +/** + * Initialize the tempStacks vector object. + * The tempStacks is a vector of pointers to strings allocated with the 'new' operator. + * Any residual entries are deleted before the vector is initialized. + */ +void ASBeautifier::initTempStacksContainer(vector*>*& container, + vector*>* value) +{ + if (container != NULL) + deleteTempStacksContainer(container); + container = value; +} + +/** + * Determine if an assignment statement ends with a comma + * that is not in a function argument. It ends with a + * comma if a comma is the last char on the line. + * + * @return true if line ends with a comma, otherwise false. + */ +bool ASBeautifier::statementEndsWithComma(const string& line, int index) const +{ + assert(line[index] == '='); + + bool isInComment_ = false; + bool isInQuote_ = false; + int parenCount = 0; + size_t lineLength = line.length(); + size_t i = 0; + char quoteChar_ = ' '; + + for (i = index + 1; i < lineLength; ++i) + { + char ch = line[i]; + + if (isInComment_) + { + if (line.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + + if (ch == '\\') + { + ++i; + continue; + } + + if (isInQuote_) + { + if (ch == quoteChar_) + isInQuote_ = false; + continue; + } + + if (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i))) + { + isInQuote_ = true; + quoteChar_ = ch; + continue; + } + + if (line.compare(i, 2, "//") == 0) + break; + + if (line.compare(i, 2, "/*") == 0) + { + if (isLineEndComment(line, i)) + break; + else + { + isInComment_ = true; + ++i; + continue; + } + } + + if (ch == '(') + parenCount++; + if (ch == ')') + parenCount--; + } + if (isInComment_ + || isInQuote_ + || parenCount > 0) + return false; + + size_t lastChar = line.find_last_not_of(" \t", i - 1); + + if (lastChar == string::npos || line[lastChar] != ',') + return false; + + return true; +} + +/** + * check if current comment is a line-end comment + * + * @return is before a line-end comment. + */ +bool ASBeautifier::isLineEndComment(const string& line, int startPos) const +{ + assert(line.compare(startPos, 2, "/*") == 0); + + // comment must be closed on this line with nothing after it + size_t endNum = line.find("*/", startPos + 2); + if (endNum != string::npos) + { + size_t nextChar = line.find_first_not_of(" \t", endNum + 2); + if (nextChar == string::npos) + return true; + } + return false; +} + +/** + * get the previous word index for an assignment operator + * + * @return is the index to the previous word (the in statement indent). + */ +int ASBeautifier::getInStatementIndentAssign(const string& line, size_t currPos) const +{ + assert(line[currPos] == '='); + + if (currPos == 0) + return 0; + + // get the last legal word (may be a number) + size_t end = line.find_last_not_of(" \t", currPos - 1); + if (end == string::npos || !isLegalNameChar(line[end])) + return 0; + + int start; // start of the previous word + for (start = end; start > -1; start--) + { + if (!isLegalNameChar(line[start]) || line[start] == '.') + break; + } + start++; + + return start; +} + +/** + * get the instatement indent for a comma + * + * @return is the indent to the second word on the line (the in statement indent). + */ +int ASBeautifier::getInStatementIndentComma(const string& line, size_t currPos) const +{ + assert(line[currPos] == ','); + + // get first word on a line + size_t indent = line.find_first_not_of(" \t"); + if (indent == string::npos || !isLegalNameChar(line[indent])) + return 0; + + // bypass first word + for (; indent < currPos; indent++) + { + if (!isLegalNameChar(line[indent])) + break; + } + indent++; + if (indent >= currPos || indent < 4) + return 0; + + // point to second word or assignment operator + indent = line.find_first_not_of(" \t", indent); + if (indent == string::npos || indent >= currPos) + return 0; + + return indent; +} + +/** + * get the next word on a line + * the argument 'currPos' must point to the current position. + * + * @return is the next word or an empty string if none found. + */ +string ASBeautifier::getNextWord(const string& line, size_t currPos) const +{ + size_t lineLength = line.length(); + // get the last legal word (may be a number) + if (currPos == lineLength - 1) + return string(); + + size_t start = line.find_first_not_of(" \t", currPos + 1); + if (start == string::npos || !isLegalNameChar(line[start])) + return string(); + + size_t end; // end of the current word + for (end = start + 1; end <= lineLength; end++) + { + if (!isLegalNameChar(line[end]) || line[end] == '.') + break; + } + + return line.substr(start, end - start); +} + +/** + * Check if a preprocessor directive is always indented. + * C# "region" and "endregion" are always indented. + * C/C++ "pragma omp" is always indented. + * + * @return is true or false. + */ +bool ASBeautifier::isIndentedPreprocessor(const string& line, size_t currPos) const +{ + assert(line[0] == '#'); + string nextWord = getNextWord(line, currPos); + if (nextWord == "region" || nextWord == "endregion") + return true; + // is it #pragma omp + if (nextWord == "pragma") + { + // find pragma + size_t start = line.find("pragma"); + if (start == string::npos || !isLegalNameChar(line[start])) + return false; + // bypass pragma + for (; start < line.length(); start++) + { + if (!isLegalNameChar(line[start])) + break; + } + start++; + if (start >= line.length()) + return false; + // point to start of second word + start = line.find_first_not_of(" \t", start); + if (start == string::npos) + return false; + // point to end of second word + size_t end; + for (end = start; end < line.length(); end++) + { + if (!isLegalNameChar(line[end])) + break; + } + // check for "pragma omp" + string word = line.substr(start, end - start); + if (word == "omp" || word == "region" || word == "endregion") + return true; + } + return false; +} + +/** + * Check if a preprocessor directive is checking for __cplusplus defined. + * + * @return is true or false. + */ +bool ASBeautifier::isPreprocessorConditionalCplusplus(const string& line) const +{ + string preproc = trim(line.substr(1)); + if (preproc.compare(0, 5, "ifdef") == 0 && getNextWord(preproc, 4) == "__cplusplus") + return true; + if (preproc.compare(0, 2, "if") == 0) + { + // check for " #if defined(__cplusplus)" + size_t charNum = 2; + charNum = preproc.find_first_not_of(" \t", charNum); + if (preproc.compare(charNum, 7, "defined") == 0) + { + charNum += 7; + charNum = preproc.find_first_not_of(" \t", charNum); + if (preproc.compare(charNum, 1, "(") == 0) + { + ++charNum; + charNum = preproc.find_first_not_of(" \t", charNum); + if (preproc.compare(charNum, 11, "__cplusplus") == 0) + return true; + } + } + } + return false; +} + +/** + * Check if a preprocessor definition contains an unterminated comment. + * Comments within a preprocessor definition can be continued without the backslash. + * + * @return is true or false. + */ +bool ASBeautifier::isInPreprocessorUnterminatedComment(const string& line) +{ + if (!isInPreprocessorComment) + { + size_t startPos = line.find("/*"); + if (startPos == string::npos) + return false; + } + size_t endNum = line.find("*/"); + if (endNum != string::npos) + { + isInPreprocessorComment = false; + return false; + } + isInPreprocessorComment = true; + return true; +} + +void ASBeautifier::popLastInStatementIndent() +{ + assert(!inStatementIndentStackSizeStack->empty()); + int previousIndentStackSize = inStatementIndentStackSizeStack->back(); + if (inStatementIndentStackSizeStack->size() > 1) + inStatementIndentStackSizeStack->pop_back(); + while (previousIndentStackSize < (int) inStatementIndentStack->size()) + inStatementIndentStack->pop_back(); +} + +// for unit testing +int ASBeautifier::getBeautifierFileType() const +{ return beautifierFileType; } + +/** + * Process preprocessor statements and update the beautifier stacks. + */ +void ASBeautifier::processPreprocessor(const string& preproc, const string& line) +{ + // When finding a multi-lined #define statement, the original beautifier + // 1. sets its isInDefineDefinition flag + // 2. clones a new beautifier that will be used for the actual indentation + // of the #define. This clone is put into the activeBeautifierStack in order + // to be called for the actual indentation. + // The original beautifier will have isInDefineDefinition = true, isInDefine = false + // The cloned beautifier will have isInDefineDefinition = true, isInDefine = true + if (shouldIndentPreprocDefine && preproc == "define" && line[line.length() - 1] == '\\') + { + if (!isInDefineDefinition) + { + // this is the original beautifier + isInDefineDefinition = true; + + // push a new beautifier into the active stack + // this beautifier will be used for the indentation of this define + ASBeautifier* defineBeautifier = new ASBeautifier(*this); + activeBeautifierStack->push_back(defineBeautifier); + } + else + { + // the is the cloned beautifier that is in charge of indenting the #define. + isInDefine = true; + } + } + else if (preproc.length() >= 2 && preproc.substr(0, 2) == "if") + { + if (isPreprocessorConditionalCplusplus(line) && !g_preprocessorCppExternCBracket) + g_preprocessorCppExternCBracket = 1; + // push a new beautifier into the stack + waitingBeautifierStackLengthStack->push_back(waitingBeautifierStack->size()); + activeBeautifierStackLengthStack->push_back(activeBeautifierStack->size()); + if (activeBeautifierStackLengthStack->back() == 0) + waitingBeautifierStack->push_back(new ASBeautifier(*this)); + else + waitingBeautifierStack->push_back(new ASBeautifier(*activeBeautifierStack->back())); + } + else if (preproc == "else") + { + if (waitingBeautifierStack && !waitingBeautifierStack->empty()) + { + // MOVE current waiting beautifier to active stack. + activeBeautifierStack->push_back(waitingBeautifierStack->back()); + waitingBeautifierStack->pop_back(); + } + } + else if (preproc == "elif" || preproc == "elseif") + { + if (waitingBeautifierStack && !waitingBeautifierStack->empty()) + { + // append a COPY current waiting beautifier to active stack, WITHOUT deleting the original. + activeBeautifierStack->push_back(new ASBeautifier(*(waitingBeautifierStack->back()))); + } + } + else if (preproc == "endif" || preproc == "end") + { + int stackLength = 0; + ASBeautifier* beautifier = NULL; + + if (waitingBeautifierStackLengthStack != NULL && !waitingBeautifierStackLengthStack->empty()) + { + stackLength = waitingBeautifierStackLengthStack->back(); + waitingBeautifierStackLengthStack->pop_back(); + while ((int) waitingBeautifierStack->size() > stackLength) + { + beautifier = waitingBeautifierStack->back(); + waitingBeautifierStack->pop_back(); + delete beautifier; + } + } + + if (!activeBeautifierStackLengthStack->empty()) + { + stackLength = activeBeautifierStackLengthStack->back(); + activeBeautifierStackLengthStack->pop_back(); + while ((int) activeBeautifierStack->size() > stackLength) + { + beautifier = activeBeautifierStack->back(); + activeBeautifierStack->pop_back(); + delete beautifier; + } + } + } +} + +// Compute the preliminary indentation based on data in the headerStack +// and data from previous lines. +// Update the class variable indentCount. +void ASBeautifier::computePreliminaryIndentation() +{ + indentCount = 0; + spaceIndentCount = 0; + isInClassHeaderTab = false; + + if (isInObjCMethodDefinition && !inStatementIndentStack->empty()) + spaceIndentObjCMethodDefinition = inStatementIndentStack->back(); + + if (!inStatementIndentStack->empty()) + spaceIndentCount = inStatementIndentStack->back(); + + for (size_t i = 0; i < headerStack->size(); i++) + { + isInClass = false; + + if (blockIndent) + { + // do NOT indent opening block for these headers + if (!((*headerStack)[i] == &AS_NAMESPACE + || (*headerStack)[i] == &AS_CLASS + || (*headerStack)[i] == &AS_STRUCT + || (*headerStack)[i] == &AS_UNION + || (*headerStack)[i] == &AS_INTERFACE + || (*headerStack)[i] == &AS_THROWS + || (*headerStack)[i] == &AS_STATIC)) + ++indentCount; + } + else if (!(i > 0 && (*headerStack)[i - 1] != &AS_OPEN_BRACKET + && (*headerStack)[i] == &AS_OPEN_BRACKET)) + ++indentCount; + + if (!isJavaStyle() && !namespaceIndent && i > 0 + && (*headerStack)[i - 1] == &AS_NAMESPACE + && (*headerStack)[i] == &AS_OPEN_BRACKET) + --indentCount; + + if (isCStyle() && i >= 1 + && (*headerStack)[i - 1] == &AS_CLASS + && (*headerStack)[i] == &AS_OPEN_BRACKET) + { + if (classIndent) + ++indentCount; + isInClass = true; + } + + // is the switchIndent option is on, indent switch statements an additional indent. + else if (switchIndent && i > 1 + && (*headerStack)[i - 1] == &AS_SWITCH + && (*headerStack)[i] == &AS_OPEN_BRACKET) + { + ++indentCount; + isInSwitch = true; + } + + } // end of for loop + + if (isInClassHeader) + { + if (!isJavaStyle()) + isInClassHeaderTab = true; + if (lineOpensWithLineComment || lineStartsInComment || lineOpensWithComment) + { + if (!lineBeginsWithOpenBracket) + --indentCount; + if (!inStatementIndentStack->empty()) + spaceIndentCount -= inStatementIndentStack->back(); + } + else if (blockIndent) + { + if (!lineBeginsWithOpenBracket) + ++indentCount; + } + } + + if (isInClassInitializer || isInEnumTypeID) + { + indentCount += classInitializerIndents; + } + + if (isInEnum && lineBeginsWithComma && !inStatementIndentStack->empty()) + { + // unregister '=' indent from the previous line + inStatementIndentStack->pop_back(); + isInStatement = false; + spaceIndentCount = 0; + } + + // Objective-C interface continuation line + if (isInObjCInterface) + ++indentCount; + + // unindent a class closing bracket... + if (!lineStartsInComment + && isCStyle() + && isInClass + && classIndent + && headerStack->size() >= 2 + && (*headerStack)[headerStack->size() - 2] == &AS_CLASS + && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACKET + && lineBeginsWithCloseBracket + && bracketBlockStateStack->back() == true) + --indentCount; + + // unindent an indented switch closing bracket... + else if (!lineStartsInComment + && isInSwitch + && switchIndent + && headerStack->size() >= 2 + && (*headerStack)[headerStack->size() - 2] == &AS_SWITCH + && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACKET + && lineBeginsWithCloseBracket) + --indentCount; + + // handle special case of horstmann comment in an indented class statement + if (isInClass + && classIndent + && isInHorstmannComment + && !lineOpensWithComment + && headerStack->size() > 1 + && (*headerStack)[headerStack->size() - 2] == &AS_CLASS) + --indentCount; + + if (isInConditional) + --indentCount; + if (g_preprocessorCppExternCBracket >= 4) + --indentCount; +} + +void ASBeautifier::adjustParsedLineIndentation(size_t iPrelim, bool isInExtraHeaderIndent) +{ + if (lineStartsInComment) + return; + + // unindent a one-line statement in a header indent + if (!blockIndent + && lineBeginsWithOpenBracket + && headerStack->size() < iPrelim + && isInExtraHeaderIndent + && (lineOpeningBlocksNum > 0 && lineOpeningBlocksNum <= lineClosingBlocksNum) + && shouldIndentBrackettedLine) + --indentCount; + + /* + * if '{' doesn't follow an immediately previous '{' in the headerStack + * (but rather another header such as "for" or "if", then unindent it + * by one indentation relative to its block. + */ + else if (!blockIndent + && lineBeginsWithOpenBracket + && !(lineOpeningBlocksNum > 0 && lineOpeningBlocksNum <= lineClosingBlocksNum) + && (headerStack->size() > 1 && (*headerStack)[headerStack->size() - 2] != &AS_OPEN_BRACKET) + && shouldIndentBrackettedLine) + --indentCount; + + // must check one less in headerStack if more than one header on a line (allow-addins)... + else if (headerStack->size() > iPrelim + 1 + && !blockIndent + && lineBeginsWithOpenBracket + && !(lineOpeningBlocksNum > 0 && lineOpeningBlocksNum <= lineClosingBlocksNum) + && (headerStack->size() > 2 && (*headerStack)[headerStack->size() - 3] != &AS_OPEN_BRACKET) + && shouldIndentBrackettedLine) + --indentCount; + + // unindent a closing bracket... + else if (lineBeginsWithCloseBracket + && shouldIndentBrackettedLine) + --indentCount; + + // correctly indent one-line-blocks... + else if (lineOpeningBlocksNum > 0 + && lineOpeningBlocksNum == lineClosingBlocksNum + && previousLineProbationTab) + --indentCount; + + if (indentCount < 0) + indentCount = 0; + + // take care of extra bracket indentation option... + if (!lineStartsInComment + && bracketIndent + && shouldIndentBrackettedLine + && (lineBeginsWithOpenBracket || lineBeginsWithCloseBracket)) + { + if (!bracketIndentVtk) + ++indentCount; + else + { + // determine if a style VTK bracket is indented + bool haveUnindentedBracket = false; + for (size_t i = 0; i < headerStack->size(); i++) + { + if (((*headerStack)[i] == &AS_NAMESPACE + || (*headerStack)[i] == &AS_CLASS + || (*headerStack)[i] == &AS_STRUCT) + && i + 1 < headerStack->size() + && (*headerStack)[i + 1] == &AS_OPEN_BRACKET) + i++; + else if (lineBeginsWithOpenBracket) + { + // don't double count the current bracket + if (i + 1 < headerStack->size() + && (*headerStack)[i] == &AS_OPEN_BRACKET) + haveUnindentedBracket = true; + } + else if ((*headerStack)[i] == &AS_OPEN_BRACKET) + haveUnindentedBracket = true; + } // end of for loop + if (haveUnindentedBracket) + ++indentCount; + } + } +} + +/** + * Compute indentCount adjustment when in a series of else-if statements + * and shouldBreakElseIfs is requested. + * It increments by one for each 'else' in the tempStack. + */ +int ASBeautifier::adjustIndentCountForBreakElseIfComments() const +{ + assert(isElseHeaderIndent && !tempStacks->empty()); + int indentCountIncrement = 0; + vector* lastTempStack = tempStacks->back(); + if (lastTempStack != NULL) + { + for (size_t i = 0; i < lastTempStack->size(); i++) + { + if (*lastTempStack->at(i) == AS_ELSE) + indentCountIncrement++; + } + } + return indentCountIncrement; +} + +/** + * Extract a preprocessor statement without the #. + * If a error occurs an empty string is returned. + */ +string ASBeautifier::extractPreprocessorStatement(const string& line) const +{ + string preproc; + size_t start = line.find_first_not_of("#/ \t"); + if (start == string::npos) + return preproc; + size_t end = line.find_first_of("/ \t", start); + if (end == string::npos) + end = line.length(); + preproc = line.substr(start, end - start); + return preproc; +} + +/** + * Clear the variables used to align the Objective-C method definitions. + */ +void ASBeautifier::clearObjCMethodDefinitionAlignment() +{ + assert(isImmediatelyPostObjCMethodDefinition); + spaceIndentCount = 0; + spaceIndentObjCMethodDefinition = 0; + colonIndentObjCMethodDefinition = 0; + objCColonAlignSubsequent = 0; + isInObjCMethodDefinition = false; + isImmediatelyPostObjCMethodDefinition = false; + if (!inStatementIndentStack->empty()) + inStatementIndentStack->pop_back(); +} + +/** + * Compute the spaceIndentCount necessary to align the current line colon + * with the colon position in the argument. + * If it cannot be aligned indentLength is returned and a new colon + * position is calculated. + */ +int ASBeautifier::computeObjCColonAlignment(string& line, int colonAlignPosition) const +{ + int colonPosition = line.find(':'); + if (colonPosition < 0 || colonPosition > colonAlignPosition) + return indentLength; + return (colonAlignPosition - colonPosition); +} + +/** + * Parse the current line to update indentCount and spaceIndentCount. + */ +void ASBeautifier::parseCurrentLine(const string& line) +{ + bool isInLineComment = false; + bool isInOperator = false; + bool isSpecialChar = false; + bool haveCaseIndent = false; + bool haveAssignmentThisLine = false; + bool closingBracketReached = false; + bool previousLineProbation = (probationHeader != NULL); + char ch = ' '; + int tabIncrementIn = 0; + + for (size_t i = 0; i < line.length(); i++) + { + ch = line[i]; + + if (isInBeautifySQL) + continue; + + if (isWhiteSpace(ch)) + { + if (ch == '\t') + tabIncrementIn += convertTabToSpaces(i, tabIncrementIn); + continue; + } + + // handle special characters (i.e. backslash+character such as \n, \t, ...) + + if (isInQuote && !isInVerbatimQuote) + { + if (isSpecialChar) + { + isSpecialChar = false; + continue; + } + if (line.compare(i, 2, "\\\\") == 0) + { + i++; + continue; + } + if (ch == '\\') + { + if (peekNextChar(line, i) == ' ') // is this '\' at end of line + haveLineContinuationChar = true; + else + isSpecialChar = true; + continue; + } + } + else if (isInDefine && ch == '\\') + continue; + + // handle quotes (such as 'x' and "Hello Dolly") + if (!(isInComment || isInLineComment) + && (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i)))) + { + if (!isInQuote) + { + quoteChar = ch; + isInQuote = true; + char prevCh = i > 0 ? line[i - 1] : ' '; + if (isCStyle() && prevCh == 'R') + { + int parenPos = line.find('(', i); + if (parenPos != -1) + { + isInVerbatimQuote = true; + verbatimDelimiter = line.substr(i + 1, parenPos - i - 1); + } + } + else if (isSharpStyle() && prevCh == '@') + isInVerbatimQuote = true; + // check for "C" following "extern" + else if (g_preprocessorCppExternCBracket == 2 && line.compare(i, 3, "\"C\"") == 0) + ++g_preprocessorCppExternCBracket; + } + else if (isInVerbatimQuote && ch == '"') + { + if (isCStyle()) + { + string delim = ')' + verbatimDelimiter; + int delimStart = i - delim.length(); + if (delimStart > 0 && line.substr(delimStart, delim.length()) == delim) + { + isInQuote = false; + isInVerbatimQuote = false; + } + } + else if (isSharpStyle()) + { + if (peekNextChar(line, i) == '"') // check consecutive quotes + i++; + else + { + isInQuote = false; + isInVerbatimQuote = false; + } + } + } + else if (quoteChar == ch) + { + isInQuote = false; + isInStatement = true; + continue; + } + } + if (isInQuote) + continue; + + // handle comments + + if (!(isInComment || isInLineComment) && line.compare(i, 2, "//") == 0) + { + // if there is a 'case' statement after these comments unindent by 1 + if (isCaseHeaderCommentIndent) + --indentCount; + // isElseHeaderIndent is set by ASFormatter if shouldBreakElseIfs is requested + // if there is an 'else' after these comments a tempStacks indent is required + if (isElseHeaderIndent && lineOpensWithLineComment && !tempStacks->empty()) + indentCount += adjustIndentCountForBreakElseIfComments(); + isInLineComment = true; + i++; + continue; + } + else if (!(isInComment || isInLineComment) && line.compare(i, 2, "/*") == 0) + { + // if there is a 'case' statement after these comments unindent by 1 + if (isCaseHeaderCommentIndent && lineOpensWithComment) + --indentCount; + // isElseHeaderIndent is set by ASFormatter if shouldBreakElseIfs is requested + // if there is an 'else' after these comments a tempStacks indent is required + if (isElseHeaderIndent && lineOpensWithComment && !tempStacks->empty()) + indentCount += adjustIndentCountForBreakElseIfComments(); + isInComment = true; + i++; + if (!lineOpensWithComment) // does line start with comment? + blockCommentNoIndent = true; // if no, cannot indent continuation lines + continue; + } + else if ((isInComment || isInLineComment) && line.compare(i, 2, "*/") == 0) + { + size_t firstText = line.find_first_not_of(" \t"); + // if there is a 'case' statement after these comments unindent by 1 + // only if the ending comment is the first entry on the line + if (isCaseHeaderCommentIndent && firstText == i) + --indentCount; + // if this comment close starts the line, must check for else-if indent + // isElseHeaderIndent is set by ASFormatter if shouldBreakElseIfs is requested + // if there is an 'else' after these comments a tempStacks indent is required + if (firstText == i) + { + if (isElseHeaderIndent && !lineOpensWithComment && !tempStacks->empty()) + indentCount += adjustIndentCountForBreakElseIfComments(); + } + isInComment = false; + i++; + blockCommentNoIndent = false; // ok to indent next comment + continue; + } + // treat indented preprocessor lines as a line comment + else if (line[0] == '#' && isIndentedPreprocessor(line, i)) + { + isInLineComment = true; + } + + if (isInLineComment) + { + // bypass rest of the comment up to the comment end + while (i + 1 < line.length()) + i++; + + continue; + } + if (isInComment) + { + // if there is a 'case' statement after these comments unindent by 1 + if (!lineOpensWithComment && isCaseHeaderCommentIndent) + --indentCount; + // isElseHeaderIndent is set by ASFormatter if shouldBreakElseIfs is requested + // if there is an 'else' after these comments a tempStacks indent is required + if (!lineOpensWithComment && isElseHeaderIndent && !tempStacks->empty()) + indentCount += adjustIndentCountForBreakElseIfComments(); + // bypass rest of the comment up to the comment end + while (i + 1 < line.length() + && line.compare(i + 1, 2, "*/") != 0) + i++; + + continue; + } + + // if we have reached this far then we are NOT in a comment or string of special character... + + if (probationHeader != NULL) + { + if ((probationHeader == &AS_STATIC && ch == '{') + || (probationHeader == &AS_SYNCHRONIZED && ch == '(')) + { + // insert the probation header as a new header + isInHeader = true; + headerStack->push_back(probationHeader); + + // handle the specific probation header + isInConditional = (probationHeader == &AS_SYNCHRONIZED); + + isInStatement = false; + // if the probation comes from the previous line, then indent by 1 tab count. + if (previousLineProbation + && ch == '{' + && !(blockIndent && probationHeader == &AS_STATIC)) + { + ++indentCount; + previousLineProbationTab = true; + } + previousLineProbation = false; + } + + // dismiss the probation header + probationHeader = NULL; + } + + prevNonSpaceCh = currentNonSpaceCh; + currentNonSpaceCh = ch; + if (!isLegalNameChar(ch) && ch != ',' && ch != ';') + { + prevNonLegalCh = currentNonLegalCh; + currentNonLegalCh = ch; + } + + if (isInHeader) + { + isInHeader = false; + currentHeader = headerStack->back(); + } + else + currentHeader = NULL; + + if (isCStyle() && isInTemplate + && (ch == '<' || ch == '>') + && !(line.length() > i + 1 && line.compare(i, 2, ">=") == 0)) + { + if (ch == '<') + { + ++templateDepth; + inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); + registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); + } + else if (ch == '>') + { + popLastInStatementIndent(); + if (--templateDepth <= 0) + { + ch = ';'; + isInTemplate = false; + templateDepth = 0; + } + } + } + + // handle parentheses + if (ch == '(' || ch == '[' || ch == ')' || ch == ']') + { + if (ch == '(' || ch == '[') + { + isInOperator = false; + // if have a struct header, this is a declaration not a definition + if (ch == '(' + && !headerStack->empty() + && headerStack->back() == &AS_STRUCT) + { + headerStack->pop_back(); + isInClassHeader = false; + if (line.find(AS_STRUCT, 0) > i) // if not on this line + indentCount -= classInitializerIndents; + if (indentCount < 0) + indentCount = 0; + } + + if (parenDepth == 0) + { + parenStatementStack->push_back(isInStatement); + isInStatement = true; + } + parenDepth++; + if (ch == '[') + ++squareBracketCount; + + inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); + + if (currentHeader != NULL) + registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, minConditionalIndent/*indentLength*2*/, true); + else + registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); + } + else if (ch == ')' || ch == ']') + { + if (ch == ']') + --squareBracketCount; + if (squareBracketCount < 0) + squareBracketCount = 0; + foundPreCommandHeader = false; + parenDepth--; + if (parenDepth == 0) + { + if (!parenStatementStack->empty()) // in case of unmatched closing parens + { + isInStatement = parenStatementStack->back(); + parenStatementStack->pop_back(); + } + isInAsm = false; + isInConditional = false; + } + + if (!inStatementIndentStackSizeStack->empty()) + { + popLastInStatementIndent(); + + if (!parenIndentStack->empty()) + { + int poppedIndent = parenIndentStack->back(); + parenIndentStack->pop_back(); + + if (i == 0) + spaceIndentCount = poppedIndent; + } + } + } + continue; + } + + if (ch == '{') + { + // first, check if '{' is a block-opener or a static-array opener + bool isBlockOpener = ((prevNonSpaceCh == '{' && bracketBlockStateStack->back()) + || prevNonSpaceCh == '}' + || prevNonSpaceCh == ')' + || prevNonSpaceCh == ';' + || peekNextChar(line, i) == '{' + || foundPreCommandHeader + || foundPreCommandMacro + || isInClassHeader + || (isInClassInitializer && !isLegalNameChar(prevNonSpaceCh)) + || isNonInStatementArray + || isInObjCMethodDefinition + || isInObjCInterface + || isSharpAccessor + || isSharpDelegate + || isInExternC + || isInAsmBlock + || getNextWord(line, i) == AS_NEW + || (isInDefine + && (prevNonSpaceCh == '(' + || isLegalNameChar(prevNonSpaceCh)))); + + if (isInObjCMethodDefinition) + isImmediatelyPostObjCMethodDefinition = true; + + if (!isBlockOpener && !isInStatement && !isInClassInitializer && !isInEnum) + { + if (headerStack->empty()) + isBlockOpener = true; + else if (headerStack->back() == &AS_NAMESPACE + || headerStack->back() == &AS_CLASS + || headerStack->back() == &AS_INTERFACE + || headerStack->back() == &AS_STRUCT + || headerStack->back() == &AS_UNION) + isBlockOpener = true; + } + + if (!isBlockOpener && currentHeader != NULL) + { + for (size_t n = 0; n < nonParenHeaders->size(); n++) + if (currentHeader == (*nonParenHeaders)[n]) + { + isBlockOpener = true; + break; + } + } + + bracketBlockStateStack->push_back(isBlockOpener); + + if (!isBlockOpener) + { + inStatementIndentStackSizeStack->push_back(inStatementIndentStack->size()); + registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, true); + parenDepth++; + if (i == 0) + shouldIndentBrackettedLine = false; + isInEnumTypeID = false; + + continue; + } + + // this bracket is a block opener... + + ++lineOpeningBlocksNum; + + if (isInClassInitializer || isInEnumTypeID) + { + // decrease tab count if bracket is broken + if (lineBeginsWithOpenBracket) + { + indentCount -= classInitializerIndents; + // decrease one more if an empty class + if (!headerStack->empty() + && (*headerStack).back() == &AS_CLASS) + { + int nextChar = getNextProgramCharDistance(line, i); + if ((int) line.length() > nextChar && line[nextChar] == '}') + --indentCount; + } + } + } + + if (isInObjCInterface) + { + isInObjCInterface = false; + if (lineBeginsWithOpenBracket) + --indentCount; + } + + if (bracketIndent && !namespaceIndent && !headerStack->empty() + && (*headerStack).back() == &AS_NAMESPACE) + { + shouldIndentBrackettedLine = false; + --indentCount; + } + + // an indentable struct is treated like a class in the header stack + if (!headerStack->empty() + && (*headerStack).back() == &AS_STRUCT + && isInIndentableStruct) + (*headerStack).back() = &AS_CLASS; + + blockParenDepthStack->push_back(parenDepth); + blockStatementStack->push_back(isInStatement); + + if (!inStatementIndentStack->empty()) + { + // completely purge the inStatementIndentStack + while (!inStatementIndentStack->empty()) + popLastInStatementIndent(); + if (isInClassInitializer || isInClassHeaderTab) + { + if (lineBeginsWithOpenBracket || lineBeginsWithComma) + spaceIndentCount = 0; + } + else + spaceIndentCount = 0; + } + + blockTabCount += (isInStatement ? 1 : 0); + if (g_preprocessorCppExternCBracket == 3) + ++g_preprocessorCppExternCBracket; + parenDepth = 0; + isInClassHeader = false; + isInClassHeaderTab = false; + isInClassInitializer = false; + isInEnumTypeID = false; + isInStatement = false; + isInQuestion = false; + isInLet = false; + foundPreCommandHeader = false; + foundPreCommandMacro = false; + isInExternC = false; + + tempStacks->push_back(new vector); + headerStack->push_back(&AS_OPEN_BRACKET); + lastLineHeader = &AS_OPEN_BRACKET; + + continue; + } // end '{' + + //check if a header has been reached + bool isPotentialHeader = isCharPotentialHeader(line, i); + + if (isPotentialHeader && !squareBracketCount) + { + const string* newHeader = findHeader(line, i, headers); + + // Qt headers may be variables in C++ + if (isCStyle() + && (newHeader == &AS_FOREVER || newHeader == &AS_FOREACH)) + { + if (line.find_first_of("=;", i) != string::npos) + newHeader = NULL; + } + else if (newHeader == &AS_USING + && ASBeautifier::peekNextChar(line, i + (*newHeader).length() - 1) != '(') + newHeader = NULL; + + if (newHeader != NULL) + { + // if we reached here, then this is a header... + bool isIndentableHeader = true; + + isInHeader = true; + + vector* lastTempStack; + if (tempStacks->empty()) + lastTempStack = NULL; + else + lastTempStack = tempStacks->back(); + + // if a new block is opened, push a new stack into tempStacks to hold the + // future list of headers in the new block. + + // take care of the special case: 'else if (...)' + if (newHeader == &AS_IF && lastLineHeader == &AS_ELSE) + { + headerStack->pop_back(); + } + + // take care of 'else' + else if (newHeader == &AS_ELSE) + { + if (lastTempStack != NULL) + { + int indexOfIf = indexOf(*lastTempStack, &AS_IF); + if (indexOfIf != -1) + { + // recreate the header list in headerStack up to the previous 'if' + // from the temporary snapshot stored in lastTempStack. + int restackSize = lastTempStack->size() - indexOfIf - 1; + for (int r = 0; r < restackSize; r++) + { + headerStack->push_back(lastTempStack->back()); + lastTempStack->pop_back(); + } + if (!closingBracketReached) + indentCount += restackSize; + } + /* + * If the above if is not true, i.e. no 'if' before the 'else', + * then nothing beautiful will come out of this... + * I should think about inserting an Exception here to notify the caller of this... + */ + } + } + + // check if 'while' closes a previous 'do' + else if (newHeader == &AS_WHILE) + { + if (lastTempStack != NULL) + { + int indexOfDo = indexOf(*lastTempStack, &AS_DO); + if (indexOfDo != -1) + { + // recreate the header list in headerStack up to the previous 'do' + // from the temporary snapshot stored in lastTempStack. + int restackSize = lastTempStack->size() - indexOfDo - 1; + for (int r = 0; r < restackSize; r++) + { + headerStack->push_back(lastTempStack->back()); + lastTempStack->pop_back(); + } + if (!closingBracketReached) + indentCount += restackSize; + } + } + } + // check if 'catch' closes a previous 'try' or 'catch' + else if (newHeader == &AS_CATCH || newHeader == &AS_FINALLY) + { + if (lastTempStack != NULL) + { + int indexOfTry = indexOf(*lastTempStack, &AS_TRY); + if (indexOfTry == -1) + indexOfTry = indexOf(*lastTempStack, &AS_CATCH); + if (indexOfTry != -1) + { + // recreate the header list in headerStack up to the previous 'try' + // from the temporary snapshot stored in lastTempStack. + int restackSize = lastTempStack->size() - indexOfTry - 1; + for (int r = 0; r < restackSize; r++) + { + headerStack->push_back(lastTempStack->back()); + lastTempStack->pop_back(); + } + + if (!closingBracketReached) + indentCount += restackSize; + } + } + } + else if (newHeader == &AS_CASE) + { + isInCase = true; + if (!haveCaseIndent) + { + haveCaseIndent = true; + if (!lineBeginsWithOpenBracket) + --indentCount; + } + } + else if (newHeader == &AS_DEFAULT) + { + isInCase = true; + --indentCount; + } + else if (newHeader == &AS_STATIC + || newHeader == &AS_SYNCHRONIZED) + { + if (!headerStack->empty() + && (headerStack->back() == &AS_STATIC + || headerStack->back() == &AS_SYNCHRONIZED)) + { + isIndentableHeader = false; + } + else + { + isIndentableHeader = false; + probationHeader = newHeader; + } + } + else if (newHeader == &AS_TEMPLATE) + { + isInTemplate = true; + isIndentableHeader = false; + } + + if (isIndentableHeader) + { + headerStack->push_back(newHeader); + isInStatement = false; + if (indexOf(*nonParenHeaders, newHeader) == -1) + { + isInConditional = true; + } + lastLineHeader = newHeader; + } + else + isInHeader = false; + + i += newHeader->length() - 1; + + continue; + } // newHeader != NULL + + if (findHeader(line, i, preCommandHeaders)) + foundPreCommandHeader = true; + + // Objective-C NSException macros are preCommandHeaders + if (isCStyle() && findKeyword(line, i, AS_NS_DURING)) + foundPreCommandMacro = true; + if (isCStyle() && findKeyword(line, i, AS_NS_HANDLER)) + foundPreCommandMacro = true; + + if (parenDepth == 0 && findKeyword(line, i, AS_ENUM)) + isInEnum = true; + + if (isSharpStyle() && findKeyword(line, i, AS_LET)) + isInLet = true; + + } // isPotentialHeader + + if (ch == '?') + isInQuestion = true; + + // special handling of colons + if (ch == ':') + { + if (line.length() > i + 1 && line[i + 1] == ':') // look for :: + { + ++i; + continue; + } + else if (isInQuestion) + { + // do nothing special + } + else if (parenDepth > 0) + { + // found a 'for' loop or an objective-C statement + // so do nothing special + } + else if (isInEnum) + { + // found an enum with a base-type + isInEnumTypeID = true; + if (i == 0) + indentCount += classInitializerIndents; + } + else if (isCStyle() + && !isInCase + && (prevNonSpaceCh == ')' || foundPreCommandHeader)) + { + // found a 'class' c'tor initializer + isInClassInitializer = true; + registerInStatementIndentColon(line, i, tabIncrementIn); + if (i == 0) + indentCount += classInitializerIndents; + } + else if (isInClassHeader || isInObjCInterface) + { + // is in a 'class A : public B' definition + isInClassHeaderTab = true; + registerInStatementIndentColon(line, i, tabIncrementIn); + } + else if (isInAsm || isInAsmOneLine || isInAsmBlock) + { + // do nothing special + } + else if (isDigit(peekNextChar(line, i))) + { + // found a bit field - do nothing special + } + else if (isCStyle() && isInClass && prevNonSpaceCh != ')') + { + // found a 'private:' or 'public:' inside a class definition + --indentCount; + if (modifierIndent) + spaceIndentCount += (indentLength / 2); + } + else if (isCStyle() && !isInClass + && headerStack->size() >= 2 + && (*headerStack)[headerStack->size() - 2] == &AS_CLASS + && (*headerStack)[headerStack->size() - 1] == &AS_OPEN_BRACKET) + { + // found a 'private:' or 'public:' inside a class definition + // and on the same line as the class opening bracket + // do nothing + } + else if (isJavaStyle() && lastLineHeader == &AS_FOR) + { + // found a java for-each statement + // so do nothing special + } + else + { + currentNonSpaceCh = ';'; // so that brackets after the ':' will appear as block-openers + char peekedChar = peekNextChar(line, i); + if (isInCase) + { + isInCase = false; + ch = ';'; // from here on, treat char as ';' + } + else if (isCStyle() || (isSharpStyle() && peekedChar == ';')) + { + // is in a label (e.g. 'label1:') + if (labelIndent) + --indentCount; // unindent label by one indent + else if (!lineBeginsWithOpenBracket) + indentCount = 0; // completely flush indent to left + } + } + } + + if ((ch == ';' || (parenDepth > 0 && ch == ',')) && !inStatementIndentStackSizeStack->empty()) + while ((int) inStatementIndentStackSizeStack->back() + (parenDepth > 0 ? 1 : 0) + < (int) inStatementIndentStack->size()) + inStatementIndentStack->pop_back(); + + else if (ch == ',' && isInEnum && isNonInStatementArray && !inStatementIndentStack->empty()) + inStatementIndentStack->pop_back(); + + // handle commas + // previous "isInStatement" will be from an assignment operator or class initializer + if (ch == ',' && parenDepth == 0 && !isInStatement && !isNonInStatementArray) + { + // is comma at end of line + size_t nextChar = line.find_first_not_of(" \t", i + 1); + if (nextChar != string::npos) + { + if (line.compare(nextChar, 2, "//") == 0 + || line.compare(nextChar, 2, "/*") == 0) + nextChar = string::npos; + } + // register indent + if (nextChar == string::npos) + { + // register indent at previous word + if (isJavaStyle() && isInClassHeader) + { + // do nothing for now + } + // register indent at second word on the line + else if (!isInTemplate && !isInClassHeaderTab && !isInClassInitializer) + { + int prevWord = getInStatementIndentComma(line, i); + int inStatementIndent = prevWord + spaceIndentCount + tabIncrementIn; + inStatementIndentStack->push_back(inStatementIndent); + isInStatement = true; + } + } + } + // handle comma first initializers + if (ch == ',' && parenDepth == 0 && lineBeginsWithComma + && (isInClassInitializer || isInClassHeaderTab)) + spaceIndentCount = 0; + + // handle ends of statements + if ((ch == ';' && parenDepth == 0) || ch == '}') + { + if (ch == '}') + { + // first check if this '}' closes a previous block, or a static array... + if (bracketBlockStateStack->size() > 1) + { + bool bracketBlockState = bracketBlockStateStack->back(); + bracketBlockStateStack->pop_back(); + if (!bracketBlockState) + { + if (!inStatementIndentStackSizeStack->empty()) + { + // this bracket is a static array + popLastInStatementIndent(); + parenDepth--; + if (i == 0) + shouldIndentBrackettedLine = false; + + if (!parenIndentStack->empty()) + { + int poppedIndent = parenIndentStack->back(); + parenIndentStack->pop_back(); + if (i == 0) + spaceIndentCount = poppedIndent; + } + } + continue; + } + } + + // this bracket is block closer... + + ++lineClosingBlocksNum; + + if (!inStatementIndentStackSizeStack->empty()) + popLastInStatementIndent(); + + if (!blockParenDepthStack->empty()) + { + parenDepth = blockParenDepthStack->back(); + blockParenDepthStack->pop_back(); + isInStatement = blockStatementStack->back(); + blockStatementStack->pop_back(); + + if (isInStatement) + blockTabCount--; + } + + closingBracketReached = true; + if (i == 0) + spaceIndentCount = 0; + isInAsmBlock = false; + isInAsm = isInAsmOneLine = isInQuote = false; // close these just in case + + int headerPlace = indexOf(*headerStack, &AS_OPEN_BRACKET); + if (headerPlace != -1) + { + const string* popped = headerStack->back(); + while (popped != &AS_OPEN_BRACKET) + { + headerStack->pop_back(); + popped = headerStack->back(); + } + headerStack->pop_back(); + + if (headerStack->empty()) + g_preprocessorCppExternCBracket = 0; + + // do not indent namespace bracket unless namespaces are indented + if (!namespaceIndent && !headerStack->empty() + && (*headerStack).back() == &AS_NAMESPACE + && i == 0) // must be the first bracket on the line + shouldIndentBrackettedLine = false; + + if (!tempStacks->empty()) + { + vector* temp = tempStacks->back(); + tempStacks->pop_back(); + delete temp; + } + } + + ch = ' '; // needed due to cases such as '}else{', so that headers ('else' in this case) will be identified... + } // ch == '}' + + /* + * Create a temporary snapshot of the current block's header-list in the + * uppermost inner stack in tempStacks, and clear the headerStack up to + * the beginning of the block. + * Thus, the next future statement will think it comes one indent past + * the block's '{' unless it specifically checks for a companion-header + * (such as a previous 'if' for an 'else' header) within the tempStacks, + * and recreates the temporary snapshot by manipulating the tempStacks. + */ + if (!tempStacks->back()->empty()) + while (!tempStacks->back()->empty()) + tempStacks->back()->pop_back(); + while (!headerStack->empty() && headerStack->back() != &AS_OPEN_BRACKET) + { + tempStacks->back()->push_back(headerStack->back()); + headerStack->pop_back(); + } + + if (parenDepth == 0 && ch == ';') + isInStatement = false; + if (isInObjCMethodDefinition) + isImmediatelyPostObjCMethodDefinition = true; + + previousLastLineHeader = NULL; + isInClassHeader = false; // for 'friend' class + isInEnum = false; + isInQuestion = false; + isInObjCInterface = false; + foundPreCommandHeader = false; + foundPreCommandMacro = false; + squareBracketCount = 0; + + continue; + } + + if (isPotentialHeader) + { + // check for preBlockStatements in C/C++ ONLY if not within parentheses + // (otherwise 'struct XXX' statements would be wrongly interpreted...) + if (!isInTemplate && !(isCStyle() && parenDepth > 0)) + { + const string* newHeader = findHeader(line, i, preBlockStatements); + if (newHeader != NULL + && !(isCStyle() && newHeader == &AS_CLASS && isInEnum)) // is not 'enum class' + { + if (!isSharpStyle()) + headerStack->push_back(newHeader); + // do not need 'where' in the headerStack + // do not need second 'class' statement in a row + else if (!(newHeader == &AS_WHERE + || (newHeader == &AS_CLASS + && !headerStack->empty() + && headerStack->back() == &AS_CLASS))) + headerStack->push_back(newHeader); + + if (!headerStack->empty()) + { + if ((*headerStack).back() == &AS_CLASS + || (*headerStack).back() == &AS_STRUCT + || (*headerStack).back() == &AS_INTERFACE) + { + isInClassHeader = true; + } + else if ((*headerStack).back() == &AS_NAMESPACE) + { + // remove inStatementIndent from namespace + if (!inStatementIndentStack->empty()) + inStatementIndentStack->pop_back(); + isInStatement = false; + } + } + + i += newHeader->length() - 1; + continue; + } + } + const string* foundIndentableHeader = findHeader(line, i, indentableHeaders); + + if (foundIndentableHeader != NULL) + { + // must bypass the header before registering the in statement + i += foundIndentableHeader->length() - 1; + if (!isInOperator && !isInTemplate && !isNonInStatementArray) + { + registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, false); + isInStatement = true; + } + continue; + } + + if (isCStyle() && findKeyword(line, i, AS_OPERATOR)) + isInOperator = true; + + if (g_preprocessorCppExternCBracket == 1 && findKeyword(line, i, AS_EXTERN)) + ++g_preprocessorCppExternCBracket; + + if (g_preprocessorCppExternCBracket == 3) // extern "C" is not followed by a '{' + g_preprocessorCppExternCBracket = 0; + + // "new" operator is a pointer, not a calculation + if (findKeyword(line, i, AS_NEW)) + { + if (isInStatement && !inStatementIndentStack->empty() && prevNonSpaceCh == '=' ) + inStatementIndentStack->back() = 0; + } + + if (isCStyle()) + { + if (findKeyword(line, i, AS_ASM) + || findKeyword(line, i, AS__ASM__)) + { + isInAsm = true; + } + else if (findKeyword(line, i, AS_MS_ASM) // microsoft specific + || findKeyword(line, i, AS_MS__ASM)) + { + int index = 4; + if (peekNextChar(line, i) == '_') // check for __asm + index = 5; + + char peekedChar = ASBase::peekNextChar(line, i + index); + if (peekedChar == '{' || peekedChar == ' ') + isInAsmBlock = true; + else + isInAsmOneLine = true; + } + } + + // bypass the entire name for all others + string name = getCurrentWord(line, i); + i += name.length() - 1; + continue; + } + + // Handle Objective-C statements + + if (ch == '@' + && isCharPotentialHeader(line, i + 1)) + { + string curWord = getCurrentWord(line, i + 1); + if (curWord == AS_INTERFACE && headerStack->empty()) + { + isInObjCInterface = true; + string name = '@' + curWord; + i += name.length() - 1; + continue; + } + else if (curWord == AS_PUBLIC + || curWord == AS_PRIVATE + || curWord == AS_PROTECTED) + { + --indentCount; + if (modifierIndent) + spaceIndentCount += (indentLength / 2); + string name = '@' + curWord; + i += name.length() - 1; + continue; + } + else if (curWord == AS_END) + { + popLastInStatementIndent(); + spaceIndentCount = 0; + if (isInObjCInterface) + --indentCount; + isInObjCInterface = false; + isInObjCMethodDefinition = false; + string name = '@' + curWord; + i += name.length() - 1; + continue; + } + } + else if ((ch == '-' || ch == '+') + && peekNextChar(line, i) == '(' + && headerStack->empty() + && line.find_first_not_of(" \t") == i) + { + if (isInObjCInterface) + --indentCount; + isInObjCInterface = false; + isInObjCMethodDefinition = true; + continue; + } + + // Handle operators + + bool isPotentialOperator = isCharPotentialOperator(ch); + + if (isPotentialOperator) + { + // Check if an operator has been reached. + const string* foundAssignmentOp = findOperator(line, i, assignmentOperators); + const string* foundNonAssignmentOp = findOperator(line, i, nonAssignmentOperators); + + if (foundNonAssignmentOp == &AS_LAMBDA) + foundPreCommandHeader = true; + + if (isInTemplate && foundNonAssignmentOp == &AS_GR_GR) + foundNonAssignmentOp = NULL; + + // Since findHeader's boundary checking was not used above, it is possible + // that both an assignment op and a non-assignment op where found, + // e.g. '>>' and '>>='. If this is the case, treat the LONGER one as the + // found operator. + if (foundAssignmentOp != NULL && foundNonAssignmentOp != NULL) + { + if (foundAssignmentOp->length() < foundNonAssignmentOp->length()) + foundAssignmentOp = NULL; + else + foundNonAssignmentOp = NULL; + } + + if (foundNonAssignmentOp != NULL) + { + if (foundNonAssignmentOp->length() > 1) + i += foundNonAssignmentOp->length() - 1; + + // For C++ input/output, operator<< and >> should be + // aligned, if we are not in a statement already and + // also not in the "operator<<(...)" header line + if (!isInOperator + && inStatementIndentStack->empty() + && isCStyle() + && (foundNonAssignmentOp == &AS_GR_GR + || foundNonAssignmentOp == &AS_LS_LS)) + { + // this will be true if the line begins with the operator + if (i < 2 && spaceIndentCount == 0) + spaceIndentCount += 2 * indentLength; + // align to the beginning column of the operator + registerInStatementIndent(line, i - foundNonAssignmentOp->length(), spaceIndentCount, tabIncrementIn, 0, false); + } + } + + else if (foundAssignmentOp != NULL) + { + foundPreCommandHeader = false; // clears this for array assignments + foundPreCommandMacro = false; + + if (foundAssignmentOp->length() > 1) + i += foundAssignmentOp->length() - 1; + + if (!isInOperator && !isInTemplate && (!isNonInStatementArray || isInEnum)) + { + // if multiple assignments, align on the previous word + if (foundAssignmentOp == &AS_ASSIGN + && prevNonSpaceCh != ']' // an array + && statementEndsWithComma(line, i)) + { + if (!haveAssignmentThisLine) // only one assignment indent per line + { + // register indent at previous word + haveAssignmentThisLine = true; + int prevWordIndex = getInStatementIndentAssign(line, i); + int inStatementIndent = prevWordIndex + spaceIndentCount + tabIncrementIn; + inStatementIndentStack->push_back(inStatementIndent); + isInStatement = true; + } + } + // don't indent an assignment if 'let' + else if (isInLet) + { + isInLet = false; + } + else + { + if (i == 0 && spaceIndentCount == 0) + spaceIndentCount += indentLength; + registerInStatementIndent(line, i, spaceIndentCount, tabIncrementIn, 0, false); + isInStatement = true; + } + } + } + } + } // end of for loop * end of for loop * end of for loop * end of for loop * end of for loop * +} + +} // end namespace astyle diff --git a/External/Tools/AStyle/src/ASEnhancer.cpp b/External/Tools/AStyle/src/ASEnhancer.cpp new file mode 100644 index 0000000000..dae0d1b3cf --- /dev/null +++ b/External/Tools/AStyle/src/ASEnhancer.cpp @@ -0,0 +1,796 @@ +// ASEnhancer.cpp +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. +// License.txt describes the conditions under which this software may be distributed. + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- + +#include "astyle.h" + +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- + +namespace astyle { +// +//----------------------------------------------------------------------------- +// ASEnhancer class +//----------------------------------------------------------------------------- + +/** + * ASEnhancer constructor + */ +ASEnhancer::ASEnhancer() +{ +} + +/** + * Destructor of ASEnhancer + */ +ASEnhancer::~ASEnhancer() +{ +} + +/** + * initialize the ASEnhancer. + * + * init() is called each time an ASFormatter object is initialized. + */ +void ASEnhancer::init(int _fileType, + int _indentLength, + int _tabLength, + bool _useTabs, + bool _forceTab, + bool _namespaceIndent, + bool _caseIndent, + bool _preprocBlockIndent, + bool _preprocDefineIndent, + bool _emptyLineFill, + vector* >* _indentableMacros) +{ + // formatting variables from ASFormatter and ASBeautifier + ASBase::init(_fileType); + indentLength = _indentLength; + tabLength = _tabLength; + useTabs = _useTabs; + forceTab = _forceTab; + namespaceIndent = _namespaceIndent; + caseIndent = _caseIndent; + preprocBlockIndent = _preprocBlockIndent; + preprocDefineIndent = _preprocDefineIndent; + emptyLineFill = _emptyLineFill; + indentableMacros = _indentableMacros; + quoteChar = '\''; + + // unindent variables + lineNumber = 0; + bracketCount = 0; + isInComment = false; + isInQuote = false; + switchDepth = 0; + eventPreprocDepth = 0; + lookingForCaseBracket = false; + unindentNextLine = false; + shouldUnindentLine = false; + shouldUnindentComment = false; + + // switch struct and vector + sw.switchBracketCount = 0; + sw.unindentDepth = 0; + sw.unindentCase = false; + switchStack.clear(); + + // other variables + nextLineIsEventIndent = false; + isInEventTable = false; + nextLineIsDeclareIndent = false; + isInDeclareSection = false; +} + +/** + * additional formatting for line of source code. + * every line of source code in a source code file should be sent + * one after the other to this function. + * indents event tables + * unindents the case blocks + * + * @param line the original formatted line will be updated if necessary. + */ +void ASEnhancer::enhance(string& line, bool isInNamespace, bool isInPreprocessor, bool isInSQL) +{ + shouldUnindentLine = true; + shouldUnindentComment = false; + lineNumber++; + + // check for beginning of event table + if (nextLineIsEventIndent) + { + isInEventTable = true; + nextLineIsEventIndent = false; + } + + // check for beginning of SQL declare section + if (nextLineIsDeclareIndent) + { + isInDeclareSection = true; + nextLineIsDeclareIndent = false; + } + + if (line.length() == 0 + && !isInEventTable + && !isInDeclareSection + && !emptyLineFill) + return; + + // test for unindent on attached brackets + if (unindentNextLine) + { + sw.unindentDepth++; + sw.unindentCase = true; + unindentNextLine = false; + } + + // parse characters in the current line + parseCurrentLine(line, isInPreprocessor, isInSQL); + + // check for SQL indentable lines + if (isInDeclareSection) + { + size_t firstText = line.find_first_not_of(" \t"); + if (firstText == string::npos || line[firstText] != '#') + indentLine(line, 1); + } + + // check for event table indentable lines + if (isInEventTable + && (eventPreprocDepth == 0 + || (namespaceIndent && isInNamespace))) + { + size_t firstText = line.find_first_not_of(" \t"); + if (firstText == string::npos || line[firstText] != '#') + indentLine(line, 1); + } + + if (shouldUnindentComment && sw.unindentDepth > 0) + unindentLine(line, sw.unindentDepth - 1); + else if (shouldUnindentLine && sw.unindentDepth > 0) + unindentLine(line, sw.unindentDepth); +} + +/** + * convert a force-tab indent to spaces + * + * @param line a reference to the line that will be converted. + */ +void ASEnhancer::convertForceTabIndentToSpaces(string& line) const +{ + // replace tab indents with spaces + for (size_t i = 0; i < line.length(); i++) + { + if (!isWhiteSpace(line[i])) + break; + if (line[i] == '\t') + { + line.erase(i, 1); + line.insert(i, tabLength, ' '); + i += tabLength - 1; + } + } +} + +/** + * convert a space indent to force-tab + * + * @param line a reference to the line that will be converted. + */ +void ASEnhancer::convertSpaceIndentToForceTab(string& line) const +{ + assert(tabLength > 0); + + // replace leading spaces with tab indents + size_t newSpaceIndentLength = line.find_first_not_of(" \t"); + size_t tabCount = newSpaceIndentLength / tabLength; // truncate extra spaces + line.replace(0U, tabCount * tabLength, tabCount, '\t'); +} + +/** + * find the colon following a 'case' statement + * + * @param line a reference to the line. + * @param caseIndex the line index of the case statement. + * @return the line index of the colon. + */ +size_t ASEnhancer::findCaseColon(string& line, size_t caseIndex) const +{ + size_t i = caseIndex; + bool isInQuote_ = false; + char quoteChar_ = ' '; + for (; i < line.length(); i++) + { + if (isInQuote_) + { + if (line[i] == '\\') + { + i++; + continue; + } + else if (line[i] == quoteChar_) // check ending quote + { + isInQuote_ = false; + quoteChar_ = ' '; + continue; + } + else + { + continue; // must close quote before continuing + } + } + if (line[i] == '"' // check opening quote + || (line[i] == '\'' && !isDigitSeparator(line, i))) + { + isInQuote_ = true; + quoteChar_ = line[i]; + continue; + } + if (line[i] == ':') + { + if ((i + 1 < line.length()) && (line[i + 1] == ':')) + i++; // bypass scope resolution operator + else + break; // found it + } + } + return i; +} + +/** +* indent a line by a given number of tabsets + * by inserting leading whitespace to the line argument. + * + * @param line a reference to the line to indent. + * @param indent the number of tabsets to insert. + * @return the number of characters inserted. + */ +int ASEnhancer::indentLine(string& line, int indent) const +{ + if (line.length() == 0 + && !emptyLineFill) + return 0; + + size_t charsToInsert = 0; + + if (forceTab && indentLength != tabLength) + { + // replace tab indents with spaces + convertForceTabIndentToSpaces(line); + // insert the space indents + charsToInsert = indent * indentLength; + line.insert(line.begin(), charsToInsert, ' '); + // replace leading spaces with tab indents + convertSpaceIndentToForceTab(line); + } + else if (useTabs) + { + charsToInsert = indent; + line.insert(line.begin(), charsToInsert, '\t'); + } + else // spaces + { + charsToInsert = indent * indentLength; + line.insert(line.begin(), charsToInsert, ' '); + } + + return charsToInsert; +} + +/** + * check for SQL "BEGIN DECLARE SECTION". + * must compare case insensitive and allow any spacing between words. + * + * @param line a reference to the line to indent. + * @param index the current line index. + * @return true if a hit. + */ +bool ASEnhancer::isBeginDeclareSectionSQL(string& line, size_t index) const +{ + string word; + size_t hits = 0; + size_t i; + for (i = index; i < line.length(); i++) + { + i = line.find_first_not_of(" \t", i); + if (i == string::npos) + return false; + if (line[i] == ';') + break; + if (!isCharPotentialHeader(line, i)) + continue; + word = getCurrentWord(line, i); + for (size_t j = 0; j < word.length(); j++) + word[j] = (char) toupper(word[j]); + if (word == "EXEC" || word == "SQL") + { + i += word.length() - 1; + continue; + } + if (word == "DECLARE" || word == "SECTION") + { + hits++; + i += word.length() - 1; + continue; + } + if (word == "BEGIN") + { + hits++; + i += word.length() - 1; + continue; + } + return false; + } + if (hits == 3) + return true; + return false; +} + +/** + * check for SQL "END DECLARE SECTION". + * must compare case insensitive and allow any spacing between words. + * + * @param line a reference to the line to indent. + * @param index the current line index. + * @return true if a hit. + */ +bool ASEnhancer::isEndDeclareSectionSQL(string& line, size_t index) const +{ + string word; + size_t hits = 0; + size_t i; + for (i = index; i < line.length(); i++) + { + i = line.find_first_not_of(" \t", i); + if (i == string::npos) + return false; + if (line[i] == ';') + break; + if (!isCharPotentialHeader(line, i)) + continue; + word = getCurrentWord(line, i); + for (size_t j = 0; j < word.length(); j++) + word[j] = (char) toupper(word[j]); + if (word == "EXEC" || word == "SQL") + { + i += word.length() - 1; + continue; + } + if (word == "DECLARE" || word == "SECTION") + { + hits++; + i += word.length() - 1; + continue; + } + if (word == "END") + { + hits++; + i += word.length() - 1; + continue; + } + return false; + } + if (hits == 3) + return true; + return false; +} + +/** + * check if a one-line bracket has been reached, + * i.e. if the currently reached '{' character is closed + * with a complimentary '}' elsewhere on the current line, + *. + * @return false = one-line bracket has not been reached. + * true = one-line bracket has been reached. + */ +bool ASEnhancer::isOneLineBlockReached(string& line, int startChar) const +{ + assert(line[startChar] == '{'); + + bool isInComment_ = false; + bool isInQuote_ = false; + int _bracketCount = 1; + int lineLength = line.length(); + char quoteChar_ = ' '; + char ch = ' '; + + for (int i = startChar + 1; i < lineLength; ++i) + { + ch = line[i]; + + if (isInComment_) + { + if (line.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + + if (ch == '\\') + { + ++i; + continue; + } + + if (isInQuote_) + { + if (ch == quoteChar_) + isInQuote_ = false; + continue; + } + + if (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i))) + { + isInQuote_ = true; + quoteChar_ = ch; + continue; + } + + if (line.compare(i, 2, "//") == 0) + break; + + if (line.compare(i, 2, "/*") == 0) + { + isInComment_ = true; + ++i; + continue; + } + + if (ch == '{') + ++_bracketCount; + else if (ch == '}') + --_bracketCount; + + if (_bracketCount == 0) + return true; + } + + return false; +} + +/** + * parse characters in the current line to determine if an indent + * or unindent is needed. + */ +void ASEnhancer::parseCurrentLine(string& line, bool isInPreprocessor, bool isInSQL) +{ + bool isSpecialChar = false; // is a backslash escape character + + for (size_t i = 0; i < line.length(); i++) + { + char ch = line[i]; + + // bypass whitespace + if (isWhiteSpace(ch)) + continue; + + // handle special characters (i.e. backslash+character such as \n, \t, ...) + if (isSpecialChar) + { + isSpecialChar = false; + continue; + } + if (!(isInComment) && line.compare(i, 2, "\\\\") == 0) + { + i++; + continue; + } + if (!(isInComment) && ch == '\\') + { + isSpecialChar = true; + continue; + } + + // handle quotes (such as 'x' and "Hello Dolly") + if (!isInComment + && (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i)))) + { + if (!isInQuote) + { + quoteChar = ch; + isInQuote = true; + } + else if (quoteChar == ch) + { + isInQuote = false; + continue; + } + } + + if (isInQuote) + continue; + + // handle comments + + if (!(isInComment) && line.compare(i, 2, "//") == 0) + { + // check for windows line markers + if (line.compare(i + 2, 1, "\xf0") > 0) + lineNumber--; + // unindent if not in case brackets + if (line.find_first_not_of(" \t") == i + && sw.switchBracketCount == 1 + && sw.unindentCase) + shouldUnindentComment = true; + break; // finished with the line + } + else if (!(isInComment) && line.compare(i, 2, "/*") == 0) + { + // unindent if not in case brackets + if (sw.switchBracketCount == 1 && sw.unindentCase) + shouldUnindentComment = true; + isInComment = true; + size_t commentEnd = line.find("*/", i); + if (commentEnd == string::npos) + i = line.length() - 1; + else + i = commentEnd - 1; + continue; + } + else if ((isInComment) && line.compare(i, 2, "*/") == 0) + { + // unindent if not in case brackets + if (sw.switchBracketCount == 1 && sw.unindentCase) + shouldUnindentComment = true; + isInComment = false; + i++; + continue; + } + + if (isInComment) + { + // unindent if not in case brackets + if (sw.switchBracketCount == 1 && sw.unindentCase) + shouldUnindentComment = true; + size_t commentEnd = line.find("*/", i); + if (commentEnd == string::npos) + i = line.length() - 1; + else + i = commentEnd - 1; + continue; + } + + // if we have reached this far then we are NOT in a comment or string of special characters + + if (line[i] == '{') + bracketCount++; + + if (line[i] == '}') + bracketCount--; + + // check for preprocessor within an event table + if (isInEventTable && line[i] == '#' && preprocBlockIndent) + { + string preproc; + preproc = line.substr(i + 1); + if (preproc.substr(0, 2) == "if") // #if, #ifdef, #ifndef) + eventPreprocDepth += 1; + if (preproc.substr(0, 3) == "end" && eventPreprocDepth > 0) // #endif, #end + eventPreprocDepth -= 1; + } + + bool isPotentialKeyword = isCharPotentialHeader(line, i); + + // ---------------- wxWidgets and MFC macros ---------------------------------- + + if (isPotentialKeyword) + { + for (size_t j = 0; j < indentableMacros->size(); j++) + { + // 'first' is the beginning macro + if (findKeyword(line, i, indentableMacros->at(j)->first)) + { + nextLineIsEventIndent = true; + break; + } + } + for (size_t j = 0; j < indentableMacros->size(); j++) + { + // 'second' is the ending macro + if (findKeyword(line, i, indentableMacros->at(j)->second)) + { + isInEventTable = false; + eventPreprocDepth = 0; + break; + } + } + } + + // ---------------- process SQL ----------------------------------------------- + + if (isInSQL) + { + if (isBeginDeclareSectionSQL(line, i)) + nextLineIsDeclareIndent = true; + if (isEndDeclareSectionSQL(line, i)) + isInDeclareSection = false; + break; + } + + // ---------------- process switch statements --------------------------------- + + if (isPotentialKeyword && findKeyword(line, i, "switch")) + { + switchDepth++; + switchStack.push_back(sw); // save current variables + sw.switchBracketCount = 0; + sw.unindentCase = false; // don't clear case until end of switch + i += 5; // bypass switch statement + continue; + } + + // just want unindented case statements from this point + + if (caseIndent + || switchDepth == 0 + || (isInPreprocessor && !preprocDefineIndent)) + { + // bypass the entire word + if (isPotentialKeyword) + { + string name = getCurrentWord(line, i); + i += name.length() - 1; + } + continue; + } + + i = processSwitchBlock(line, i); + + } // end of for loop * end of for loop * end of for loop * end of for loop +} + +/** + * process the character at the current index in a switch block. + * + * @param line a reference to the line to indent. + * @param index the current line index. + * @return the new line index. + */ +size_t ASEnhancer::processSwitchBlock(string& line, size_t index) +{ + size_t i = index; + bool isPotentialKeyword = isCharPotentialHeader(line, i); + + if (line[i] == '{') + { + sw.switchBracketCount++; + if (lookingForCaseBracket) // if 1st after case statement + { + sw.unindentCase = true; // unindenting this case + sw.unindentDepth++; + lookingForCaseBracket = false; // not looking now + } + return i; + } + lookingForCaseBracket = false; // no opening bracket, don't indent + + if (line[i] == '}') + { + sw.switchBracketCount--; + assert(sw.switchBracketCount <= bracketCount); + if (sw.switchBracketCount == 0) // if end of switch statement + { + int lineUnindent = sw.unindentDepth; + if (line.find_first_not_of(" \t") == i + && !switchStack.empty()) + lineUnindent = switchStack[switchStack.size() - 1].unindentDepth; + if (shouldUnindentLine) + { + if (lineUnindent > 0) + i -= unindentLine(line, lineUnindent); + shouldUnindentLine = false; + } + switchDepth--; + sw = switchStack.back(); + switchStack.pop_back(); + } + return i; + } + + if (isPotentialKeyword + && (findKeyword(line, i, "case") || findKeyword(line, i, "default"))) + { + if (sw.unindentCase) // if unindented last case + { + sw.unindentCase = false; // stop unindenting previous case + sw.unindentDepth--; + } + + i = findCaseColon(line, i); + + i++; + for (; i < line.length(); i++) // bypass whitespace + { + if (!isWhiteSpace(line[i])) + break; + } + if (i < line.length()) + { + if (line[i] == '{') + { + bracketCount++; + sw.switchBracketCount++; + if (!isOneLineBlockReached(line, i)) + unindentNextLine = true; + return i; + } + } + lookingForCaseBracket = true; + i--; // need to process this char + return i; + } + if (isPotentialKeyword) + { + string name = getCurrentWord(line, i); // bypass the entire name + i += name.length() - 1; + } + return i; +} + +/** + * unindent a line by a given number of tabsets + * by erasing the leading whitespace from the line argument. + * + * @param line a reference to the line to unindent. + * @param unindent the number of tabsets to erase. + * @return the number of characters erased. + */ +int ASEnhancer::unindentLine(string& line, int unindent) const +{ + size_t whitespace = line.find_first_not_of(" \t"); + + if (whitespace == string::npos) // if line is blank + whitespace = line.length(); // must remove padding, if any + + if (whitespace == 0) + return 0; + + size_t charsToErase = 0; + + if (forceTab && indentLength != tabLength) + { + // replace tab indents with spaces + convertForceTabIndentToSpaces(line); + // remove the space indents + size_t spaceIndentLength = line.find_first_not_of(" \t"); + charsToErase = unindent * indentLength; + if (charsToErase <= spaceIndentLength) + line.erase(0, charsToErase); + else + charsToErase = 0; + // replace leading spaces with tab indents + convertSpaceIndentToForceTab(line); + } + else if (useTabs) + { + charsToErase = unindent; + if (charsToErase <= whitespace) + line.erase(0, charsToErase); + else + charsToErase = 0; + } + else // spaces + { + charsToErase = unindent * indentLength; + if (charsToErase <= whitespace) + line.erase(0, charsToErase); + else + charsToErase = 0; + } + + return charsToErase; +} + +} // end namespace astyle diff --git a/External/Tools/AStyle/src/ASFormatter.cpp b/External/Tools/AStyle/src/ASFormatter.cpp new file mode 100644 index 0000000000..d417bd0be6 --- /dev/null +++ b/External/Tools/AStyle/src/ASFormatter.cpp @@ -0,0 +1,7263 @@ +// ASFormatter.cpp +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. +// License.txt describes the conditions under which this software may be distributed. + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- + +#include "astyle.h" + +#include +#include + +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- + +namespace astyle { +// +//----------------------------------------------------------------------------- +// ASFormatter class +//----------------------------------------------------------------------------- + +/** + * Constructor of ASFormatter + */ +ASFormatter::ASFormatter() +{ + sourceIterator = NULL; + enhancer = new ASEnhancer; + preBracketHeaderStack = NULL; + bracketTypeStack = NULL; + parenStack = NULL; + structStack = NULL; + questionMarkStack = NULL; + lineCommentNoIndent = false; + formattingStyle = STYLE_NONE; + bracketFormatMode = NONE_MODE; + pointerAlignment = PTR_ALIGN_NONE; + referenceAlignment = REF_SAME_AS_PTR; + objCColonPadMode = COLON_PAD_NO_CHANGE; + lineEnd = LINEEND_DEFAULT; + maxCodeLength = string::npos; + shouldPadCommas = false; + shouldPadOperators = false; + shouldPadParensOutside = false; + shouldPadFirstParen = false; + shouldPadParensInside = false; + shouldPadHeader = false; + shouldStripCommentPrefix = false; + shouldUnPadParens = false; + attachClosingBracketMode = false; + shouldBreakOneLineBlocks = true; + shouldBreakOneLineStatements = true; + shouldConvertTabs = false; + shouldIndentCol1Comments = false; + shouldIndentPreprocBlock = false; + shouldCloseTemplates = false; + shouldAttachExternC = false; + shouldAttachNamespace = false; + shouldAttachClass = false; + shouldAttachInline = false; + shouldBreakBlocks = false; + shouldBreakClosingHeaderBlocks = false; + shouldBreakClosingHeaderBrackets = false; + shouldDeleteEmptyLines = false; + shouldBreakElseIfs = false; + shouldBreakLineAfterLogical = false; + shouldAddBrackets = false; + shouldAddOneLineBrackets = false; + shouldRemoveBrackets = false; + shouldPadMethodColon = false; + shouldPadMethodPrefix = false; + shouldUnPadMethodPrefix = false; + shouldPadReturnType = false; + shouldUnPadReturnType = false; + + // initialize ASFormatter member vectors + formatterFileType = 9; // reset to an invalid type + headers = new vector; + nonParenHeaders = new vector; + preDefinitionHeaders = new vector; + preCommandHeaders = new vector; + operators = new vector; + assignmentOperators = new vector; + castOperators = new vector; + + // initialize ASEnhancer member vectors + indentableMacros = new vector* >; +} + +/** + * Destructor of ASFormatter + */ +ASFormatter::~ASFormatter() +{ + // delete ASFormatter stack vectors + deleteContainer(preBracketHeaderStack); + deleteContainer(bracketTypeStack); + deleteContainer(parenStack); + deleteContainer(structStack); + deleteContainer(questionMarkStack); + + // delete ASFormatter member vectors + formatterFileType = 9; // reset to an invalid type + delete headers; + delete nonParenHeaders; + delete preDefinitionHeaders; + delete preCommandHeaders; + delete operators; + delete assignmentOperators; + delete castOperators; + + // delete ASEnhancer member vectors + delete indentableMacros; + + // delete ASBeautifier member vectors + // must be done when the ASFormatter object is deleted (not ASBeautifier) + ASBeautifier::deleteBeautifierVectors(); + + delete enhancer; +} + +/** + * initialize the ASFormatter. + * + * init() should be called every time a ASFormatter object is to start + * formatting a NEW source file. + * init() receives a pointer to a ASSourceIterator object that will be + * used to iterate through the source code. + * + * @param si a pointer to the ASSourceIterator or ASStreamIterator object. + */ +void ASFormatter::init(ASSourceIterator* si) +{ + buildLanguageVectors(); + fixOptionVariableConflicts(); + ASBeautifier::init(si); + sourceIterator = si; + + enhancer->init(getFileType(), + getIndentLength(), + getTabLength(), + getIndentString() == "\t" ? true : false, + getForceTabIndentation(), + getNamespaceIndent(), + getCaseIndent(), + shouldIndentPreprocBlock, + getPreprocDefineIndent(), + getEmptyLineFill(), + indentableMacros); + + initContainer(preBracketHeaderStack, new vector); + initContainer(parenStack, new vector); + initContainer(structStack, new vector); + initContainer(questionMarkStack, new vector); + parenStack->push_back(0); // parenStack must contain this default entry + initContainer(bracketTypeStack, new vector); + bracketTypeStack->push_back(NULL_TYPE); // bracketTypeStack must contain this default entry + clearFormattedLineSplitPoints(); + + currentHeader = NULL; + currentLine = ""; + readyFormattedLine = ""; + formattedLine = ""; + verbatimDelimiter = ""; + currentChar = ' '; + previousChar = ' '; + previousCommandChar = ' '; + previousNonWSChar = ' '; + quoteChar = '"'; + preprocBlockEnd = 0; + charNum = 0; + checksumIn = 0; + checksumOut = 0; + currentLineFirstBracketNum = string::npos; + formattedLineCommentNum = 0; + leadingSpaces = 0; + previousReadyFormattedLineLength = string::npos; + preprocBracketTypeStackSize = 0; + spacePadNum = 0; + nextLineSpacePadNum = 0; + objCColonAlign = 0; + templateDepth = 0; + squareBracketCount = 0; + horstmannIndentChars = 0; + tabIncrementIn = 0; + previousBracketType = NULL_TYPE; + previousOperator = NULL; + + isVirgin = true; + isInLineComment = false; + isInComment = false; + isInCommentStartLine = false; + noTrimCommentContinuation = false; + isInPreprocessor = false; + isInPreprocessorBeautify = false; + doesLineStartComment = false; + lineEndsInCommentOnly = false; + lineIsCommentOnly = false; + lineIsLineCommentOnly = false; + lineIsEmpty = false; + isImmediatelyPostCommentOnly = false; + isImmediatelyPostEmptyLine = false; + isInClassInitializer = false; + isInQuote = false; + isInVerbatimQuote = false; + haveLineContinuationChar = false; + isInQuoteContinuation = false; + isHeaderInMultiStatementLine = false; + isSpecialChar = false; + isNonParenHeader = false; + foundNamespaceHeader = false; + foundClassHeader = false; + foundStructHeader = false; + foundInterfaceHeader = false; + foundPreDefinitionHeader = false; + foundPreCommandHeader = false; + foundPreCommandMacro = false; + foundCastOperator = false; + foundQuestionMark = false; + isInLineBreak = false; + endOfAsmReached = false; + endOfCodeReached = false; + isFormattingModeOff = false; + isInEnum = false; + isInExecSQL = false; + isInAsm = false; + isInAsmOneLine = false; + isInAsmBlock = false; + isLineReady = false; + elseHeaderFollowsComments = false; + caseHeaderFollowsComments = false; + isPreviousBracketBlockRelated = false; + isInPotentialCalculation = false; + shouldReparseCurrentChar = false; + needHeaderOpeningBracket = false; + shouldBreakLineAtNextChar = false; + shouldKeepLineUnbroken = false; + passedSemicolon = false; + passedColon = false; + isImmediatelyPostNonInStmt = false; + isCharImmediatelyPostNonInStmt = false; + isInTemplate = false; + isImmediatelyPostComment = false; + isImmediatelyPostLineComment = false; + isImmediatelyPostEmptyBlock = false; + isImmediatelyPostObjCMethodPrefix = false; + isImmediatelyPostPreprocessor = false; + isImmediatelyPostReturn = false; + isImmediatelyPostThrow = false; + isImmediatelyPostOperator = false; + isImmediatelyPostTemplate = false; + isImmediatelyPostPointerOrReference = false; + isCharImmediatelyPostReturn = false; + isCharImmediatelyPostThrow = false; + isCharImmediatelyPostOperator = false; + isCharImmediatelyPostComment = false; + isPreviousCharPostComment = false; + isCharImmediatelyPostLineComment = false; + isCharImmediatelyPostOpenBlock = false; + isCharImmediatelyPostCloseBlock = false; + isCharImmediatelyPostTemplate = false; + isCharImmediatelyPostPointerOrReference = false; + isInObjCInterface = false; + isInObjCMethodDefinition = false; + isInObjCReturnType = false; + isInObjCSelector = false; + breakCurrentOneLineBlock = false; + shouldRemoveNextClosingBracket = false; + isInHorstmannRunIn = false; + currentLineBeginsWithBracket = false; + isPrependPostBlockEmptyLineRequested = false; + isAppendPostBlockEmptyLineRequested = false; + isIndentableProprocessor = false; + isIndentableProprocessorBlock = false; + prependEmptyLine = false; + appendOpeningBracket = false; + foundClosingHeader = false; + isImmediatelyPostHeader = false; + isInHeader = false; + isInCase = false; + isFirstPreprocConditional = false; + processedFirstConditional = false; + isJavaStaticConstructor = false; +} + +/** + * build vectors for each programing language + * depending on the file extension. + */ +void ASFormatter::buildLanguageVectors() +{ + if (getFileType() == formatterFileType) // don't build unless necessary + return; + + formatterFileType = getFileType(); + + headers->clear(); + nonParenHeaders->clear(); + preDefinitionHeaders->clear(); + preCommandHeaders->clear(); + operators->clear(); + assignmentOperators->clear(); + castOperators->clear(); + indentableMacros->clear(); // ASEnhancer + + ASResource::buildHeaders(headers, getFileType()); + ASResource::buildNonParenHeaders(nonParenHeaders, getFileType()); + ASResource::buildPreDefinitionHeaders(preDefinitionHeaders, getFileType()); + ASResource::buildPreCommandHeaders(preCommandHeaders, getFileType()); + ASResource::buildOperators(operators, getFileType()); + ASResource::buildAssignmentOperators(assignmentOperators); + ASResource::buildCastOperators(castOperators); + ASResource::buildIndentableMacros(indentableMacros); //ASEnhancer +} + +/** + * set the variables for each predefined style. + * this will override any previous settings. + */ +void ASFormatter::fixOptionVariableConflicts() +{ + if (formattingStyle == STYLE_ALLMAN) + { + setBracketFormatMode(BREAK_MODE); + } + else if (formattingStyle == STYLE_JAVA) + { + setBracketFormatMode(ATTACH_MODE); + } + else if (formattingStyle == STYLE_KR) + { + setBracketFormatMode(LINUX_MODE); + } + else if (formattingStyle == STYLE_STROUSTRUP) + { + setBracketFormatMode(STROUSTRUP_MODE); + } + else if (formattingStyle == STYLE_WHITESMITH) + { + setBracketFormatMode(BREAK_MODE); + setBracketIndent(true); + setClassIndent(true); // avoid hanging indent with access modifiers + setSwitchIndent(true); // avoid hanging indent with case statements + } + else if (formattingStyle == STYLE_VTK) + { + // the unindented class bracket does NOT cause a hanging indent like Whitesmith + setBracketFormatMode(BREAK_MODE); + setBracketIndentVtk(true); // sets both bracketIndent and bracketIndentVtk + setSwitchIndent(true); // avoid hanging indent with case statements + } + else if (formattingStyle == STYLE_BANNER) + { + // attached brackets can have hanging indents with the closing bracket + setBracketFormatMode(ATTACH_MODE); + setBracketIndent(true); + setClassIndent(true); // avoid hanging indent with access modifiers + setSwitchIndent(true); // avoid hanging indent with case statements + } + else if (formattingStyle == STYLE_GNU) + { + setBracketFormatMode(BREAK_MODE); + setBlockIndent(true); + } + else if (formattingStyle == STYLE_LINUX) + { + setBracketFormatMode(LINUX_MODE); + // always for Linux style + setMinConditionalIndentOption(MINCOND_ONEHALF); + } + else if (formattingStyle == STYLE_HORSTMANN) + { + setBracketFormatMode(RUN_IN_MODE); + setSwitchIndent(true); + } + else if (formattingStyle == STYLE_1TBS) + { + setBracketFormatMode(LINUX_MODE); + setAddBracketsMode(true); + setRemoveBracketsMode(false); + } + else if (formattingStyle == STYLE_GOOGLE) + { + setBracketFormatMode(ATTACH_MODE); + setModifierIndent(true); + setClassIndent(false); + } + else if (formattingStyle == STYLE_PICO) + { + setBracketFormatMode(RUN_IN_MODE); + setAttachClosingBracketMode(true); + setSwitchIndent(true); + setBreakOneLineBlocksMode(false); + setSingleStatementsMode(false); + // add-brackets won't work for pico, but it could be fixed if necessary + // both options should be set to true + if (shouldAddBrackets) + shouldAddOneLineBrackets = true; + } + else if (formattingStyle == STYLE_LISP) + { + setBracketFormatMode(ATTACH_MODE); + setAttachClosingBracketMode(true); + setSingleStatementsMode(false); + // add-one-line-brackets won't work for lisp + // only shouldAddBrackets should be set to true + if (shouldAddOneLineBrackets) + { + shouldAddBrackets = true; + shouldAddOneLineBrackets = false; + } + } + setMinConditionalIndentLength(); + // if not set by indent=force-tab-x set equal to indentLength + if (!getTabLength()) + setDefaultTabLength(); + // add-one-line-brackets implies keep-one-line-blocks + if (shouldAddOneLineBrackets) + setBreakOneLineBlocksMode(false); + // don't allow add-brackets and remove-brackets + if (shouldAddBrackets || shouldAddOneLineBrackets) + setRemoveBracketsMode(false); + // don't allow indent-classes and indent-modifiers + if (getClassIndent()) + setModifierIndent(false); +} + +/** + * get the next formatted line. + * + * @return formatted line. + */ +string ASFormatter::nextLine() +{ + const string* newHeader = NULL; + bool isInVirginLine = isVirgin; + isCharImmediatelyPostComment = false; + isPreviousCharPostComment = false; + isCharImmediatelyPostLineComment = false; + isCharImmediatelyPostOpenBlock = false; + isCharImmediatelyPostCloseBlock = false; + isCharImmediatelyPostTemplate = false; + + while (!isLineReady) + { + if (shouldReparseCurrentChar) + shouldReparseCurrentChar = false; + else if (!getNextChar()) + { + breakLine(); + continue; + } + else // stuff to do when reading a new character... + { + // make sure that a virgin '{' at the beginning of the file will be treated as a block... + if (isInVirginLine && currentChar == '{' + && currentLineBeginsWithBracket + && previousCommandChar == ' ') + previousCommandChar = '{'; + if (isInClassInitializer + && isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + isInClassInitializer = false; + if (isInHorstmannRunIn) + isInLineBreak = false; + if (!isWhiteSpace(currentChar)) + isInHorstmannRunIn = false; + isPreviousCharPostComment = isCharImmediatelyPostComment; + isCharImmediatelyPostComment = false; + isCharImmediatelyPostTemplate = false; + isCharImmediatelyPostReturn = false; + isCharImmediatelyPostThrow = false; + isCharImmediatelyPostOperator = false; + isCharImmediatelyPostPointerOrReference = false; + isCharImmediatelyPostOpenBlock = false; + isCharImmediatelyPostCloseBlock = false; + } + + if ((lineIsLineCommentOnly || lineIsCommentOnly) + && currentLine.find("*INDENT-ON*", charNum) != string::npos + && isFormattingModeOff) + { + isFormattingModeOff = false; + breakLine(); + formattedLine = currentLine; + charNum = (int) currentLine.length() - 1; + continue; + } + if (isFormattingModeOff) + { + breakLine(); + formattedLine = currentLine; + charNum = (int) currentLine.length() - 1; + continue; + } + if ((lineIsLineCommentOnly || lineIsCommentOnly) + && currentLine.find("*INDENT-OFF*", charNum) != string::npos) + { + isFormattingModeOff = true; + if (isInLineBreak) // is true if not the first line + breakLine(); + formattedLine = currentLine; + charNum = (int)currentLine.length() - 1; + continue; + } + + if (shouldBreakLineAtNextChar) + { + if (isWhiteSpace(currentChar) && !lineIsEmpty) + continue; + isInLineBreak = true; + shouldBreakLineAtNextChar = false; + } + + if (isInExecSQL && !passedSemicolon) + { + if (currentChar == ';') + passedSemicolon = true; + appendCurrentChar(); + continue; + } + + if (isInLineComment) + { + formatLineCommentBody(); + continue; + } + else if (isInComment) + { + formatCommentBody(); + continue; + } + + else if (isInQuote) + { + formatQuoteBody(); + continue; + } + + // not in quote or comment or line comment + + if (isSequenceReached("//")) + { + formatLineCommentOpener(); + testForTimeToSplitFormattedLine(); + continue; + } + else if (isSequenceReached("/*")) + { + formatCommentOpener(); + testForTimeToSplitFormattedLine(); + continue; + } + else if (currentChar == '"' + || (currentChar == '\'' && !isDigitSeparator(currentLine, charNum))) + { + formatQuoteOpener(); + testForTimeToSplitFormattedLine(); + continue; + } + // treat these preprocessor statements as a line comment + else if (currentChar == '#' + && currentLine.find_first_not_of(" \t") == (size_t) charNum) + { + string preproc = trim(currentLine.c_str() + charNum + 1); + if (preproc.length() > 0 + && isCharPotentialHeader(preproc, 0) + && (findKeyword(preproc, 0, "region") + || findKeyword(preproc, 0, "endregion") + || findKeyword(preproc, 0, "error") + || findKeyword(preproc, 0, "warning") + || findKeyword(preproc, 0, "line"))) + { + currentLine = rtrim(currentLine); // trim the end only + // check for horstmann run-in + if (formattedLine.length() > 0 && formattedLine[0] == '{') + { + isInLineBreak = true; + isInHorstmannRunIn = false; + } + if (previousCommandChar == '}') + currentHeader = NULL; + isInLineComment = true; + appendCurrentChar(); + continue; + } + } + + if (isInPreprocessor) + { + appendCurrentChar(); + continue; + } + + if (isInTemplate && shouldCloseTemplates) + { + if (previousCommandChar == '<' && isWhiteSpace(currentChar)) + continue; + if (isWhiteSpace(currentChar) && peekNextChar() == '>') + continue; + } + + if (shouldRemoveNextClosingBracket && currentChar == '}') + { + currentLine[charNum] = currentChar = ' '; + shouldRemoveNextClosingBracket = false; + assert(adjustChecksumIn(-'}')); + // if the line is empty, delete it + if (currentLine.find_first_not_of(" \t")) + continue; + } + + // handle white space - needed to simplify the rest. + if (isWhiteSpace(currentChar)) + { + appendCurrentChar(); + continue; + } + + /* not in MIDDLE of quote or comment or SQL or white-space of any type ... */ + + // check if in preprocessor + // ** isInPreprocessor will be automatically reset at the beginning + // of a new line in getnextChar() + if (currentChar == '#') + { + isInPreprocessor = true; + // check for horstmann run-in + if (formattedLine.length() > 0 && formattedLine[0] == '{') + { + isInLineBreak = true; + isInHorstmannRunIn = false; + } + processPreprocessor(); + // if top level it is potentially indentable + if (shouldIndentPreprocBlock + && (isBracketType(bracketTypeStack->back(), NULL_TYPE) + || isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE)) + && !foundClassHeader + && !isInClassInitializer + && sourceIterator->tellg() > preprocBlockEnd) + { + // indent the #if preprocessor blocks + string preproc = ASBeautifier::extractPreprocessorStatement(currentLine); + if (preproc.length() >= 2 && preproc.substr(0, 2) == "if") // #if, #ifdef, #ifndef + { + if (isImmediatelyPostPreprocessor) + breakLine(); + isIndentableProprocessorBlock = isIndentablePreprocessorBlock(currentLine, charNum); + isIndentableProprocessor = isIndentableProprocessorBlock; + } + } + if (isIndentableProprocessorBlock + && charNum < (int) currentLine.length() - 1 + && isWhiteSpace(currentLine[charNum + 1])) + { + size_t nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText != string::npos) + currentLine.erase(charNum + 1, nextText - charNum - 1); + } + if (isIndentableProprocessorBlock + && sourceIterator->tellg() >= preprocBlockEnd) + isIndentableProprocessorBlock = false; + // need to fall thru here to reset the variables + } + + /* not in preprocessor ... */ + + if (isImmediatelyPostComment) + { + caseHeaderFollowsComments = false; + isImmediatelyPostComment = false; + isCharImmediatelyPostComment = true; + } + + if (isImmediatelyPostLineComment) + { + caseHeaderFollowsComments = false; + isImmediatelyPostLineComment = false; + isCharImmediatelyPostLineComment = true; + } + + if (isImmediatelyPostReturn) + { + isImmediatelyPostReturn = false; + isCharImmediatelyPostReturn = true; + } + + if (isImmediatelyPostThrow) + { + isImmediatelyPostThrow = false; + isCharImmediatelyPostThrow = true; + } + + if (isImmediatelyPostOperator) + { + isImmediatelyPostOperator = false; + isCharImmediatelyPostOperator = true; + } + if (isImmediatelyPostTemplate) + { + isImmediatelyPostTemplate = false; + isCharImmediatelyPostTemplate = true; + } + if (isImmediatelyPostPointerOrReference) + { + isImmediatelyPostPointerOrReference = false; + isCharImmediatelyPostPointerOrReference = true; + } + + // reset isImmediatelyPostHeader information + if (isImmediatelyPostHeader) + { + // should brackets be added + if (currentChar != '{' && shouldAddBrackets) + { + bool bracketsAdded = addBracketsToStatement(); + if (bracketsAdded && !shouldAddOneLineBrackets) + { + size_t firstText = currentLine.find_first_not_of(" \t"); + assert(firstText != string::npos); + if ((int) firstText == charNum) + breakCurrentOneLineBlock = true; + } + } + // should brackets be removed + else if (currentChar == '{' && shouldRemoveBrackets) + { + bool bracketsRemoved = removeBracketsFromStatement(); + if (bracketsRemoved) + { + shouldRemoveNextClosingBracket = true; + if (isBeforeAnyLineEndComment(charNum)) + spacePadNum--; + else if (shouldBreakOneLineBlocks + || (currentLineBeginsWithBracket + && currentLine.find_first_not_of(" \t") != string::npos)) + shouldBreakLineAtNextChar = true; + continue; + } + } + + // break 'else-if' if shouldBreakElseIfs is requested + if (shouldBreakElseIfs + && currentHeader == &AS_ELSE + && isOkToBreakBlock(bracketTypeStack->back()) + && !isBeforeAnyComment() + && (shouldBreakOneLineStatements || !isHeaderInMultiStatementLine)) + { + string nextText = peekNextText(currentLine.substr(charNum)); + if (nextText.length() > 0 + && isCharPotentialHeader(nextText, 0) + && ASBeautifier::findHeader(nextText, 0, headers) == &AS_IF) + { + isInLineBreak = true; + } + } + + isImmediatelyPostHeader = false; + } + + if (passedSemicolon) // need to break the formattedLine + { + passedSemicolon = false; + if (parenStack->back() == 0 && !isCharImmediatelyPostComment && currentChar != ';') // allow ;; + { + // does a one-line block have ending comments? + if (isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + { + size_t blockEnd = currentLine.rfind(AS_CLOSE_BRACKET); + assert(blockEnd != string::npos); + // move ending comments to this formattedLine + if (isBeforeAnyLineEndComment(blockEnd)) + { + size_t commentStart = currentLine.find_first_not_of(" \t", blockEnd + 1); + assert(commentStart != string::npos); + assert((currentLine.compare(commentStart, 2, "//") == 0) + || (currentLine.compare(commentStart, 2, "/*") == 0)); + size_t commentLength = currentLine.length() - commentStart; + formattedLine.append(getIndentLength() - 1, ' '); + formattedLine.append(currentLine, commentStart, commentLength); + currentLine.erase(commentStart, commentLength); + testForTimeToSplitFormattedLine(); + } + } + isInExecSQL = false; + shouldReparseCurrentChar = true; + if (formattedLine.find_first_not_of(" \t") != string::npos) + isInLineBreak = true; + if (needHeaderOpeningBracket) + { + isCharImmediatelyPostCloseBlock = true; + needHeaderOpeningBracket = false; + } + continue; + } + } + + if (passedColon) + { + passedColon = false; + if (parenStack->back() == 0 + && !isBeforeAnyComment() + && (formattedLine.find_first_not_of(" \t") != string::npos)) + { + shouldReparseCurrentChar = true; + isInLineBreak = true; + continue; + } + } + + // Check if in template declaration, e.g. foo or foo + if (!isInTemplate && currentChar == '<') + { + checkIfTemplateOpener(); + } + + // handle parens + if (currentChar == '(' || currentChar == '[' || (isInTemplate && currentChar == '<')) + { + questionMarkStack->push_back(foundQuestionMark); + foundQuestionMark = false; + parenStack->back()++; + if (currentChar == '[') + ++squareBracketCount; + } + else if (currentChar == ')' || currentChar == ']' || (isInTemplate && currentChar == '>')) + { + foundPreCommandHeader = false; + parenStack->back()--; + // this can happen in preprocessor directives + if (parenStack->back() < 0) + parenStack->back() = 0; + if (!questionMarkStack->empty()) + { + foundQuestionMark = questionMarkStack->back(); + questionMarkStack->pop_back(); + } + if (isInTemplate && currentChar == '>') + { + templateDepth--; + if (templateDepth == 0) + { + isInTemplate = false; + isImmediatelyPostTemplate = true; + } + } + + // check if this parenthesis closes a header, e.g. if (...), while (...) + if (isInHeader && parenStack->back() == 0) + { + isInHeader = false; + isImmediatelyPostHeader = true; + foundQuestionMark = false; + } + if (currentChar == ']') + { + --squareBracketCount; + if (squareBracketCount < 0) + squareBracketCount = 0; + } + if (currentChar == ')') + { + foundCastOperator = false; + if (parenStack->back() == 0) + endOfAsmReached = true; + } + } + + // handle brackets + if (currentChar == '{' || currentChar == '}') + { + // if appendOpeningBracket this was already done for the original bracket + if (currentChar == '{' && !appendOpeningBracket) + { + BracketType newBracketType = getBracketType(); + foundNamespaceHeader = false; + foundClassHeader = false; + foundStructHeader = false; + foundInterfaceHeader = false; + foundPreDefinitionHeader = false; + foundPreCommandHeader = false; + foundPreCommandMacro = false; + isInPotentialCalculation = false; + isInObjCMethodDefinition = false; + isInObjCInterface = false; + isInEnum = false; + isJavaStaticConstructor = false; + isCharImmediatelyPostNonInStmt = false; + needHeaderOpeningBracket = false; + shouldKeepLineUnbroken = false; + objCColonAlign = 0; + + isPreviousBracketBlockRelated = !isBracketType(newBracketType, ARRAY_TYPE); + bracketTypeStack->push_back(newBracketType); + preBracketHeaderStack->push_back(currentHeader); + currentHeader = NULL; + structStack->push_back(isInIndentableStruct); + if (isBracketType(newBracketType, STRUCT_TYPE) && isCStyle()) + isInIndentableStruct = isStructAccessModified(currentLine, charNum); + else + isInIndentableStruct = false; + } + + // this must be done before the bracketTypeStack is popped + BracketType bracketType = bracketTypeStack->back(); + bool isOpeningArrayBracket = (isBracketType(bracketType, ARRAY_TYPE) + && bracketTypeStack->size() >= 2 + && !isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 2], ARRAY_TYPE) + ); + + if (currentChar == '}') + { + // if a request has been made to append a post block empty line, + // but the block exists immediately before a closing bracket, + // then there is no need for the post block empty line. + isAppendPostBlockEmptyLineRequested = false; + breakCurrentOneLineBlock = false; + if (isInAsm) + endOfAsmReached = true; + isInAsmOneLine = isInQuote = false; + shouldKeepLineUnbroken = false; + squareBracketCount = 0; + + if (bracketTypeStack->size() > 1) + { + previousBracketType = bracketTypeStack->back(); + bracketTypeStack->pop_back(); + isPreviousBracketBlockRelated = !isBracketType(bracketType, ARRAY_TYPE); + } + else + { + previousBracketType = NULL_TYPE; + isPreviousBracketBlockRelated = false; + } + + if (!preBracketHeaderStack->empty()) + { + currentHeader = preBracketHeaderStack->back(); + preBracketHeaderStack->pop_back(); + } + else + currentHeader = NULL; + + if (!structStack->empty()) + { + isInIndentableStruct = structStack->back(); + structStack->pop_back(); + } + else + isInIndentableStruct = false; + + if (isNonInStatementArray + && (!isBracketType(bracketTypeStack->back(), ARRAY_TYPE) // check previous bracket + || peekNextChar() == ';')) // check for "};" added V2.01 + isImmediatelyPostNonInStmt = true; + } + + // format brackets + appendOpeningBracket = false; + if (isBracketType(bracketType, ARRAY_TYPE)) + { + formatArrayBrackets(bracketType, isOpeningArrayBracket); + } + else + { + if (currentChar == '{') + formatOpeningBracket(bracketType); + else + formatClosingBracket(bracketType); + } + continue; + } + + if ((((previousCommandChar == '{' && isPreviousBracketBlockRelated) + || ((previousCommandChar == '}' + && !isImmediatelyPostEmptyBlock + && isPreviousBracketBlockRelated + && !isPreviousCharPostComment // Fixes wrongly appended newlines after '}' immediately after comments + && peekNextChar() != ' ' + && !isBracketType(previousBracketType, DEFINITION_TYPE)) + && !isBracketType(bracketTypeStack->back(), DEFINITION_TYPE))) + && isOkToBreakBlock(bracketTypeStack->back())) + // check for array + || (previousCommandChar == '{' // added 9/30/2010 + && isBracketType(bracketTypeStack->back(), ARRAY_TYPE) + && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) + && isNonInStatementArray)) + { + isCharImmediatelyPostOpenBlock = (previousCommandChar == '{'); + isCharImmediatelyPostCloseBlock = (previousCommandChar == '}'); + + if (isCharImmediatelyPostOpenBlock + && !isCharImmediatelyPostComment + && !isCharImmediatelyPostLineComment) + { + previousCommandChar = ' '; + + if (bracketFormatMode == NONE_MODE) + { + if (shouldBreakOneLineBlocks + && isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + isInLineBreak = true; + else if (currentLineBeginsWithBracket) + formatRunIn(); + else + breakLine(); + } + else if (bracketFormatMode == RUN_IN_MODE + && currentChar != '#') + formatRunIn(); + else + isInLineBreak = true; + } + else if (isCharImmediatelyPostCloseBlock + && shouldBreakOneLineStatements + && (isLegalNameChar(currentChar) && currentChar != '.') + && !isCharImmediatelyPostComment) + { + previousCommandChar = ' '; + isInLineBreak = true; + } + } + + // reset block handling flags + isImmediatelyPostEmptyBlock = false; + + // look for headers + bool isPotentialHeader = isCharPotentialHeader(currentLine, charNum); + + if (isPotentialHeader && !isInTemplate && !squareBracketCount) + { + isNonParenHeader = false; + foundClosingHeader = false; + newHeader = findHeader(headers); + + // Qt headers may be variables in C++ + if (isCStyle() + && (newHeader == &AS_FOREVER || newHeader == &AS_FOREACH)) + { + if (currentLine.find_first_of("=;", charNum) != string::npos) + newHeader = NULL; + } + else if (newHeader == &AS_USING + && ASBeautifier::peekNextChar(currentLine, + charNum + (*newHeader).length() - 1) != '(') + newHeader = NULL; + + if (newHeader != NULL) + { + // recognize closing headers of do..while, if..else, try..catch..finally + if ((newHeader == &AS_ELSE && currentHeader == &AS_IF) + || (newHeader == &AS_WHILE && currentHeader == &AS_DO) + || (newHeader == &AS_CATCH && currentHeader == &AS_TRY) + || (newHeader == &AS_CATCH && currentHeader == &AS_CATCH) + || (newHeader == &AS_FINALLY && currentHeader == &AS_TRY) + || (newHeader == &AS_FINALLY && currentHeader == &AS_CATCH) + || (newHeader == &_AS_FINALLY && currentHeader == &_AS_TRY) + || (newHeader == &_AS_EXCEPT && currentHeader == &_AS_TRY) + || (newHeader == &AS_SET && currentHeader == &AS_GET) + || (newHeader == &AS_REMOVE && currentHeader == &AS_ADD)) + foundClosingHeader = true; + + const string* previousHeader = currentHeader; + currentHeader = newHeader; + needHeaderOpeningBracket = true; + + // is the previous statement on the same line? + if ((previousNonWSChar == ';' || previousNonWSChar == ':') + && !isInLineBreak + && isOkToBreakBlock(bracketTypeStack->back())) + { + // if breaking lines, break the line at the header + // except for multiple 'case' statements on a line + if (maxCodeLength != string::npos + && previousHeader != &AS_CASE) + isInLineBreak = true; + else + isHeaderInMultiStatementLine = true; + } + + if (foundClosingHeader && previousNonWSChar == '}') + { + if (isOkToBreakBlock(bracketTypeStack->back())) + isLineBreakBeforeClosingHeader(); + + // get the adjustment for a comment following the closing header + if (isInLineBreak) + nextLineSpacePadNum = getNextLineCommentAdjustment(); + else + spacePadNum = getCurrentLineCommentAdjustment(); + } + + // check if the found header is non-paren header + isNonParenHeader = findHeader(nonParenHeaders) != NULL; + + // join 'else if' statements + if (currentHeader == &AS_IF + && previousHeader == &AS_ELSE + && isInLineBreak + && !shouldBreakElseIfs + && !isCharImmediatelyPostLineComment + && !isImmediatelyPostPreprocessor) + { + // 'else' must be last thing on the line + size_t start = formattedLine.length() >= 6 ? formattedLine.length() - 6 : 0; + if (formattedLine.find(AS_ELSE, start) != string::npos) + { + appendSpacePad(); + isInLineBreak = false; + } + } + + appendSequence(*currentHeader); + goForward(currentHeader->length() - 1); + // if a paren-header is found add a space after it, if needed + // this checks currentLine, appendSpacePad() checks formattedLine + // in 'case' and C# 'catch' can be either a paren or non-paren header + if (shouldPadHeader + && (!isNonParenHeader + || (currentHeader == &AS_CASE && peekNextChar() == '(') + || (currentHeader == &AS_CATCH && peekNextChar() == '(')) + && charNum < (int) currentLine.length() - 1 && !isWhiteSpace(currentLine[charNum + 1])) + appendSpacePad(); + + // Signal that a header has been reached + // *** But treat a closing while() (as in do...while) + // as if it were NOT a header since a closing while() + // should never have a block after it! + if (currentHeader != &AS_CASE && currentHeader != &AS_DEFAULT + && !(foundClosingHeader && currentHeader == &AS_WHILE)) + { + isInHeader = true; + + // in C# 'catch' and 'delegate' can be a paren or non-paren header + if (isNonParenHeader && !isSharpStyleWithParen(currentHeader)) + { + isImmediatelyPostHeader = true; + isInHeader = false; + } + } + + if (shouldBreakBlocks + && isOkToBreakBlock(bracketTypeStack->back()) + && !isHeaderInMultiStatementLine) + { + if (previousHeader == NULL + && !foundClosingHeader + && !isCharImmediatelyPostOpenBlock + && !isImmediatelyPostCommentOnly) + { + isPrependPostBlockEmptyLineRequested = true; + } + + if (currentHeader == &AS_ELSE + || currentHeader == &AS_CATCH + || currentHeader == &AS_FINALLY + || foundClosingHeader) + { + isPrependPostBlockEmptyLineRequested = false; + } + + if (shouldBreakClosingHeaderBlocks + && isCharImmediatelyPostCloseBlock + && !isImmediatelyPostCommentOnly + && currentHeader != &AS_WHILE) // closing do-while block + { + isPrependPostBlockEmptyLineRequested = true; + } + } + + if (currentHeader == &AS_CASE + || currentHeader == &AS_DEFAULT) + isInCase = true; + + continue; + } + else if ((newHeader = findHeader(preDefinitionHeaders)) != NULL + && parenStack->back() == 0 + && !isInEnum) // not C++11 enum class + { + if (newHeader == &AS_NAMESPACE) + foundNamespaceHeader = true; + if (newHeader == &AS_CLASS) + foundClassHeader = true; + if (newHeader == &AS_STRUCT) + foundStructHeader = true; + if (newHeader == &AS_INTERFACE) + foundInterfaceHeader = true; + foundPreDefinitionHeader = true; + appendSequence(*newHeader); + goForward(newHeader->length() - 1); + + continue; + } + else if ((newHeader = findHeader(preCommandHeaders)) != NULL) + { + // a 'const' variable is not a preCommandHeader + if (previousNonWSChar == ')') + foundPreCommandHeader = true; + } + else if ((newHeader = findHeader(castOperators)) != NULL) + { + foundCastOperator = true; + appendSequence(*newHeader); + goForward(newHeader->length() - 1); + continue; + } + } // (isPotentialHeader && !isInTemplate) + + if (isInLineBreak) // OK to break line here + { + breakLine(); + if (isInVirginLine) // adjust for the first line + { + lineCommentNoBeautify = lineCommentNoIndent; + lineCommentNoIndent = false; + if (isImmediatelyPostPreprocessor) + { + isInIndentablePreproc = isIndentableProprocessor; + isIndentableProprocessor = false; + } + } + } + + if (previousNonWSChar == '}' || currentChar == ';') + { + if (currentChar == ';') + { + squareBracketCount = 0; + + if (((shouldBreakOneLineStatements + || isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + && isOkToBreakBlock(bracketTypeStack->back())) + && !(attachClosingBracketMode && peekNextChar() == '}')) + { + passedSemicolon = true; + } + + // append post block empty line for unbracketed header + if (shouldBreakBlocks + && currentHeader != NULL + && currentHeader != &AS_CASE + && currentHeader != &AS_DEFAULT + && !isHeaderInMultiStatementLine + && parenStack->back() == 0) + { + isAppendPostBlockEmptyLineRequested = true; + } + } + if (currentChar != ';' + || (needHeaderOpeningBracket && parenStack->back() == 0)) + currentHeader = NULL; + resetEndOfStatement(); + } + + if (currentChar == ':' + && previousChar != ':' // not part of '::' + && peekNextChar() != ':') // not part of '::' + { + if (isInCase) + { + isInCase = false; + if (shouldBreakOneLineStatements) + passedColon = true; + } + else if (isCStyle() // for C/C++ only + && isOkToBreakBlock(bracketTypeStack->back()) + && shouldBreakOneLineStatements + && !foundQuestionMark // not in a ?: sequence + && !foundPreDefinitionHeader // not in a definition block (e.g. class foo : public bar + && previousCommandChar != ')' // not immediately after closing paren of a method header, e.g. ASFormatter::ASFormatter(...) : ASBeautifier(...) + && !foundPreCommandHeader // not after a 'noexcept' + && !squareBracketCount // not in objC method call + && !isInObjCMethodDefinition // not objC '-' or '+' method + && !isInObjCInterface // not objC @interface + && !isInObjCSelector // not objC @selector + && !isDigit(peekNextChar()) // not a bit field + && !isInEnum // not an enum with a base type + && !isInAsm // not in extended assembler + && !isInAsmOneLine // not in extended assembler + && !isInAsmBlock) // not in extended assembler + { + passedColon = true; + } + + if (isCStyle() + && shouldPadMethodColon + && (squareBracketCount > 0 || isInObjCMethodDefinition || isInObjCSelector) + && !foundQuestionMark) // not in a ?: sequence + padObjCMethodColon(); + + if (isInObjCInterface) + { + appendSpacePad(); + if ((int) currentLine.length() > charNum + 1 && !isWhiteSpace(currentLine[charNum + 1])) + currentLine.insert(charNum + 1, " "); + } + + if (isClassInitializer()) + isInClassInitializer = true; + } + + if (currentChar == '?') + foundQuestionMark = true; + + if (isPotentialHeader && !isInTemplate) + { + if (findKeyword(currentLine, charNum, AS_NEW)) + isInPotentialCalculation = false; + + if (findKeyword(currentLine, charNum, AS_RETURN)) + { + isInPotentialCalculation = true; // return is the same as an = sign + isImmediatelyPostReturn = true; + } + + if (findKeyword(currentLine, charNum, AS_OPERATOR)) + isImmediatelyPostOperator = true; + + if (findKeyword(currentLine, charNum, AS_ENUM)) + { + size_t firstNum = currentLine.find_first_of("(){},/"); + if (firstNum == string::npos + || currentLine[firstNum] == '{' + || currentLine[firstNum] == '/') + isInEnum = true; + } + + if (isCStyle() + && findKeyword(currentLine, charNum, AS_THROW) + && previousCommandChar != ')' + && !foundPreCommandHeader) // 'const' throw() + isImmediatelyPostThrow = true; + + if (isCStyle() && findKeyword(currentLine, charNum, AS_EXTERN) && isExternC()) + isInExternC = true; + + // Objective-C NSException macros are preCommandHeaders + if (isCStyle() && findKeyword(currentLine, charNum, AS_NS_DURING)) + foundPreCommandMacro = true; + if (isCStyle() && findKeyword(currentLine, charNum, AS_NS_HANDLER)) + foundPreCommandMacro = true; + + if (isCStyle() && isExecSQL(currentLine, charNum)) + isInExecSQL = true; + + if (isCStyle()) + { + if (findKeyword(currentLine, charNum, AS_ASM) + || findKeyword(currentLine, charNum, AS__ASM__)) + { + isInAsm = true; + } + else if (findKeyword(currentLine, charNum, AS_MS_ASM) // microsoft specific + || findKeyword(currentLine, charNum, AS_MS__ASM)) + { + int index = 4; + if (peekNextChar() == '_') // check for __asm + index = 5; + + char peekedChar = ASBase::peekNextChar(currentLine, charNum + index); + if (peekedChar == '{' || peekedChar == ' ') + isInAsmBlock = true; + else + isInAsmOneLine = true; + } + } + + if (isJavaStyle() + && (findKeyword(currentLine, charNum, AS_STATIC) + && isNextCharOpeningBracket(charNum + 6))) + isJavaStaticConstructor = true; + + if (isSharpStyle() + && (findKeyword(currentLine, charNum, AS_DELEGATE) + || findKeyword(currentLine, charNum, AS_UNCHECKED))) + isSharpDelegate = true; + + // append the entire name + string name = getCurrentWord(currentLine, charNum); + // must pad the 'and' and 'or' operators if required + if (name == "and" || name == "or") + { + if (shouldPadOperators && previousNonWSChar != ':') + { + appendSpacePad(); + appendOperator(name); + goForward(name.length() - 1); + if (!isBeforeAnyComment() + && !(currentLine.compare(charNum + 1, 1, AS_SEMICOLON) == 0) + && !(currentLine.compare(charNum + 1, 2, AS_SCOPE_RESOLUTION) == 0)) + appendSpaceAfter(); + } + else + { + appendOperator(name); + goForward(name.length() - 1); + } + } + else + { + appendSequence(name); + goForward(name.length() - 1); + } + + continue; + + } // (isPotentialHeader && !isInTemplate) + + // determine if this is an Objective-C statement + + if (currentChar == '@' + && isCharPotentialHeader(currentLine, charNum + 1) + && findKeyword(currentLine, charNum + 1, AS_INTERFACE) + && isBracketType(bracketTypeStack->back(), NULL_TYPE)) + { + isInObjCInterface = true; + string name = '@' + AS_INTERFACE; + appendSequence(name); + goForward(name.length() - 1); + continue; + } + else if (currentChar == '@' + && isCharPotentialHeader(currentLine, charNum + 1) + && findKeyword(currentLine, charNum + 1, AS_SELECTOR)) + { + isInObjCSelector = true; + string name = '@' + AS_SELECTOR; + appendSequence(name); + goForward(name.length() - 1); + continue; + } + else if ((currentChar == '-' || currentChar == '+') + && charNum == 0 + && peekNextChar() == '(' + && isBracketType(bracketTypeStack->back(), NULL_TYPE) + && !isInPotentialCalculation) + { + isInObjCMethodDefinition = true; + isImmediatelyPostObjCMethodPrefix = true; + isInObjCInterface = false; + if (getAlignMethodColon()) + objCColonAlign = findObjCColonAlignment(); + appendCurrentChar(); + continue; + } + + // determine if this is a potential calculation + + bool isPotentialOperator = isCharPotentialOperator(currentChar); + newHeader = NULL; + + if (isPotentialOperator) + { + newHeader = findOperator(operators); + + // check for Java ? wildcard + if (newHeader == &AS_GCC_MIN_ASSIGN && isJavaStyle() && isInTemplate) + newHeader = NULL; + + if (newHeader != NULL) + { + if (newHeader == &AS_LAMBDA) + foundPreCommandHeader = true; + + // correct mistake of two >> closing a template + if (isInTemplate && (newHeader == &AS_GR_GR || newHeader == &AS_GR_GR_GR)) + newHeader = &AS_GR; + + if (!isInPotentialCalculation) + { + // must determine if newHeader is an assignment operator + // do NOT use findOperator!!! + if (find(assignmentOperators->begin(), assignmentOperators->end(), newHeader) + != assignmentOperators->end()) + { + foundPreCommandHeader = false; + char peekedChar = peekNextChar(); + isInPotentialCalculation = !(newHeader == &AS_EQUAL && peekedChar == '*') + && !(newHeader == &AS_EQUAL && peekedChar == '&') + && !isCharImmediatelyPostOperator; + } + } + } + } + + // process pointers and references + // check newHeader to eliminate things like '&&' sequence + if (!isJavaStyle() + && (newHeader == &AS_MULT + || newHeader == &AS_BIT_AND + || newHeader == &AS_BIT_XOR + || newHeader == &AS_AND) + && isPointerOrReference()) + { + if (!isDereferenceOrAddressOf() && !isOperatorPaddingDisabled()) + formatPointerOrReference(); + else + { + appendOperator(*newHeader); + goForward(newHeader->length() - 1); + } + isImmediatelyPostPointerOrReference = true; + continue; + } + + if (shouldPadOperators && newHeader != NULL && !isOperatorPaddingDisabled()) + { + padOperators(newHeader); + continue; + } + + // remove spaces before commas + if (currentChar == ',') + { + const size_t len = formattedLine.length(); + size_t lastText = formattedLine.find_last_not_of(' '); + if (lastText != string::npos && lastText < len - 1) + { + formattedLine.resize(lastText + 1); + int size_diff = len - (lastText + 1); + spacePadNum -= size_diff; + } + } + + // pad commas and semi-colons + if (currentChar == ';' + || (currentChar == ',' && (shouldPadOperators || shouldPadCommas))) + { + char nextChar = ' '; + if (charNum + 1 < (int) currentLine.length()) + nextChar = currentLine[charNum + 1]; + if (!isWhiteSpace(nextChar) + && nextChar != '}' + && nextChar != ')' + && nextChar != ']' + && nextChar != '>' + && nextChar != ';' + && !isBeforeAnyComment() + /* && !(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) */ + ) + { + appendCurrentChar(); + appendSpaceAfter(); + continue; + } + } + + // pad parens + if (currentChar == '(' || currentChar == ')') + { + if (currentChar == '(') + { + if (shouldPadHeader + && (isCharImmediatelyPostReturn || isCharImmediatelyPostThrow)) + appendSpacePad(); + } + + if (shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens || shouldPadFirstParen) + padParens(); + else + appendCurrentChar(); + + if (currentChar == '(' + && isImmediatelyPostObjCMethodPrefix + && (shouldPadMethodPrefix || shouldUnPadMethodPrefix)) + padParenObjC(); + if (currentChar == ')' + && isInObjCReturnType + && (shouldPadReturnType || shouldUnPadReturnType)) + padParenObjC(); + + if (currentChar == '(' && isImmediatelyPostObjCMethodPrefix) + { + isImmediatelyPostObjCMethodPrefix = false; + isInObjCReturnType = true; + } + else if (currentChar == ')' && isInObjCReturnType) + isInObjCReturnType = false; + + continue; + } + + // bypass the entire operator + if (newHeader != NULL) + { + appendOperator(*newHeader); + goForward(newHeader->length() - 1); + continue; + } + + appendCurrentChar(); + + } // end of while loop * end of while loop * end of while loop * end of while loop + + // return a beautified (i.e. correctly indented) line. + + string beautifiedLine; + size_t readyFormattedLineLength = trim(readyFormattedLine).length(); + bool isInNamespace = isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE); + + if (prependEmptyLine // prepend a blank line before this formatted line + && readyFormattedLineLength > 0 + && previousReadyFormattedLineLength > 0) + { + isLineReady = true; // signal a waiting readyFormattedLine + beautifiedLine = beautify(""); + previousReadyFormattedLineLength = 0; + // call the enhancer for new empty lines + enhancer->enhance(beautifiedLine, isInNamespace, isInPreprocessorBeautify, isInBeautifySQL); + } + else // format the current formatted line + { + isLineReady = false; + horstmannIndentInStatement = horstmannIndentChars; + beautifiedLine = beautify(readyFormattedLine); + previousReadyFormattedLineLength = readyFormattedLineLength; + // the enhancer is not called for no-indent line comments + if (!lineCommentNoBeautify && !isFormattingModeOff) + enhancer->enhance(beautifiedLine, isInNamespace, isInPreprocessorBeautify, isInBeautifySQL); + horstmannIndentChars = 0; + lineCommentNoBeautify = lineCommentNoIndent; + lineCommentNoIndent = false; + isInIndentablePreproc = isIndentableProprocessor; + isIndentableProprocessor = false; + isElseHeaderIndent = elseHeaderFollowsComments; + isCaseHeaderCommentIndent = caseHeaderFollowsComments; + objCColonAlignSubsequent = objCColonAlign; + if (isCharImmediatelyPostNonInStmt) + { + isNonInStatementArray = false; + isCharImmediatelyPostNonInStmt = false; + } + isInPreprocessorBeautify = isInPreprocessor; // used by ASEnhancer + isInBeautifySQL = isInExecSQL; // used by ASEnhancer + } + + prependEmptyLine = false; + assert(computeChecksumOut(beautifiedLine)); + return beautifiedLine; +} + +/** + * check if there are any indented lines ready to be read by nextLine() + * + * @return are there any indented lines ready? + */ +bool ASFormatter::hasMoreLines() const +{ + return !endOfCodeReached; +} + +/** + * comparison function for BracketType enum + */ +bool ASFormatter::isBracketType(BracketType a, BracketType b) const +{ + if (a == NULL_TYPE || b == NULL_TYPE) + return (a == b); + return ((a & b) == b); +} + +/** + * set the formatting style. + * + * @param style the formatting style. + */ +void ASFormatter::setFormattingStyle(FormatStyle style) +{ + formattingStyle = style; +} + +/** + * set the add brackets mode. + * options: + * true brackets added to headers for single line statements. + * false brackets NOT added to headers for single line statements. + * + * @param state the add brackets state. + */ +void ASFormatter::setAddBracketsMode(bool state) +{ + shouldAddBrackets = state; +} + +/** + * set the add one line brackets mode. + * options: + * true one line brackets added to headers for single line statements. + * false one line brackets NOT added to headers for single line statements. + * + * @param state the add one line brackets state. + */ +void ASFormatter::setAddOneLineBracketsMode(bool state) +{ + shouldAddBrackets = state; + shouldAddOneLineBrackets = state; +} + +/** + * set the remove brackets mode. + * options: + * true brackets removed from headers for single line statements. + * false brackets NOT removed from headers for single line statements. + * + * @param state the remove brackets state. + */ +void ASFormatter::setRemoveBracketsMode(bool state) +{ + shouldRemoveBrackets = state; +} + +/** + * set the bracket formatting mode. + * options: + * + * @param mode the bracket formatting mode. + */ +void ASFormatter::setBracketFormatMode(BracketMode mode) +{ + bracketFormatMode = mode; +} + +/** + * set 'break after' mode for maximum code length + * + * @param state the 'break after' mode. + */ +void ASFormatter::setBreakAfterMode(bool state) +{ + shouldBreakLineAfterLogical = state; +} + +/** + * set closing header bracket breaking mode + * options: + * true brackets just before closing headers (e.g. 'else', 'catch') + * will be broken, even if standard brackets are attached. + * false closing header brackets will be treated as standard brackets. + * + * @param state the closing header bracket breaking mode. + */ +void ASFormatter::setBreakClosingHeaderBracketsMode(bool state) +{ + shouldBreakClosingHeaderBrackets = state; +} + +/** + * set 'else if()' breaking mode + * options: + * true 'else' headers will be broken from their succeeding 'if' headers. + * false 'else' headers will be attached to their succeeding 'if' headers. + * + * @param state the 'else if()' breaking mode. + */ +void ASFormatter::setBreakElseIfsMode(bool state) +{ + shouldBreakElseIfs = state; +} + +/** +* set comma padding mode. +* options: +* true statement commas and semicolons will be padded with spaces around them. +* false statement commas and semicolons will not be padded. +* +* @param state the padding mode. +*/ +void ASFormatter::setCommaPaddingMode(bool state) +{ + shouldPadCommas = state; +} + +/** + * set maximum code length + * + * @param max the maximum code length. + */ +void ASFormatter::setMaxCodeLength(int max) +{ + maxCodeLength = max; +} + +/** + * set operator padding mode. + * options: + * true statement operators will be padded with spaces around them. + * false statement operators will not be padded. + * + * @param state the padding mode. + */ +void ASFormatter::setOperatorPaddingMode(bool state) +{ + shouldPadOperators = state; +} + +/** + * set parenthesis outside padding mode. + * options: + * true statement parentheses will be padded with spaces around them. + * false statement parentheses will not be padded. + * + * @param state the padding mode. + */ +void ASFormatter::setParensOutsidePaddingMode(bool state) +{ + shouldPadParensOutside = state; +} + +/** + * set parenthesis inside padding mode. + * options: + * true statement parenthesis will be padded with spaces around them. + * false statement parenthesis will not be padded. + * + * @param state the padding mode. + */ +void ASFormatter::setParensInsidePaddingMode(bool state) +{ + shouldPadParensInside = state; +} + +/** + * set padding mode before one or more open parentheses. + * options: + * true first open parenthesis will be padded with a space before. + * false first open parenthesis will not be padded. + * + * @param state the padding mode. + */ +void ASFormatter::setParensFirstPaddingMode(bool state) +{ + shouldPadFirstParen = state; +} + +/** + * set header padding mode. + * options: + * true headers will be padded with spaces around them. + * false headers will not be padded. + * + * @param state the padding mode. + */ +void ASFormatter::setParensHeaderPaddingMode(bool state) +{ + shouldPadHeader = state; +} + +/** + * set parenthesis unpadding mode. + * options: + * true statement parenthesis will be unpadded with spaces removed around them. + * false statement parenthesis will not be unpadded. + * + * @param state the padding mode. + */ +void ASFormatter::setParensUnPaddingMode(bool state) +{ + shouldUnPadParens = state; +} + +/** +* set the state of the preprocessor indentation option. +* If true, #ifdef blocks at level 0 will be indented. +* +* @param state state of option. +*/ +void ASFormatter::setPreprocBlockIndent(bool state) +{ + shouldIndentPreprocBlock = state; +} + +/** + * Set strip comment prefix mode. + * options: + * true strip leading '*' in a comment. + * false leading '*' in a comment will be left unchanged. + * + * @param state the strip comment prefix mode. + */ +void ASFormatter::setStripCommentPrefix(bool state) +{ + shouldStripCommentPrefix = state; +} + +/** + * set objective-c '-' or '+' class prefix padding mode. + * options: + * true class prefix will be padded a spaces after them. + * false class prefix will be left unchanged. + * + * @param state the padding mode. + */ +void ASFormatter::setMethodPrefixPaddingMode(bool state) +{ + shouldPadMethodPrefix = state; +} + +/** + * set objective-c '-' or '+' class prefix unpadding mode. + * options: + * true class prefix will be unpadded with spaces after them removed. + * false class prefix will left unchanged. + * + * @param state the unpadding mode. + */ +void ASFormatter::setMethodPrefixUnPaddingMode(bool state) +{ + shouldUnPadMethodPrefix = state; +} + +// set objective-c '-' or '+' return type padding mode. +void ASFormatter::setReturnTypePaddingMode(bool state) +{ + shouldPadReturnType = state; +} + +// set objective-c '-' or '+' return type unpadding mode. +void ASFormatter::setReturnTypeUnPaddingMode(bool state) +{ + shouldUnPadReturnType = state; +} + +/** + * set objective-c method colon padding mode. + * + * @param mode objective-c colon padding mode. + */ +void ASFormatter::setObjCColonPaddingMode(ObjCColonPad mode) +{ + shouldPadMethodColon = true; + objCColonPadMode = mode; +} + +/** + * set option to attach closing brackets + * + * @param state true = attach, false = don't attach. + */ +void ASFormatter::setAttachClosingBracketMode(bool state) +{ + attachClosingBracketMode = state; +} + +/** + * set option to attach class brackets + * + * @param state true = attach, false = use style default. + */ +void ASFormatter::setAttachClass(bool state) +{ + shouldAttachClass = state; +} + +/** + * set option to attach extern "C" brackets + * + * @param state true = attach, false = use style default. + */ +void ASFormatter::setAttachExternC(bool state) +{ + shouldAttachExternC = state; +} + +/** + * set option to attach namespace brackets + * + * @param state true = attach, false = use style default. + */ +void ASFormatter::setAttachNamespace(bool state) +{ + shouldAttachNamespace = state; +} + +/** + * set option to attach inline brackets + * + * @param state true = attach, false = use style default. + */ +void ASFormatter::setAttachInline(bool state) +{ + shouldAttachInline = state; +} + +/** + * set option to break/not break one-line blocks + * + * @param state true = break, false = don't break. + */ +void ASFormatter::setBreakOneLineBlocksMode(bool state) +{ + shouldBreakOneLineBlocks = state; +} + +void ASFormatter::setCloseTemplatesMode(bool state) +{ + shouldCloseTemplates = state; +} + +/** + * set option to break/not break lines consisting of multiple statements. + * + * @param state true = break, false = don't break. + */ +void ASFormatter::setSingleStatementsMode(bool state) +{ + shouldBreakOneLineStatements = state; +} + +/** + * set option to convert tabs to spaces. + * + * @param state true = convert, false = don't convert. + */ +void ASFormatter::setTabSpaceConversionMode(bool state) +{ + shouldConvertTabs = state; +} + +/** + * set option to indent comments in column 1. + * + * @param state true = indent, false = don't indent. + */ +void ASFormatter::setIndentCol1CommentsMode(bool state) +{ + shouldIndentCol1Comments = state; +} + +/** + * set option to force all line ends to a particular style. + * + * @param fmt format enum value + */ +void ASFormatter::setLineEndFormat(LineEndFormat fmt) +{ + lineEnd = fmt; +} + +/** + * set option to break unrelated blocks of code with empty lines. + * + * @param state true = convert, false = don't convert. + */ +void ASFormatter::setBreakBlocksMode(bool state) +{ + shouldBreakBlocks = state; +} + +/** + * set option to break closing header blocks of code (such as 'else', 'catch', ...) with empty lines. + * + * @param state true = convert, false = don't convert. + */ +void ASFormatter::setBreakClosingHeaderBlocksMode(bool state) +{ + shouldBreakClosingHeaderBlocks = state; +} + +/** + * set option to delete empty lines. + * + * @param state true = delete, false = don't delete. + */ +void ASFormatter::setDeleteEmptyLinesMode(bool state) +{ + shouldDeleteEmptyLines = state; +} + +/** + * set the pointer alignment. + * + * @param alignment the pointer alignment. + */ +void ASFormatter::setPointerAlignment(PointerAlign alignment) +{ + pointerAlignment = alignment; +} + +void ASFormatter::setReferenceAlignment(ReferenceAlign alignment) +{ + referenceAlignment = alignment; +} + +/** + * jump over several characters. + * + * @param i the number of characters to jump over. + */ +void ASFormatter::goForward(int i) +{ + while (--i >= 0) + getNextChar(); +} + +/** + * peek at the next unread character. + * + * @return the next unread character. + */ +char ASFormatter::peekNextChar() const +{ + char ch = ' '; + size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); + + if (peekNum == string::npos) + return ch; + + ch = currentLine[peekNum]; + + return ch; +} + +/** + * check if current placement is before a comment + * + * @return is before a comment. + */ +bool ASFormatter::isBeforeComment() const +{ + bool foundComment = false; + size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); + + if (peekNum == string::npos) + return foundComment; + + foundComment = (currentLine.compare(peekNum, 2, "/*") == 0); + + return foundComment; +} + +/** + * check if current placement is before a comment or line-comment + * + * @return is before a comment or line-comment. + */ +bool ASFormatter::isBeforeAnyComment() const +{ + bool foundComment = false; + size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); + + if (peekNum == string::npos) + return foundComment; + + foundComment = (currentLine.compare(peekNum, 2, "/*") == 0 + || currentLine.compare(peekNum, 2, "//") == 0); + + return foundComment; +} + +/** + * check if current placement is before a comment or line-comment + * if a block comment it must be at the end of the line + * + * @return is before a comment or line-comment. + */ +bool ASFormatter::isBeforeAnyLineEndComment(int startPos) const +{ + bool foundLineEndComment = false; + size_t peekNum = currentLine.find_first_not_of(" \t", startPos + 1); + + if (peekNum != string::npos) + { + if (currentLine.compare(peekNum, 2, "//") == 0) + foundLineEndComment = true; + else if (currentLine.compare(peekNum, 2, "/*") == 0) + { + // comment must be closed on this line with nothing after it + size_t endNum = currentLine.find("*/", peekNum + 2); + if (endNum != string::npos) + { + size_t nextChar = currentLine.find_first_not_of(" \t", endNum + 2); + if (nextChar == string::npos) + foundLineEndComment = true; + } + } + } + return foundLineEndComment; +} + +/** + * check if current placement is before a comment followed by a line-comment + * + * @return is before a multiple line-end comment. + */ +bool ASFormatter::isBeforeMultipleLineEndComments(int startPos) const +{ + bool foundMultipleLineEndComment = false; + size_t peekNum = currentLine.find_first_not_of(" \t", startPos + 1); + + if (peekNum != string::npos) + { + if (currentLine.compare(peekNum, 2, "/*") == 0) + { + // comment must be closed on this line with nothing after it + size_t endNum = currentLine.find("*/", peekNum + 2); + if (endNum != string::npos) + { + size_t nextChar = currentLine.find_first_not_of(" \t", endNum + 2); + if (nextChar != string::npos + && currentLine.compare(nextChar, 2, "//") == 0) + foundMultipleLineEndComment = true; + } + } + } + return foundMultipleLineEndComment; +} + +/** + * get the next character, increasing the current placement in the process. + * the new character is inserted into the variable currentChar. + * + * @return whether succeeded to receive the new character. + */ +bool ASFormatter::getNextChar() +{ + isInLineBreak = false; + previousChar = currentChar; + + if (!isWhiteSpace(currentChar)) + { + previousNonWSChar = currentChar; + if (!isInComment && !isInLineComment && !isInQuote + && !isImmediatelyPostComment + && !isImmediatelyPostLineComment + && !isInPreprocessor + && !isSequenceReached("/*") + && !isSequenceReached("//")) + previousCommandChar = currentChar; + } + + if (charNum + 1 < (int) currentLine.length() + && (!isWhiteSpace(peekNextChar()) || isInComment || isInLineComment)) + { + currentChar = currentLine[++charNum]; + + if (currentChar == '\t' && shouldConvertTabs) + convertTabToSpaces(); + + return true; + } + + // end of line has been reached + return getNextLine(); +} + +/** + * get the next line of input, increasing the current placement in the process. + * + * @param emptyLineWasDeleted an empty line was deleted. + * @return whether succeeded in reading the next line. + */ +bool ASFormatter::getNextLine(bool emptyLineWasDeleted /*false*/) +{ + if (sourceIterator->hasMoreLines()) + { + if (appendOpeningBracket) + currentLine = "{"; // append bracket that was removed from the previous line + else + { + currentLine = sourceIterator->nextLine(emptyLineWasDeleted); + assert(computeChecksumIn(currentLine)); + } + // reset variables for new line + inLineNumber++; + if (endOfAsmReached) + endOfAsmReached = isInAsmBlock = isInAsm = false; + shouldKeepLineUnbroken = false; + isInCommentStartLine = false; + isInCase = false; + isInAsmOneLine = false; + isHeaderInMultiStatementLine = false; + isInQuoteContinuation = isInVerbatimQuote | haveLineContinuationChar; + haveLineContinuationChar = false; + isImmediatelyPostEmptyLine = lineIsEmpty; + previousChar = ' '; + + if (currentLine.length() == 0) + currentLine = string(" "); // a null is inserted if this is not done + + // unless reading in the first line of the file, break a new line. + if (!isVirgin) + isInLineBreak = true; + else + isVirgin = false; + + if (isImmediatelyPostNonInStmt) + { + isCharImmediatelyPostNonInStmt = true; + isImmediatelyPostNonInStmt = false; + } + + // check if is in preprocessor before line trimming + // a blank line after a \ will remove the flag + isImmediatelyPostPreprocessor = isInPreprocessor; + if (!isInComment + && (previousNonWSChar != '\\' + || isEmptyLine(currentLine))) + isInPreprocessor = false; + + if (passedSemicolon) + isInExecSQL = false; + initNewLine(); + + currentChar = currentLine[charNum]; + if (isInHorstmannRunIn && previousNonWSChar == '{' && !isInComment) + isInLineBreak = false; + isInHorstmannRunIn = false; + + if (currentChar == '\t' && shouldConvertTabs) + convertTabToSpaces(); + + // check for an empty line inside a command bracket. + // if yes then read the next line (calls getNextLine recursively). + // must be after initNewLine. + if (shouldDeleteEmptyLines + && lineIsEmpty + && isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 1], COMMAND_TYPE)) + { + if (!shouldBreakBlocks || previousNonWSChar == '{' || !commentAndHeaderFollows()) + { + isInPreprocessor = isImmediatelyPostPreprocessor; // restore + lineIsEmpty = false; + return getNextLine(true); + } + } + return true; + } + else + { + endOfCodeReached = true; + return false; + } +} + +/** + * jump over the leading white space in the current line, + * IF the line does not begin a comment or is in a preprocessor definition. + */ +void ASFormatter::initNewLine() +{ + size_t len = currentLine.length(); + size_t tabSize = getTabLength(); + charNum = 0; + + // don't trim these + if (isInQuoteContinuation + || (isInPreprocessor && !getPreprocDefineIndent())) + return; + + // SQL continuation lines must be adjusted so the leading spaces + // is equivalent to the opening EXEC SQL + if (isInExecSQL) + { + // replace leading tabs with spaces + // so that continuation indent will be spaces + size_t tabCount_ = 0; + size_t i; + for (i = 0; i < currentLine.length(); i++) + { + if (!isWhiteSpace(currentLine[i])) // stop at first text + break; + if (currentLine[i] == '\t') + { + size_t numSpaces = tabSize - ((tabCount_ + i) % tabSize); + currentLine.replace(i, 1, numSpaces, ' '); + tabCount_++; + i += tabSize - 1; + } + } + // this will correct the format if EXEC SQL is not a hanging indent + trimContinuationLine(); + return; + } + + // comment continuation lines must be adjusted so the leading spaces + // is equivalent to the opening comment + if (isInComment) + { + if (noTrimCommentContinuation) + leadingSpaces = tabIncrementIn = 0; + trimContinuationLine(); + return; + } + + // compute leading spaces + isImmediatelyPostCommentOnly = lineIsLineCommentOnly || lineEndsInCommentOnly; + lineIsCommentOnly = false; + lineIsLineCommentOnly = false; + lineEndsInCommentOnly = false; + doesLineStartComment = false; + currentLineBeginsWithBracket = false; + lineIsEmpty = false; + currentLineFirstBracketNum = string::npos; + tabIncrementIn = 0; + + // bypass whitespace at the start of a line + // preprocessor tabs are replaced later in the program + for (charNum = 0; isWhiteSpace(currentLine[charNum]) && charNum + 1 < (int) len; charNum++) + { + if (currentLine[charNum] == '\t' && !isInPreprocessor) + tabIncrementIn += tabSize - 1 - ((tabIncrementIn + charNum) % tabSize); + } + leadingSpaces = charNum + tabIncrementIn; + + if (isSequenceReached("/*")) + { + doesLineStartComment = true; + if ((int) currentLine.length() > charNum + 2 + && currentLine.find("*/", charNum + 2) != string::npos) + lineIsCommentOnly = true; + } + else if (isSequenceReached("//")) + { + lineIsLineCommentOnly = true; + } + else if (isSequenceReached("{")) + { + currentLineBeginsWithBracket = true; + currentLineFirstBracketNum = charNum; + size_t firstText = currentLine.find_first_not_of(" \t", charNum + 1); + if (firstText != string::npos) + { + if (currentLine.compare(firstText, 2, "//") == 0) + lineIsLineCommentOnly = true; + else if (currentLine.compare(firstText, 2, "/*") == 0 + || isExecSQL(currentLine, firstText)) + { + // get the extra adjustment + size_t j; + for (j = charNum + 1; j < firstText && isWhiteSpace(currentLine[j]); j++) + { + if (currentLine[j] == '\t') + tabIncrementIn += tabSize - 1 - ((tabIncrementIn + j) % tabSize); + } + leadingSpaces = j + tabIncrementIn; + if (currentLine.compare(firstText, 2, "/*") == 0) + doesLineStartComment = true; + } + } + } + else if (isWhiteSpace(currentLine[charNum]) && !(charNum + 1 < (int) currentLine.length())) + { + lineIsEmpty = true; + } + + // do not trim indented preprocessor define (except for comment continuation lines) + if (isInPreprocessor) + { + if (!doesLineStartComment) + leadingSpaces = 0; + charNum = 0; + } +} + +/** + * Append a character to the current formatted line. + * The formattedLine split points are updated. + * + * @param ch the character to append. + * @param canBreakLine if true, a registered line-break + */ +void ASFormatter::appendChar(char ch, bool canBreakLine) +{ + if (canBreakLine && isInLineBreak) + breakLine(); + + formattedLine.append(1, ch); + isImmediatelyPostCommentOnly = false; + if (maxCodeLength != string::npos) + { + // These compares reduce the frequency of function calls. + if (isOkToSplitFormattedLine()) + updateFormattedLineSplitPoints(ch); + if (formattedLine.length() > maxCodeLength) + testForTimeToSplitFormattedLine(); + } +} + +/** + * Append a string sequence to the current formatted line. + * The formattedLine split points are NOT updated. + * But the formattedLine is checked for time to split. + * + * @param sequence the sequence to append. + * @param canBreakLine if true, a registered line-break + */ +void ASFormatter::appendSequence(const string& sequence, bool canBreakLine) +{ + if (canBreakLine && isInLineBreak) + breakLine(); + formattedLine.append(sequence); + if (formattedLine.length() > maxCodeLength) + testForTimeToSplitFormattedLine(); +} + +/** + * Append an operator sequence to the current formatted line. + * The formattedLine split points are updated. + * + * @param sequence the sequence to append. + * @param canBreakLine if true, a registered line-break + */ +void ASFormatter::appendOperator(const string& sequence, bool canBreakLine) +{ + if (canBreakLine && isInLineBreak) + breakLine(); + formattedLine.append(sequence); + if (maxCodeLength != string::npos) + { + // These compares reduce the frequency of function calls. + if (isOkToSplitFormattedLine()) + updateFormattedLineSplitPointsOperator(sequence); + if (formattedLine.length() > maxCodeLength) + testForTimeToSplitFormattedLine(); + } +} + +/** + * append a space to the current formattedline, UNLESS the + * last character is already a white-space character. + */ +void ASFormatter::appendSpacePad() +{ + int len = formattedLine.length(); + if (len > 0 && !isWhiteSpace(formattedLine[len - 1])) + { + formattedLine.append(1, ' '); + spacePadNum++; + if (maxCodeLength != string::npos) + { + // These compares reduce the frequency of function calls. + if (isOkToSplitFormattedLine()) + updateFormattedLineSplitPoints(' '); + if (formattedLine.length() > maxCodeLength) + testForTimeToSplitFormattedLine(); + } + } +} + +/** + * append a space to the current formattedline, UNLESS the + * next character is already a white-space character. + */ +void ASFormatter::appendSpaceAfter() +{ + int len = currentLine.length(); + if (charNum + 1 < len && !isWhiteSpace(currentLine[charNum + 1])) + { + formattedLine.append(1, ' '); + spacePadNum++; + if (maxCodeLength != string::npos) + { + // These compares reduce the frequency of function calls. + if (isOkToSplitFormattedLine()) + updateFormattedLineSplitPoints(' '); + if (formattedLine.length() > maxCodeLength) + testForTimeToSplitFormattedLine(); + } + } +} + +/** + * register a line break for the formatted line. + */ +void ASFormatter::breakLine(bool isSplitLine /*false*/) +{ + isLineReady = true; + isInLineBreak = false; + spacePadNum = nextLineSpacePadNum; + nextLineSpacePadNum = 0; + readyFormattedLine = formattedLine; + formattedLine.erase(); + // queue an empty line prepend request if one exists + prependEmptyLine = isPrependPostBlockEmptyLineRequested; + + if (!isSplitLine) + { + formattedLineCommentNum = string::npos; + clearFormattedLineSplitPoints(); + + if (isAppendPostBlockEmptyLineRequested) + { + isAppendPostBlockEmptyLineRequested = false; + isPrependPostBlockEmptyLineRequested = true; + } + else + isPrependPostBlockEmptyLineRequested = false; + } +} + +/** + * check if the currently reached open-bracket (i.e. '{') + * opens a: + * - a definition type block (such as a class or namespace), + * - a command block (such as a method block) + * - a static array + * this method takes for granted that the current character + * is an opening bracket. + * + * @return the type of the opened block. + */ +BracketType ASFormatter::getBracketType() +{ + assert(currentChar == '{'); + + BracketType returnVal = NULL_TYPE; + + if ((previousNonWSChar == '=' + || isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) + && previousCommandChar != ')') + returnVal = ARRAY_TYPE; + else if (foundPreDefinitionHeader && previousCommandChar != ')') + { + returnVal = DEFINITION_TYPE; + if (foundNamespaceHeader) + returnVal = (BracketType)(returnVal | NAMESPACE_TYPE); + else if (foundClassHeader) + returnVal = (BracketType)(returnVal | CLASS_TYPE); + else if (foundStructHeader) + returnVal = (BracketType)(returnVal | STRUCT_TYPE); + else if (foundInterfaceHeader) + returnVal = (BracketType)(returnVal | INTERFACE_TYPE); + } + else if (isInEnum) + { + returnVal = (BracketType)(ARRAY_TYPE | ENUM_TYPE); + } + else + { + bool isCommandType = (foundPreCommandHeader + || foundPreCommandMacro + || (currentHeader != NULL && isNonParenHeader) + || (previousCommandChar == ')') + || (previousCommandChar == ':' && !foundQuestionMark) + || (previousCommandChar == ';') + || ((previousCommandChar == '{' || previousCommandChar == '}') + && isPreviousBracketBlockRelated) + || (isInClassInitializer + && (!isLegalNameChar(previousNonWSChar) || foundPreCommandHeader)) + || isInObjCMethodDefinition + || isInObjCInterface + || isJavaStaticConstructor + || isSharpDelegate); + + // C# methods containing 'get', 'set', 'add', and 'remove' do NOT end with parens + if (!isCommandType && isSharpStyle() && isNextWordSharpNonParenHeader(charNum + 1)) + { + isCommandType = true; + isSharpAccessor = true; + } + + if (isInExternC) + returnVal = (isCommandType ? COMMAND_TYPE : EXTERN_TYPE); + else + returnVal = (isCommandType ? COMMAND_TYPE : ARRAY_TYPE); + } + + int foundOneLineBlock = isOneLineBlockReached(currentLine, charNum); + // this assumes each array definition is on a single line + // (foundOneLineBlock == 2) is a one line block followed by a comma + if (foundOneLineBlock == 2 && returnVal == COMMAND_TYPE) + returnVal = ARRAY_TYPE; + + if (foundOneLineBlock > 0) // found one line block + returnVal = (BracketType)(returnVal | SINGLE_LINE_TYPE); + + if (isBracketType(returnVal, ARRAY_TYPE)) + { + if (isNonInStatementArrayBracket()) + { + returnVal = (BracketType)(returnVal | ARRAY_NIS_TYPE); + isNonInStatementArray = true; + isImmediatelyPostNonInStmt = false; // in case of "},{" + nonInStatementBracket = formattedLine.length() - 1; + } + if (isUniformInitializerBracket()) + returnVal = (BracketType)(returnVal | INIT_TYPE); + } + + return returnVal; +} + +/** +* check if a colon is a class initializer separator +* +* @return whether it is a class initializer separator +*/ +bool ASFormatter::isClassInitializer() const +{ + assert(currentChar == ':'); + assert(previousChar != ':' && peekNextChar() != ':'); // not part of '::' + + // this should be similar to ASBeautifier::parseCurrentLine() + bool foundClassInitializer = false; + + if (foundQuestionMark) + { + // do nothing special + } + else if (parenStack->back() > 0) + { + // found a 'for' loop or an objective-C statement + // so do nothing special + } + else if (isInEnum) + { + // found an enum with a base-type + } + else if (isCStyle() + && !isInCase + && (previousCommandChar == ')' || foundPreCommandHeader)) + { + // found a 'class' c'tor initializer + foundClassInitializer = true; + } + return foundClassInitializer; +} + +/** + * check if a line is empty + * + * @return whether line is empty + */ +bool ASFormatter::isEmptyLine(const string& line) const +{ + return line.find_first_not_of(" \t") == string::npos; +} + +/** + * Check if the following text is "C" as in extern "C". + * + * @return whether the statement is extern "C" + */ +bool ASFormatter::isExternC() const +{ + // charNum should be at 'extern' + assert(!isWhiteSpace(currentLine[charNum])); + size_t startQuote = currentLine.find_first_of(" \t\"", charNum); + if (startQuote == string::npos) + return false; + startQuote = currentLine.find_first_not_of(" \t", startQuote); + if (startQuote == string::npos) + return false; + if (currentLine.compare(startQuote, 3, "\"C\"") != 0) + return false; + return true; +} + +/** + * Check if the currently reached '*', '&' or '^' character is + * a pointer-or-reference symbol, or another operator. + * A pointer dereference (*) or an "address of" character (&) + * counts as a pointer or reference because it is not an + * arithmetic operator. + * + * @return whether current character is a reference-or-pointer + */ +bool ASFormatter::isPointerOrReference() const +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + + if (isJavaStyle()) + return false; + + if (isCharImmediatelyPostOperator) + return false; + + // get the last legal word (may be a number) + string lastWord = getPreviousWord(currentLine, charNum); + if (lastWord.empty()) + lastWord = " "; + + // check for preceding or following numeric values + string nextText = peekNextText(currentLine.substr(charNum + 1)); + if (nextText.length() == 0) + nextText = " "; + char nextChar = nextText[0]; + if (isDigit(lastWord[0]) + || isDigit(nextChar) + || nextChar == '!' + || nextChar == '~') + return false; + + // check for multiply then a dereference (a * *b) + if (currentChar == '*' + && charNum < (int) currentLine.length() - 1 + && isWhiteSpace(currentLine[charNum + 1]) + && nextChar == '*') + return false; + + if ((foundCastOperator && nextChar == '>') + || isPointerOrReferenceVariable(lastWord)) + return true; + + if (isInClassInitializer + && previousNonWSChar != '(' + && previousNonWSChar != '{' + && previousCommandChar != ',' + && nextChar != ')' + && nextChar != '}') + return false; + + //check for rvalue reference + if (currentChar == '&' && nextChar == '&') + { + string followingText = peekNextText(currentLine.substr(charNum + 2)); + if (followingText.length() > 0 && followingText[0] == ')') + return true; + if (currentHeader != NULL || isInPotentialCalculation) + return false; + if (parenStack->back() > 0 && isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + return false; + return true; + } + if (nextChar == '*' + || previousNonWSChar == '=' + || previousNonWSChar == '(' + || previousNonWSChar == '[' + || isCharImmediatelyPostReturn + || isInTemplate + || isCharImmediatelyPostTemplate + || currentHeader == &AS_CATCH + || currentHeader == &AS_FOREACH + || currentHeader == &AS_QFOREACH) + return true; + + if (isBracketType(bracketTypeStack->back(), ARRAY_TYPE) + && isLegalNameChar(lastWord[0]) + && isLegalNameChar(nextChar) + && previousNonWSChar != ')') + { + if (isArrayOperator()) + return false; + } + + // checks on operators in parens + if (parenStack->back() > 0 + && isLegalNameChar(lastWord[0]) + && isLegalNameChar(nextChar)) + { + // if followed by an assignment it is a pointer or reference + // if followed by semicolon it is a pointer or reference in range-based for + const string* followingOperator = getFollowingOperator(); + if (followingOperator + && followingOperator != &AS_MULT + && followingOperator != &AS_BIT_AND) + { + if (followingOperator == &AS_ASSIGN || followingOperator == &AS_COLON) + return true; + else + return false; + } + + if (isBracketType(bracketTypeStack->back(), COMMAND_TYPE) + || squareBracketCount > 0) + return false; + else + return true; + } + + // checks on operators in parens with following '(' + if (parenStack->back() > 0 + && nextChar == '(' + && previousNonWSChar != ',' + && previousNonWSChar != '(' + && previousNonWSChar != '!' + && previousNonWSChar != '&' + && previousNonWSChar != '*' + && previousNonWSChar != '|') + return false; + + if (nextChar == '-' + || nextChar == '+') + { + size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextNum != string::npos) + { + if (currentLine.compare(nextNum, 2, "++") != 0 + && currentLine.compare(nextNum, 2, "--") != 0) + return false; + } + } + + bool isPR = (!isInPotentialCalculation + || (!isLegalNameChar(previousNonWSChar) + && !(previousNonWSChar == ')' && nextChar == '(') + && !(previousNonWSChar == ')' && currentChar == '*' && !isImmediatelyPostCast()) + && previousNonWSChar != ']') + || (!isWhiteSpace(nextChar) + && nextChar != '-' + && nextChar != '(' + && nextChar != '[' + && !isLegalNameChar(nextChar)) + ); + + return isPR; +} + +/** + * Check if the currently reached '*' or '&' character is + * a dereferenced pointer or "address of" symbol. + * NOTE: this MUST be a pointer or reference as determined by + * the function isPointerOrReference(). + * + * @return whether current character is a dereference or address of + */ +bool ASFormatter::isDereferenceOrAddressOf() const +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + + if (isCharImmediatelyPostTemplate) + return false; + + if (previousNonWSChar == '=' + || previousNonWSChar == ',' + || previousNonWSChar == '.' + || previousNonWSChar == '{' + || previousNonWSChar == '>' + || previousNonWSChar == '<' + || previousNonWSChar == '?' + || isCharImmediatelyPostLineComment + || isCharImmediatelyPostComment + || isCharImmediatelyPostReturn) + return true; + + char nextChar = peekNextChar(); + if (currentChar == '*' && nextChar == '*') + { + if (previousNonWSChar == '(') + return true; + if ((int) currentLine.length() < charNum + 2) + return true; + return false; + } + if (currentChar == '&' && nextChar == '&') + { + if (previousNonWSChar == '(' || isInTemplate) + return true; + if ((int) currentLine.length() < charNum + 2) + return true; + return false; + } + + // check first char on the line + if (charNum == (int) currentLine.find_first_not_of(" \t") + && (isBracketType(bracketTypeStack->back(), COMMAND_TYPE) + || parenStack->back() != 0)) + return true; + + string nextText = peekNextText(currentLine.substr(charNum + 1)); + if (nextText.length() > 0) + { + if (nextText[0] == ')' || nextText[0] == '>' + || nextText[0] == ',' || nextText[0] == '=') + return false; + if (nextText[0] == ';') + return true; + } + + // check for reference to a pointer *& (cannot have &*) + if ((currentChar == '*' && nextChar == '&') + || (previousNonWSChar == '*' && currentChar == '&')) + return false; + + if (!isBracketType(bracketTypeStack->back(), COMMAND_TYPE) + && parenStack->back() == 0) + return false; + + string lastWord = getPreviousWord(currentLine, charNum); + if (lastWord == "else" || lastWord == "delete") + return true; + + if (isPointerOrReferenceVariable(lastWord)) + return false; + + bool isDA = (!(isLegalNameChar(previousNonWSChar) || previousNonWSChar == '>') + || (nextText.length() > 0 && !isLegalNameChar(nextText[0]) && nextText[0] != '/') + || (ispunct((unsigned char)previousNonWSChar) && previousNonWSChar != '.') + || isCharImmediatelyPostReturn); + + return isDA; +} + +/** + * Check if the currently reached '*' or '&' character is + * centered with one space on each side. + * Only spaces are checked, not tabs. + * If true then a space will be deleted on the output. + * + * @return whether current character is centered. + */ +bool ASFormatter::isPointerOrReferenceCentered() const +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + + int prNum = charNum; + int lineLength = (int) currentLine.length(); + + // check for end of line + if (peekNextChar() == ' ') + return false; + + // check space before + if (prNum < 1 + || currentLine[prNum - 1] != ' ') + return false; + + // check no space before that + if (prNum < 2 + || currentLine[prNum - 2] == ' ') + return false; + + // check for ** or && + if (prNum + 1 < lineLength + && (currentLine[prNum + 1] == '*' || currentLine[prNum + 1] == '&')) + prNum++; + + // check space after + if (prNum + 1 <= lineLength + && currentLine[prNum + 1] != ' ') + return false; + + // check no space after that + if (prNum + 2 < lineLength + && currentLine[prNum + 2] == ' ') + return false; + + return true; +} + +/** + * Check if a word is a pointer or reference variable type. + * + * @return whether word is a pointer or reference variable. + */ +bool ASFormatter::isPointerOrReferenceVariable(string& word) const +{ + if (word == "char" + || word == "int" + || word == "void" + || (word.length() >= 6 // check end of word for _t + && word.compare(word.length() - 2, 2, "_t") == 0) + || word == "INT" + || word == "VOID") + return true; + return false; +} + +/** + * check if the currently reached '+' or '-' character is a unary operator + * this method takes for granted that the current character + * is a '+' or '-'. + * + * @return whether the current '+' or '-' is a unary operator. + */ +bool ASFormatter::isUnaryOperator() const +{ + assert(currentChar == '+' || currentChar == '-'); + + return ((isCharImmediatelyPostReturn || !isLegalNameChar(previousCommandChar)) + && previousCommandChar != '.' + && previousCommandChar != '\"' + && previousCommandChar != '\'' + && previousCommandChar != ')' + && previousCommandChar != ']'); +} + +/** + * check if the currently reached comment is in a 'switch' statement + * + * @return whether the current '+' or '-' is in an exponent. + */ +bool ASFormatter::isInSwitchStatement() const +{ + assert(isInLineComment || isInComment); + if (preBracketHeaderStack->size() > 0) + for (size_t i = 1; i < preBracketHeaderStack->size(); i++) + if (preBracketHeaderStack->at(i) == &AS_SWITCH) + return true; + return false; +} + +/** + * check if the currently reached '+' or '-' character is + * part of an exponent, i.e. 0.2E-5. + * + * @return whether the current '+' or '-' is in an exponent. + */ +bool ASFormatter::isInExponent() const +{ + assert(currentChar == '+' || currentChar == '-'); + + int formattedLineLength = formattedLine.length(); + if (formattedLineLength >= 2) + { + char prevPrevFormattedChar = formattedLine[formattedLineLength - 2]; + char prevFormattedChar = formattedLine[formattedLineLength - 1]; + + return ((prevFormattedChar == 'e' || prevFormattedChar == 'E') + && (prevPrevFormattedChar == '.' || isDigit(prevPrevFormattedChar))); + } + else + return false; +} + +/** + * check if an array bracket should NOT have an in-statement indent + * + * @return the array is non in-statement + */ +bool ASFormatter::isNonInStatementArrayBracket() const +{ + bool returnVal = false; + char nextChar = peekNextChar(); + // if this opening bracket begins the line there will be no inStatement indent + if (currentLineBeginsWithBracket + && charNum == (int) currentLineFirstBracketNum + && nextChar != '}') + returnVal = true; + // if an opening bracket ends the line there will be no inStatement indent + if (isWhiteSpace(nextChar) + || isBeforeAnyLineEndComment(charNum) + || nextChar == '{') + returnVal = true; + + // Java "new Type [] {...}" IS an inStatement indent + if (isJavaStyle() && previousNonWSChar == ']') + returnVal = false; + + return returnVal; +} + +/** + * check if a one-line bracket has been reached, + * i.e. if the currently reached '{' character is closed + * with a complimentary '}' elsewhere on the current line, + *. + * @return 0 = one-line bracket has not been reached. + * 1 = one-line bracket has been reached. + * 2 = one-line bracket has been reached and is followed by a comma. + */ +int ASFormatter::isOneLineBlockReached(string& line, int startChar) const +{ + assert(line[startChar] == '{'); + + bool isInComment_ = false; + bool isInQuote_ = false; + int bracketCount = 1; + int lineLength = line.length(); + char quoteChar_ = ' '; + char ch = ' '; + char prevCh = ' '; + + for (int i = startChar + 1; i < lineLength; ++i) + { + ch = line[i]; + + if (isInComment_) + { + if (line.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + + if (ch == '\\') + { + ++i; + continue; + } + + if (isInQuote_) + { + if (ch == quoteChar_) + isInQuote_ = false; + continue; + } + + if (ch == '"' + || (ch == '\'' && !isDigitSeparator(line, i))) + { + isInQuote_ = true; + quoteChar_ = ch; + continue; + } + + if (line.compare(i, 2, "//") == 0) + break; + + if (line.compare(i, 2, "/*") == 0) + { + isInComment_ = true; + ++i; + continue; + } + + if (ch == '{') + ++bracketCount; + else if (ch == '}') + --bracketCount; + + if (bracketCount == 0) + { + // is this an array? + if (parenStack->back() == 0 && prevCh != '}') + { + size_t peekNum = line.find_first_not_of(" \t", i + 1); + if (peekNum != string::npos && line[peekNum] == ',') + return 2; + } + return 1; + } + if (!isWhiteSpace(ch)) + prevCh = ch; + } + + return 0; +} + +/** + * peek at the next word to determine if it is a C# non-paren header. + * will look ahead in the input file if necessary. + * + * @param startChar position on currentLine to start the search + * @return true if the next word is get or set. + */ +bool ASFormatter::isNextWordSharpNonParenHeader(int startChar) const +{ + // look ahead to find the next non-comment text + string nextText = peekNextText(currentLine.substr(startChar)); + if (nextText.length() == 0) + return false; + if (nextText[0] == '[') + return true; + if (!isCharPotentialHeader(nextText, 0)) + return false; + if (findKeyword(nextText, 0, AS_GET) || findKeyword(nextText, 0, AS_SET) + || findKeyword(nextText, 0, AS_ADD) || findKeyword(nextText, 0, AS_REMOVE)) + return true; + return false; +} + +/** + * peek at the next char to determine if it is an opening bracket. + * will look ahead in the input file if necessary. + * this determines a java static constructor. + * + * @param startChar position on currentLine to start the search + * @return true if the next word is an opening bracket. + */ +bool ASFormatter::isNextCharOpeningBracket(int startChar) const +{ + bool retVal = false; + string nextText = peekNextText(currentLine.substr(startChar)); + if (nextText.length() > 0 + && nextText.compare(0, 1, "{") == 0) + retVal = true; + return retVal; +} + +/** +* Check if operator and, pointer, and reference padding is disabled. +* Disabling is done thru a NOPAD tag in an ending comment. +* +* @return true if the formatting on this line is disabled. +*/ +bool ASFormatter::isOperatorPaddingDisabled() const +{ + size_t commentStart = currentLine.find("//", charNum); + if (commentStart == string::npos) + { + commentStart = currentLine.find("/*", charNum); + // comment must end on this line + if (commentStart != string::npos) + { + size_t commentEnd = currentLine.find("*/", commentStart + 2); + if (commentEnd == string::npos) + commentStart = string::npos; + } + } + if (commentStart == string::npos) + return false; + size_t noPadStart = currentLine.find("*NOPAD*", commentStart); + if (noPadStart == string::npos) + return false; + return true; +} + +/** +* Determine if an opening array-type bracket should have a leading space pad. +* This is to identify C++11 uniform initializers. +*/ +bool ASFormatter::isUniformInitializerBracket() const +{ + if (isCStyle() && !isInEnum && !isImmediatelyPostPreprocessor) + { + if (isInClassInitializer + || isLegalNameChar(previousNonWSChar)) + return true; + } + return false; +} + +/** + * get the next non-whitespace substring on following lines, bypassing all comments. + * + * @param firstLine the first line to check + * @return the next non-whitespace substring. + */ +string ASFormatter::peekNextText(const string& firstLine, bool endOnEmptyLine /*false*/, bool shouldReset /*false*/) const +{ + bool isFirstLine = true; + bool needReset = shouldReset; + string nextLine_ = firstLine; + size_t firstChar = string::npos; + + // find the first non-blank text, bypassing all comments. + bool isInComment_ = false; + while (sourceIterator->hasMoreLines() || isFirstLine) + { + if (isFirstLine) + isFirstLine = false; + else + { + nextLine_ = sourceIterator->peekNextLine(); + needReset = true; + } + + firstChar = nextLine_.find_first_not_of(" \t"); + if (firstChar == string::npos) + { + if (endOnEmptyLine && !isInComment_) + break; + continue; + } + + if (nextLine_.compare(firstChar, 2, "/*") == 0) + { + firstChar += 2; + isInComment_ = true; + } + + if (isInComment_) + { + firstChar = nextLine_.find("*/", firstChar); + if (firstChar == string::npos) + continue; + firstChar += 2; + isInComment_ = false; + firstChar = nextLine_.find_first_not_of(" \t", firstChar); + if (firstChar == string::npos) + continue; + } + + if (nextLine_.compare(firstChar, 2, "//") == 0) + continue; + + // found the next text + break; + } + + if (firstChar == string::npos) + nextLine_ = ""; + else + nextLine_ = nextLine_.substr(firstChar); + if (needReset) + sourceIterator->peekReset(); + return nextLine_; +} + +/** + * adjust comment position because of adding or deleting spaces + * the spaces are added or deleted to formattedLine + * spacePadNum contains the adjustment + */ +void ASFormatter::adjustComments(void) +{ + assert(spacePadNum != 0); + assert(currentLine.compare(charNum, 2, "//") == 0 + || currentLine.compare(charNum, 2, "/*") == 0); + + // block comment must be closed on this line with nothing after it + if (currentLine.compare(charNum, 2, "/*") == 0) + { + size_t endNum = currentLine.find("*/", charNum + 2); + if (endNum == string::npos) + return; + if (currentLine.find_first_not_of(" \t", endNum + 2) != string::npos) + return; + } + + size_t len = formattedLine.length(); + // don't adjust a tab + if (formattedLine[len - 1] == '\t') + return; + // if spaces were removed, need to add spaces before the comment + if (spacePadNum < 0) + { + int adjust = -spacePadNum; // make the number positive + formattedLine.append(adjust, ' '); + } + // if spaces were added, need to delete extra spaces before the comment + // if cannot be done put the comment one space after the last text + else if (spacePadNum > 0) + { + int adjust = spacePadNum; + size_t lastText = formattedLine.find_last_not_of(' '); + if (lastText != string::npos + && lastText < len - adjust - 1) + formattedLine.resize(len - adjust); + else if (len > lastText + 2) + formattedLine.resize(lastText + 2); + else if (len < lastText + 2) + formattedLine.append(len - lastText, ' '); + } +} + +/** + * append the current bracket inside the end of line comments + * currentChar contains the bracket, it will be appended to formattedLine + * formattedLineCommentNum is the comment location on formattedLine + */ +void ASFormatter::appendCharInsideComments(void) +{ + if (formattedLineCommentNum == string::npos) // does the comment start on the previous line? + { + appendCurrentChar(); // don't attach + return; + } + assert(formattedLine.compare(formattedLineCommentNum, 2, "//") == 0 + || formattedLine.compare(formattedLineCommentNum, 2, "/*") == 0); + + // find the previous non space char + size_t end = formattedLineCommentNum; + size_t beg = formattedLine.find_last_not_of(" \t", end - 1); + if (beg == string::npos) + { + appendCurrentChar(); // don't attach + return; + } + beg++; + + // insert the bracket + if (end - beg < 3) // is there room to insert? + formattedLine.insert(beg, 3 - end + beg, ' '); + if (formattedLine[beg] == '\t') // don't pad with a tab + formattedLine.insert(beg, 1, ' '); + formattedLine[beg + 1] = currentChar; + testForTimeToSplitFormattedLine(); + + if (isBeforeComment()) + breakLine(); + else if (isCharImmediatelyPostLineComment) + shouldBreakLineAtNextChar = true; + return; +} + +/** + * add or remove space padding to operators + * the operators and necessary padding will be appended to formattedLine + * the calling function should have a continue statement after calling this method + * + * @param newOperator the operator to be padded + */ +void ASFormatter::padOperators(const string* newOperator) +{ + assert(shouldPadOperators); + assert(newOperator != NULL); + + bool shouldPad = (newOperator != &AS_SCOPE_RESOLUTION + && newOperator != &AS_PLUS_PLUS + && newOperator != &AS_MINUS_MINUS + && newOperator != &AS_NOT + && newOperator != &AS_BIT_NOT + && newOperator != &AS_ARROW + && !(newOperator == &AS_COLON && !foundQuestionMark // objC methods + && (isInObjCMethodDefinition || isInObjCInterface + || isInObjCSelector || squareBracketCount)) + && !(newOperator == &AS_MINUS && isInExponent()) + && !((newOperator == &AS_PLUS || newOperator == &AS_MINUS) // check for unary plus or minus + && (previousNonWSChar == '(' + || previousNonWSChar == '[' + || previousNonWSChar == '=' + || previousNonWSChar == ',')) + && !(newOperator == &AS_PLUS && isInExponent()) + && !isCharImmediatelyPostOperator +//? // commented out in release 2.05.1 - doesn't seem to do anything??? +//x && !((newOperator == &AS_MULT || newOperator == &AS_BIT_AND || newOperator == &AS_AND) +//x && isPointerOrReference()) + && !(newOperator == &AS_MULT + && (previousNonWSChar == '.' + || previousNonWSChar == '>')) // check for -> + && !((isInTemplate || isImmediatelyPostTemplate) + && (newOperator == &AS_LS || newOperator == &AS_GR)) + && !(newOperator == &AS_GCC_MIN_ASSIGN + && ASBase::peekNextChar(currentLine, charNum + 1) == '>') + && !(newOperator == &AS_GR && previousNonWSChar == '?') + && !(newOperator == &AS_QUESTION // check for Java wildcard + && (previousNonWSChar == '<' + || ASBase::peekNextChar(currentLine, charNum) == '>' + || ASBase::peekNextChar(currentLine, charNum) == '.')) + && !isInCase + && !isInAsm + && !isInAsmOneLine + && !isInAsmBlock + ); + + // pad before operator + if (shouldPad + && !(newOperator == &AS_COLON + && (!foundQuestionMark && !isInEnum) && currentHeader != &AS_FOR) + && !(newOperator == &AS_QUESTION && isSharpStyle() // check for C# nullable type (e.g. int?) + && currentLine.find(':', charNum + 1) == string::npos) + ) + appendSpacePad(); + appendOperator(*newOperator); + goForward(newOperator->length() - 1); + + currentChar = (*newOperator)[newOperator->length() - 1]; + // pad after operator + // but do not pad after a '-' that is a unary-minus. + if (shouldPad + && !isBeforeAnyComment() + && !(newOperator == &AS_PLUS && isUnaryOperator()) + && !(newOperator == &AS_MINUS && isUnaryOperator()) + && !(currentLine.compare(charNum + 1, 1, AS_SEMICOLON) == 0) + && !(currentLine.compare(charNum + 1, 2, AS_SCOPE_RESOLUTION) == 0) + && !(peekNextChar() == ',') + && !(newOperator == &AS_QUESTION && isSharpStyle() // check for C# nullable type (e.g. int?) + && peekNextChar() == '[') + ) + appendSpaceAfter(); + + previousOperator = newOperator; + return; +} + +/** + * format pointer or reference + * currentChar contains the pointer or reference + * the symbol and necessary padding will be appended to formattedLine + * the calling function should have a continue statement after calling this method + * + * NOTE: Do NOT use appendCurrentChar() in this method. The line should not be + * broken once the calculation starts. + */ +void ASFormatter::formatPointerOrReference(void) +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + assert(!isJavaStyle()); + + int pa = pointerAlignment; + int ra = referenceAlignment; + int itemAlignment = (currentChar == '*' || currentChar == '^') ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); + + // check for ** and && + char peekedChar = peekNextChar(); + if ((currentChar == '*' && peekedChar == '*') + || (currentChar == '&' && peekedChar == '&')) + { + size_t nextChar = currentLine.find_first_not_of(" \t", charNum + 2); + if (nextChar == string::npos) + peekedChar = ' '; + else + peekedChar = currentLine[nextChar]; + } + // check for cast + if (peekedChar == ')' || peekedChar == '>' || peekedChar == ',') + { + formatPointerOrReferenceCast(); + return; + } + + // check for a padded space and remove it + if (charNum > 0 + && !isWhiteSpace(currentLine[charNum - 1]) + && formattedLine.length() > 0 + && isWhiteSpace(formattedLine[formattedLine.length() - 1])) + { + formattedLine.erase(formattedLine.length() - 1); + spacePadNum--; + } + + if (itemAlignment == PTR_ALIGN_TYPE) + { + formatPointerOrReferenceToType(); + } + else if (itemAlignment == PTR_ALIGN_MIDDLE) + { + formatPointerOrReferenceToMiddle(); + } + else if (itemAlignment == PTR_ALIGN_NAME) + { + formatPointerOrReferenceToName(); + } + else // pointerAlignment == PTR_ALIGN_NONE + { + formattedLine.append(1, currentChar); + } +} + +/** + * format pointer or reference with align to type + */ +void ASFormatter::formatPointerOrReferenceToType() +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + assert(!isJavaStyle()); + + // do this before bumping charNum + bool isOldPRCentered = isPointerOrReferenceCentered(); + + size_t prevCh = formattedLine.find_last_not_of(" \t"); + if (prevCh == string::npos) + prevCh = 0; + if (formattedLine.length() == 0 || prevCh == formattedLine.length() - 1) + formattedLine.append(1, currentChar); + else + { + // exchange * or & with character following the type + // this may not work every time with a tab character + string charSave = formattedLine.substr(prevCh + 1, 1); + formattedLine[prevCh + 1] = currentChar; + formattedLine.append(charSave); + } + if (isSequenceReached("**") || isSequenceReached("&&")) + { + if (formattedLine.length() == 1) + formattedLine.append(1, currentChar); + else + formattedLine.insert(prevCh + 2, 1, currentChar); + goForward(1); + } + // if no space after then add one + if (charNum < (int) currentLine.length() - 1 + && !isWhiteSpace(currentLine[charNum + 1]) + && currentLine[charNum + 1] != ')') + appendSpacePad(); + // if old pointer or reference is centered, remove a space + if (isOldPRCentered + && isWhiteSpace(formattedLine[formattedLine.length() - 1])) + { + formattedLine.erase(formattedLine.length() - 1, 1); + spacePadNum--; + } + // update the formattedLine split point + if (maxCodeLength != string::npos) + { + size_t index = formattedLine.length() - 1; + if (isWhiteSpace(formattedLine[index])) + { + updateFormattedLineSplitPointsPointerOrReference(index); + testForTimeToSplitFormattedLine(); + } + } +} + +/** + * format pointer or reference with align in the middle + */ +void ASFormatter::formatPointerOrReferenceToMiddle() +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + assert(!isJavaStyle()); + + // compute current whitespace before + size_t wsBefore = currentLine.find_last_not_of(" \t", charNum - 1); + if (wsBefore == string::npos) + wsBefore = 0; + else + wsBefore = charNum - wsBefore - 1; + string sequenceToInsert(1, currentChar); + if (isSequenceReached("**")) + { + sequenceToInsert = "**"; + goForward(1); + } + else if (isSequenceReached("&&")) + { + sequenceToInsert = "&&"; + goForward(1); + } + // if reference to a pointer check for conflicting alignment + else if (currentChar == '*' && peekNextChar() == '&' + && (referenceAlignment == REF_ALIGN_TYPE + || referenceAlignment == REF_ALIGN_MIDDLE + || referenceAlignment == REF_SAME_AS_PTR)) + { + sequenceToInsert = "*&"; + goForward(1); + for (size_t i = charNum; i < currentLine.length() - 1 && isWhiteSpace(currentLine[i]); i++) + goForward(1); + } + // if a comment follows don't align, just space pad + if (isBeforeAnyComment()) + { + appendSpacePad(); + formattedLine.append(sequenceToInsert); + appendSpaceAfter(); + return; + } + // do this before goForward() + bool isAfterScopeResolution = previousNonWSChar == ':'; + size_t charNumSave = charNum; + // if this is the last thing on the line + if (currentLine.find_first_not_of(" \t", charNum + 1) == string::npos) + { + if (wsBefore == 0 && !isAfterScopeResolution) + formattedLine.append(1, ' '); + formattedLine.append(sequenceToInsert); + return; + } + // goForward() to convert tabs to spaces, if necessary, + // and move following characters to preceding characters + // this may not work every time with tab characters + for (size_t i = charNum + 1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) + { + goForward(1); + if (formattedLine.length() > 0) + formattedLine.append(1, currentLine[i]); + else + spacePadNum--; + } + // find space padding after + size_t wsAfter = currentLine.find_first_not_of(" \t", charNumSave + 1); + if (wsAfter == string::npos || isBeforeAnyComment()) + wsAfter = 0; + else + wsAfter = wsAfter - charNumSave - 1; + // don't pad before scope resolution operator, but pad after + if (isAfterScopeResolution) + { + size_t lastText = formattedLine.find_last_not_of(" \t"); + formattedLine.insert(lastText + 1, sequenceToInsert); + appendSpacePad(); + } + else if (formattedLine.length() > 0) + { + // whitespace should be at least 2 chars to center + if (wsBefore + wsAfter < 2) + { + size_t charsToAppend = (2 - (wsBefore + wsAfter)); + formattedLine.append(charsToAppend, ' '); + spacePadNum += charsToAppend; + if (wsBefore == 0) wsBefore++; + if (wsAfter == 0) wsAfter++; + } + // insert the pointer or reference char + size_t padAfter = (wsBefore + wsAfter) / 2; + size_t index = formattedLine.length() - padAfter; + formattedLine.insert(index, sequenceToInsert); + } + else // formattedLine.length() == 0 + { + formattedLine.append(sequenceToInsert); + if (wsAfter == 0) + wsAfter++; + formattedLine.append(wsAfter, ' '); + spacePadNum += wsAfter; + } + // update the formattedLine split point after the pointer + if (maxCodeLength != string::npos && formattedLine.length() > 0) + { + size_t index = formattedLine.find_last_not_of(" \t"); + if (index != string::npos && (index < formattedLine.length() - 1)) + { + index++; + updateFormattedLineSplitPointsPointerOrReference(index); + testForTimeToSplitFormattedLine(); + } + } +} + +/** + * format pointer or reference with align to name + */ +void ASFormatter::formatPointerOrReferenceToName() +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + assert(!isJavaStyle()); + + // do this before bumping charNum + bool isOldPRCentered = isPointerOrReferenceCentered(); + + size_t startNum = formattedLine.find_last_not_of(" \t"); + if (startNum == string::npos) + startNum = 0; + string sequenceToInsert(1, currentChar); + if (isSequenceReached("**")) + { + sequenceToInsert = "**"; + goForward(1); + } + else if (isSequenceReached("&&")) + { + sequenceToInsert = "&&"; + goForward(1); + } + // if reference to a pointer align both to name + else if (currentChar == '*' && peekNextChar() == '&') + { + sequenceToInsert = "*&"; + goForward(1); + for (size_t i = charNum; i < currentLine.length() - 1 && isWhiteSpace(currentLine[i]); i++) + goForward(1); + } + char peekedChar = peekNextChar(); + bool isAfterScopeResolution = previousNonWSChar == ':'; // check for :: + // if this is not the last thing on the line + if (!isBeforeAnyComment() + && (int) currentLine.find_first_not_of(" \t", charNum + 1) > charNum) + { + // goForward() to convert tabs to spaces, if necessary, + // and move following characters to preceding characters + // this may not work every time with tab characters + for (size_t i = charNum + 1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) + { + // if a padded paren follows don't move + if (shouldPadParensOutside && peekedChar == '(' && !isOldPRCentered) + { + // empty parens don't count + size_t start = currentLine.find_first_not_of("( \t", charNum + 1); + if (start != string::npos && currentLine[start] != ')') + break; + } + goForward(1); + if (formattedLine.length() > 0) + formattedLine.append(1, currentLine[i]); + else + spacePadNum--; + } + } + // don't pad before scope resolution operator + if (isAfterScopeResolution) + { + size_t lastText = formattedLine.find_last_not_of(" \t"); + if (lastText != string::npos && lastText + 1 < formattedLine.length()) + formattedLine.erase(lastText + 1); + } + // if no space before * then add one + else if (formattedLine.length() > 0 + && (formattedLine.length() <= startNum + 1 + || !isWhiteSpace(formattedLine[startNum + 1]))) + { + formattedLine.insert(startNum + 1, 1, ' '); + spacePadNum++; + } + appendSequence(sequenceToInsert, false); + // if old pointer or reference is centered, remove a space + if (isOldPRCentered + && formattedLine.length() > startNum + 1 + && isWhiteSpace(formattedLine[startNum + 1]) + && !isBeforeAnyComment()) + { + formattedLine.erase(startNum + 1, 1); + spacePadNum--; + } + // don't convert to *= or &= + if (peekedChar == '=') + { + appendSpaceAfter(); + // if more than one space before, delete one + if (formattedLine.length() > startNum + && isWhiteSpace(formattedLine[startNum + 1]) + && isWhiteSpace(formattedLine[startNum + 2])) + { + formattedLine.erase(startNum + 1, 1); + spacePadNum--; + } + } + // update the formattedLine split point + if (maxCodeLength != string::npos) + { + size_t index = formattedLine.find_last_of(" \t"); + if (index != string::npos + && index < formattedLine.length() - 1 + && (formattedLine[index + 1] == '*' + || formattedLine[index + 1] == '&' + || formattedLine[index + 1] == '^')) + { + updateFormattedLineSplitPointsPointerOrReference(index); + testForTimeToSplitFormattedLine(); + } + } +} + +/** + * format pointer or reference cast + * currentChar contains the pointer or reference + * NOTE: the pointers and references in function definitions + * are processed as a cast (e.g. void foo(void*, void*)) + * is processed here. + */ +void ASFormatter::formatPointerOrReferenceCast(void) +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + assert(!isJavaStyle()); + + int pa = pointerAlignment; + int ra = referenceAlignment; + int itemAlignment = (currentChar == '*' || currentChar == '^') ? pa : ((ra == REF_SAME_AS_PTR) ? pa : ra); + + string sequenceToInsert(1, currentChar); + if (isSequenceReached("**") || isSequenceReached("&&")) + { + goForward(1); + sequenceToInsert.append(1, currentLine[charNum]); + } + if (itemAlignment == PTR_ALIGN_NONE) + { + appendSequence(sequenceToInsert, false); + return; + } + // remove preceding whitespace + char prevCh = ' '; + size_t prevNum = formattedLine.find_last_not_of(" \t"); + if (prevNum != string::npos) + { + prevCh = formattedLine[prevNum]; + if (prevNum + 1 < formattedLine.length() + && isWhiteSpace(formattedLine[prevNum + 1]) + && prevCh != '(') + { + spacePadNum -= (formattedLine.length() - 1 - prevNum); + formattedLine.erase(prevNum + 1); + } + } + bool isAfterScopeResolution = previousNonWSChar == ':'; + if ((itemAlignment == PTR_ALIGN_MIDDLE || itemAlignment == PTR_ALIGN_NAME) + && !isAfterScopeResolution && prevCh != '(') + { + appendSpacePad(); + // in this case appendSpacePad may or may not update the split point + if (maxCodeLength != string::npos && formattedLine.length() > 0) + updateFormattedLineSplitPointsPointerOrReference(formattedLine.length() - 1); + appendSequence(sequenceToInsert, false); + } + else + appendSequence(sequenceToInsert, false); +} + +/** + * add or remove space padding to parens + * currentChar contains the paren + * the parens and necessary padding will be appended to formattedLine + * the calling function should have a continue statement after calling this method + */ +void ASFormatter::padParens(void) +{ + assert(currentChar == '(' || currentChar == ')'); + assert(shouldPadParensOutside || shouldPadParensInside || shouldUnPadParens || shouldPadFirstParen); + + int spacesOutsideToDelete = 0; + int spacesInsideToDelete = 0; + + if (currentChar == '(') + { + spacesOutsideToDelete = formattedLine.length() - 1; + spacesInsideToDelete = 0; + + // compute spaces outside the opening paren to delete + if (shouldUnPadParens) + { + char lastChar = ' '; + bool prevIsParenHeader = false; + size_t i = formattedLine.find_last_not_of(" \t"); + if (i != string::npos) + { + // if last char is a bracket the previous whitespace is an indent + if (formattedLine[i] == '{') + spacesOutsideToDelete = 0; + else if (isCharImmediatelyPostPointerOrReference) + spacesOutsideToDelete = 0; + else + { + spacesOutsideToDelete -= i; + lastChar = formattedLine[i]; + // if previous word is a header, it will be a paren header + string prevWord = getPreviousWord(formattedLine, formattedLine.length()); + const string* prevWordH = NULL; + if (shouldPadHeader + && prevWord.length() > 0 + && isCharPotentialHeader(prevWord, 0)) + prevWordH = ASBeautifier::findHeader(prevWord, 0, headers); + if (prevWordH != NULL) + prevIsParenHeader = true; + else if (prevWord == "return") // don't unpad + prevIsParenHeader = true; + else if (isCStyle() && prevWord == "throw" && shouldPadHeader) // don't unpad + prevIsParenHeader = true; + else if (prevWord == "and" || prevWord == "or") // don't unpad + prevIsParenHeader = true; + // don't unpad variables + else if (prevWord == "bool" + || prevWord == "int" + || prevWord == "void" + || prevWord == "void*" + || prevWord == "char" + || prevWord == "long" + || prevWord == "double" + || prevWord == "float" + || (prevWord.length() >= 4 // check end of word for _t + && prevWord.compare(prevWord.length() - 2, 2, "_t") == 0) + || prevWord == "Int32" + || prevWord == "UInt32" + || prevWord == "Int64" + || prevWord == "UInt64" + || prevWord == "BOOL" + || prevWord == "DWORD" + || prevWord == "HWND" + || prevWord == "INT" + || prevWord == "LPSTR" + || prevWord == "VOID" + || prevWord == "LPVOID" + ) + { + prevIsParenHeader = true; + } + } + } + // do not unpad operators, but leave them if already padded + if (shouldPadParensOutside || prevIsParenHeader) + spacesOutsideToDelete--; + else if (lastChar == '|' // check for || + || lastChar == '&' // check for && + || lastChar == ',' + || (lastChar == '(' && shouldPadParensInside) + || (lastChar == '>' && !foundCastOperator) + || lastChar == '<' + || lastChar == '?' + || lastChar == ':' + || lastChar == ';' + || lastChar == '=' + || lastChar == '+' + || lastChar == '-' + || lastChar == '*' + || lastChar == '/' + || lastChar == '%' + || lastChar == '^' + ) + spacesOutsideToDelete--; + + if (spacesOutsideToDelete > 0) + { + formattedLine.erase(i + 1, spacesOutsideToDelete); + spacePadNum -= spacesOutsideToDelete; + } + } + + // pad open paren outside + char peekedCharOutside = peekNextChar(); + if (shouldPadFirstParen && previousChar != '(' && peekedCharOutside != ')') + appendSpacePad(); + else if (shouldPadParensOutside) + { + if (!(currentChar == '(' && peekedCharOutside == ')')) + appendSpacePad(); + } + + appendCurrentChar(); + + // unpad open paren inside + if (shouldUnPadParens) + { + size_t j = currentLine.find_first_not_of(" \t", charNum + 1); + if (j != string::npos) + spacesInsideToDelete = j - charNum - 1; + if (shouldPadParensInside) + spacesInsideToDelete--; + if (spacesInsideToDelete > 0) + { + currentLine.erase(charNum + 1, spacesInsideToDelete); + spacePadNum -= spacesInsideToDelete; + } + // convert tab to space if requested + if (shouldConvertTabs + && (int) currentLine.length() > charNum + 1 + && currentLine[charNum + 1] == '\t') + currentLine[charNum + 1] = ' '; + } + + // pad open paren inside + char peekedCharInside = peekNextChar(); + if (shouldPadParensInside) + if (!(currentChar == '(' && peekedCharInside == ')')) + appendSpaceAfter(); + } + else if (currentChar == ')') + { + // unpad close paren inside + if (shouldUnPadParens) + { + spacesInsideToDelete = formattedLine.length(); + size_t i = formattedLine.find_last_not_of(" \t"); + if (i != string::npos) + spacesInsideToDelete = formattedLine.length() - 1 - i; + if (shouldPadParensInside) + spacesInsideToDelete--; + if (spacesInsideToDelete > 0) + { + formattedLine.erase(i + 1, spacesInsideToDelete); + spacePadNum -= spacesInsideToDelete; + } + } + + // pad close paren inside + if (shouldPadParensInside) + if (!(previousChar == '(' && currentChar == ')')) + appendSpacePad(); + + appendCurrentChar(); + + // unpad close paren outside + // close parens outside are left unchanged + if (shouldUnPadParens) + { + //spacesOutsideToDelete = 0; + //size_t j = currentLine.find_first_not_of(" \t", charNum + 1); + //if (j != string::npos) + // spacesOutsideToDelete = j - charNum - 1; + //if (shouldPadParensOutside) + // spacesOutsideToDelete--; + + //if (spacesOutsideToDelete > 0) + //{ + // currentLine.erase(charNum + 1, spacesOutsideToDelete); + // spacePadNum -= spacesOutsideToDelete; + //} + } + + // pad close paren outside + char peekedCharOutside = peekNextChar(); + if (shouldPadParensOutside) + if (peekedCharOutside != ';' + && peekedCharOutside != ',' + && peekedCharOutside != '.' + && peekedCharOutside != '+' // check for ++ + && peekedCharOutside != '-' // check for -- + && peekedCharOutside != ']') + appendSpaceAfter(); + } + return; +} + +/** +* add or remove space padding to objective-c parens +* these options have precedence over the padParens methods +* the padParens method has already been called, this method adjusts +*/ +void ASFormatter::padParenObjC(void) +{ + // the paren was previously been written to formattedLine + assert(formattedLine[0] == '+' || formattedLine[0] == '-'); + assert(formattedLine.find('(') != string::npos + || formattedLine.find(')') != string::npos); + assert(isImmediatelyPostObjCMethodPrefix || isInObjCReturnType); + assert(shouldPadMethodPrefix || shouldUnPadMethodPrefix + || shouldPadReturnType || shouldUnPadReturnType); + + if (isImmediatelyPostObjCMethodPrefix) + { + size_t prefix = formattedLine.find_first_of("+-"); + if (prefix == string::npos) + return; + size_t paren = formattedLine.find_first_of("("); + if (paren == string::npos) + return; + int spaces = paren - prefix - 1; + if (shouldPadMethodPrefix) + { + if (spaces == 0) + { + formattedLine.insert(prefix + 1, 1, ' '); + spacePadNum += 1; + } + else if (spaces > 1) + { + formattedLine.erase(prefix + 1, spaces - 1); + spacePadNum -= spaces - 1; + } + } + // this option will be ignored if used with pad-method-prefix + else if (shouldUnPadMethodPrefix) + { + if (spaces > 0) + { + formattedLine.erase(prefix + 1, spaces); + spacePadNum -= spaces; + } + } + } + + if (isInObjCReturnType) + { + size_t nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText == string::npos) + return; + int spaces = nextText - charNum - 1; + if (shouldPadReturnType) + { + if (spaces == 0) + { + // this will already be padded if pad-paren is used + if (formattedLine[formattedLine.length() - 1] != ' ') + { + formattedLine.append(" "); + spacePadNum += 1; + } + } + else if (spaces > 1) + { + // do not use goForward here + currentLine.erase(charNum + 1, spaces - 1); + spacePadNum -= spaces - 1; + } + } + // this option will be ignored if used with pad-return-type + else if (shouldUnPadReturnType) + { + // this will already be padded if pad-paren is used + if (formattedLine[formattedLine.length() - 1] == ' ') + { + spacePadNum -= formattedLine.length() - 1 - nextText; + int lastText = formattedLine.find_last_not_of(" \t"); + formattedLine.resize(lastText + 1); + } + if (spaces > 0) + { + // do not use goForward here + currentLine.erase(charNum + 1, spaces); + spacePadNum -= spaces; + } + } + } +} + +/** + * format opening bracket as attached or broken + * currentChar contains the bracket + * the brackets will be appended to the current formattedLine or a new formattedLine as necessary + * the calling function should have a continue statement after calling this method + * + * @param bracketType the type of bracket to be formatted. + */ +void ASFormatter::formatOpeningBracket(BracketType bracketType) +{ + assert(!isBracketType(bracketType, ARRAY_TYPE)); + assert(currentChar == '{'); + + parenStack->push_back(0); + + bool breakBracket = isCurrentBracketBroken(); + + if (breakBracket) + { + if (isBeforeAnyComment() && isOkToBreakBlock(bracketType)) + { + // if comment is at line end leave the comment on this line + if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) + { + currentChar = ' '; // remove bracket from current line + if (parenStack->size() > 1) + parenStack->pop_back(); + currentLine[charNum] = currentChar; + appendOpeningBracket = true; // append bracket to following line + } + // else put comment after the bracket + else if (!isBeforeMultipleLineEndComments(charNum)) + breakLine(); + } + else if (!isBracketType(bracketType, SINGLE_LINE_TYPE)) + breakLine(); + else if (shouldBreakOneLineBlocks && peekNextChar() != '}') + breakLine(); + else if (!isInLineBreak) + appendSpacePad(); + + appendCurrentChar(); + + // should a following comment break from the bracket? + // must break the line AFTER the bracket + if (isBeforeComment() + && formattedLine.length() > 0 + && formattedLine[0] == '{' + && isOkToBreakBlock(bracketType) + && (bracketFormatMode == BREAK_MODE + || bracketFormatMode == LINUX_MODE + || bracketFormatMode == STROUSTRUP_MODE)) + { + shouldBreakLineAtNextChar = true; + } + } + else // attach bracket + { + // are there comments before the bracket? + if (isCharImmediatelyPostComment || isCharImmediatelyPostLineComment) + { + if (isOkToBreakBlock(bracketType) + && !(isCharImmediatelyPostComment && isCharImmediatelyPostLineComment) // don't attach if two comments on the line + && !isImmediatelyPostPreprocessor +// && peekNextChar() != '}' // don't attach { } // removed release 2.03 + && previousCommandChar != '{' // don't attach { { + && previousCommandChar != '}' // don't attach } { + && previousCommandChar != ';') // don't attach ; { + { + appendCharInsideComments(); + } + else + { + appendCurrentChar(); // don't attach + } + } + else if (previousCommandChar == '{' + || (previousCommandChar == '}' && !isInClassInitializer) + || previousCommandChar == ';') // '}' , ';' chars added for proper handling of '{' immediately after a '}' or ';' + { + appendCurrentChar(); // don't attach + } + else + { + // if a blank line precedes this don't attach + if (isEmptyLine(formattedLine)) + appendCurrentChar(); // don't attach + else if (isOkToBreakBlock(bracketType) + && !(isImmediatelyPostPreprocessor + && currentLineBeginsWithBracket)) + { + if (peekNextChar() != '}') + { + appendSpacePad(); + appendCurrentChar(false); // OK to attach + testForTimeToSplitFormattedLine(); // line length will have changed + // should a following comment attach with the bracket? + // insert spaces to reposition the comment + if (isBeforeComment() + && !isBeforeMultipleLineEndComments(charNum) + && (!isBeforeAnyLineEndComment(charNum) || currentLineBeginsWithBracket)) + { + shouldBreakLineAtNextChar = true; + currentLine.insert(charNum + 1, charNum + 1, ' '); + } + else if (!isBeforeAnyComment()) // added in release 2.03 + { + shouldBreakLineAtNextChar = true; + } + } + else + { + if (currentLineBeginsWithBracket && charNum == (int) currentLineFirstBracketNum) + { + appendSpacePad(); + appendCurrentChar(false); // attach + shouldBreakLineAtNextChar = true; + } + else + { + appendSpacePad(); + appendCurrentChar(); // don't attach + } + } + } + else + { + if (!isInLineBreak) + appendSpacePad(); + appendCurrentChar(); // don't attach + } + } + } +} + +/** + * format closing bracket + * currentChar contains the bracket + * the calling function should have a continue statement after calling this method + * + * @param bracketType the type of the opening bracket for this closing bracket. + */ +void ASFormatter::formatClosingBracket(BracketType bracketType) +{ + assert(!isBracketType(bracketType, ARRAY_TYPE)); + assert(currentChar == '}'); + + // parenStack must contain one entry + if (parenStack->size() > 1) + parenStack->pop_back(); + + // mark state of immediately after empty block + // this state will be used for locating brackets that appear immediately AFTER an empty block (e.g. '{} \n}'). + if (previousCommandChar == '{') + isImmediatelyPostEmptyBlock = true; + + if (attachClosingBracketMode) + { + // for now, namespaces and classes will be attached. Uncomment the lines below to break. + if ((isEmptyLine(formattedLine) // if a blank line precedes this + || isCharImmediatelyPostLineComment + || isCharImmediatelyPostComment + || (isImmediatelyPostPreprocessor && (int) currentLine.find_first_not_of(" \t") == charNum) +// || (isBracketType(bracketType, CLASS_TYPE) && isOkToBreakBlock(bracketType) && previousNonWSChar != '{') +// || (isBracketType(bracketType, NAMESPACE_TYPE) && isOkToBreakBlock(bracketType) && previousNonWSChar != '{') + ) + && (!isBracketType(bracketType, SINGLE_LINE_TYPE) || isOkToBreakBlock(bracketType))) + { + breakLine(); + appendCurrentChar(); // don't attach + } + else + { + if (previousNonWSChar != '{' + && (!isBracketType(bracketType, SINGLE_LINE_TYPE) || isOkToBreakBlock(bracketType))) + appendSpacePad(); + appendCurrentChar(false); // attach + } + } + else if ((!(previousCommandChar == '{' && isPreviousBracketBlockRelated)) // this '}' does not close an empty block + && isOkToBreakBlock(bracketType)) // astyle is allowed to break one line blocks + { + breakLine(); + appendCurrentChar(); + } + else + { + appendCurrentChar(); + } + + // if a declaration follows a definition, space pad + if (isLegalNameChar(peekNextChar())) + appendSpaceAfter(); + + if (shouldBreakBlocks + && currentHeader != NULL + && !isHeaderInMultiStatementLine + && parenStack->back() == 0) + { + if (currentHeader == &AS_CASE || currentHeader == &AS_DEFAULT) + { + // do not yet insert a line if "break" statement is outside the brackets + string nextText = peekNextText(currentLine.substr(charNum + 1)); + if (nextText.length() > 0 + && nextText.substr(0, 5) != "break") + isAppendPostBlockEmptyLineRequested = true; + } + else + isAppendPostBlockEmptyLineRequested = true; + } +} + +/** + * format array brackets as attached or broken + * determine if the brackets can have an inStatement indent + * currentChar contains the bracket + * the brackets will be appended to the current formattedLine or a new formattedLine as necessary + * the calling function should have a continue statement after calling this method + * + * @param bracketType the type of bracket to be formatted, must be an ARRAY_TYPE. + * @param isOpeningArrayBracket indicates if this is the opening bracket for the array block. + */ +void ASFormatter::formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket) +{ + assert(isBracketType(bracketType, ARRAY_TYPE)); + assert(currentChar == '{' || currentChar == '}'); + + if (currentChar == '{') + { + // is this the first opening bracket in the array? + if (isOpeningArrayBracket) + { + if (bracketFormatMode == ATTACH_MODE + || bracketFormatMode == LINUX_MODE + || bracketFormatMode == STROUSTRUP_MODE) + { + // don't attach to a preprocessor directive or '\' line + if ((isImmediatelyPostPreprocessor + || (formattedLine.length() > 0 + && formattedLine[formattedLine.length() - 1] == '\\')) + && currentLineBeginsWithBracket) + { + isInLineBreak = true; + appendCurrentChar(); // don't attach + } + else if (isCharImmediatelyPostComment) + { + // TODO: attach bracket to line-end comment + appendCurrentChar(); // don't attach + } + else if (isCharImmediatelyPostLineComment && !isBracketType(bracketType, SINGLE_LINE_TYPE)) + { + appendCharInsideComments(); + } + else + { + // if a blank line precedes this don't attach + if (isEmptyLine(formattedLine)) + appendCurrentChar(); // don't attach + else + { + // if bracket is broken or not an assignment + if (currentLineBeginsWithBracket + && !isBracketType(bracketType, SINGLE_LINE_TYPE)) + { + appendSpacePad(); + appendCurrentChar(false); // OK to attach + // TODO: debug the following line + testForTimeToSplitFormattedLine(); // line length will have changed + + if (currentLineBeginsWithBracket + && (int) currentLineFirstBracketNum == charNum) + shouldBreakLineAtNextChar = true; + } + else + { + if (previousNonWSChar != '(') + { + // don't space pad C++11 uniform initialization + if (!isBracketType(bracketType, INIT_TYPE)) + appendSpacePad(); + } + appendCurrentChar(); + } + } + } + } + else if (bracketFormatMode == BREAK_MODE) + { + if (isWhiteSpace(peekNextChar())) + breakLine(); + else if (isBeforeAnyComment()) + { + // do not break unless comment is at line end + if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) + { + currentChar = ' '; // remove bracket from current line + appendOpeningBracket = true; // append bracket to following line + } + } + if (!isInLineBreak && previousNonWSChar != '(') + { + // don't space pad C++11 uniform initialization + if (!isBracketType(bracketType, INIT_TYPE)) + appendSpacePad(); + } + appendCurrentChar(); + + if (currentLineBeginsWithBracket + && (int) currentLineFirstBracketNum == charNum + && !isBracketType(bracketType, SINGLE_LINE_TYPE)) + shouldBreakLineAtNextChar = true; + } + else if (bracketFormatMode == RUN_IN_MODE) + { + if (isWhiteSpace(peekNextChar())) + breakLine(); + else if (isBeforeAnyComment()) + { + // do not break unless comment is at line end + if (isBeforeAnyLineEndComment(charNum) && !currentLineBeginsWithBracket) + { + currentChar = ' '; // remove bracket from current line + appendOpeningBracket = true; // append bracket to following line + } + } + if (!isInLineBreak && previousNonWSChar != '(') + { + // don't space pad C++11 uniform initialization + if (!isBracketType(bracketType, INIT_TYPE)) + appendSpacePad(); + } + appendCurrentChar(); + } + else if (bracketFormatMode == NONE_MODE) + { + if (currentLineBeginsWithBracket + && charNum == (int) currentLineFirstBracketNum) + { + appendCurrentChar(); // don't attach + } + else + { + if (previousNonWSChar != '(') + { + // don't space pad C++11 uniform initialization + if (!isBracketType(bracketType, INIT_TYPE)) + appendSpacePad(); + } + appendCurrentChar(false); // OK to attach + } + } + } + else // not the first opening bracket + { + if (bracketFormatMode == RUN_IN_MODE) + { + if (previousNonWSChar == '{' + && bracketTypeStack->size() > 2 + && !isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 2], SINGLE_LINE_TYPE)) + formatArrayRunIn(); + } + else if (!isInLineBreak + && !isWhiteSpace(peekNextChar()) + && previousNonWSChar == '{' + && bracketTypeStack->size() > 2 + && !isBracketType((*bracketTypeStack)[bracketTypeStack->size() - 2], SINGLE_LINE_TYPE)) + formatArrayRunIn(); + + appendCurrentChar(); + } + } + else if (currentChar == '}') + { + if (attachClosingBracketMode) + { + if (isEmptyLine(formattedLine) // if a blank line precedes this + || isImmediatelyPostPreprocessor + || isCharImmediatelyPostLineComment + || isCharImmediatelyPostComment) + appendCurrentChar(); // don't attach + else + { + appendSpacePad(); + appendCurrentChar(false); // attach + } + } + else + { + // does this close the first opening bracket in the array? + // must check if the block is still a single line because of anonymous statements + if (!isBracketType(bracketType, INIT_TYPE) + && (!isBracketType(bracketType, SINGLE_LINE_TYPE) + || formattedLine.find('{') == string::npos)) + breakLine(); + appendCurrentChar(); + } + + // if a declaration follows an enum definition, space pad + char peekedChar = peekNextChar(); + if (isLegalNameChar(peekedChar) + || peekedChar == '[') + appendSpaceAfter(); + } +} + +/** + * determine if a run-in can be attached. + * if it can insert the indents in formattedLine and reset the current line break. + */ +void ASFormatter::formatRunIn() +{ + assert(bracketFormatMode == RUN_IN_MODE || bracketFormatMode == NONE_MODE); + + // keep one line blocks returns true without indenting the run-in + if (!isOkToBreakBlock(bracketTypeStack->back())) + return; // true; + + // make sure the line begins with a bracket + size_t lastText = formattedLine.find_last_not_of(" \t"); + if (lastText == string::npos || formattedLine[lastText] != '{') + return; // false; + + // make sure the bracket is broken + if (formattedLine.find_first_not_of(" \t{") != string::npos) + return; // false; + + if (isBracketType(bracketTypeStack->back(), NAMESPACE_TYPE)) + return; // false; + + bool extraIndent = false; + bool extraHalfIndent = false; + isInLineBreak = true; + + // cannot attach a class modifier without indent-classes + if (isCStyle() + && isCharPotentialHeader(currentLine, charNum) + && (isBracketType(bracketTypeStack->back(), CLASS_TYPE) + || (isBracketType(bracketTypeStack->back(), STRUCT_TYPE) + && isInIndentableStruct))) + { + if (findKeyword(currentLine, charNum, AS_PUBLIC) + || findKeyword(currentLine, charNum, AS_PRIVATE) + || findKeyword(currentLine, charNum, AS_PROTECTED)) + { + if (getModifierIndent()) + extraHalfIndent = true; + else if (!getClassIndent()) + return; // false; + } + else if (getClassIndent()) + extraIndent = true; + } + + // cannot attach a 'case' statement without indent-switches + if (!getSwitchIndent() + && isCharPotentialHeader(currentLine, charNum) + && (findKeyword(currentLine, charNum, AS_CASE) + || findKeyword(currentLine, charNum, AS_DEFAULT))) + return; // false; + + // extra indent for switch statements + if (getSwitchIndent() + && !preBracketHeaderStack->empty() + && preBracketHeaderStack->back() == &AS_SWITCH + && ((isLegalNameChar(currentChar) + && !findKeyword(currentLine, charNum, AS_CASE)))) + extraIndent = true; + + isInLineBreak = false; + // remove for extra whitespace + if (formattedLine.length() > lastText + 1 + && formattedLine.find_first_not_of(" \t", lastText + 1) == string::npos) + formattedLine.erase(lastText + 1); + + if (extraHalfIndent) + { + int indentLength_ = getIndentLength(); + horstmannIndentChars = indentLength_ / 2; + formattedLine.append(horstmannIndentChars - 1, ' '); + } + else if (getForceTabIndentation() && getIndentLength() != getTabLength()) + { + // insert the space indents + string indent; + int indentLength_ = getIndentLength(); + int tabLength_ = getTabLength(); + indent.append(indentLength_, ' '); + if (extraIndent) + indent.append(indentLength_, ' '); + // replace spaces indents with tab indents + size_t tabCount = indent.length() / tabLength_; // truncate extra spaces + indent.replace(0U, tabCount * tabLength_, tabCount, '\t'); + horstmannIndentChars = indentLength_; + if (indent[0] == ' ') // allow for bracket + indent.erase(0, 1); + formattedLine.append(indent); + } + else if (getIndentString() == "\t") + { + appendChar('\t', false); + horstmannIndentChars = 2; // one for { and one for tab + if (extraIndent) + { + appendChar('\t', false); + horstmannIndentChars++; + } + } + else // spaces + { + int indentLength_ = getIndentLength(); + formattedLine.append(indentLength_ - 1, ' '); + horstmannIndentChars = indentLength_; + if (extraIndent) + { + formattedLine.append(indentLength_, ' '); + horstmannIndentChars += indentLength_; + } + } + isInHorstmannRunIn = true; +} + +/** + * remove whitespace and add indentation for an array run-in. + */ +void ASFormatter::formatArrayRunIn() +{ + assert(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)); + + // make sure the bracket is broken + if (formattedLine.find_first_not_of(" \t{") != string::npos) + return; + + size_t lastText = formattedLine.find_last_not_of(" \t"); + if (lastText == string::npos || formattedLine[lastText] != '{') + return; + + // check for extra whitespace + if (formattedLine.length() > lastText + 1 + && formattedLine.find_first_not_of(" \t", lastText + 1) == string::npos) + formattedLine.erase(lastText + 1); + + if (getIndentString() == "\t") + { + appendChar('\t', false); + horstmannIndentChars = 2; // one for { and one for tab + } + else + { + int indent = getIndentLength(); + formattedLine.append(indent - 1, ' '); + horstmannIndentChars = indent; + } + isInHorstmannRunIn = true; + isInLineBreak = false; +} + +/** + * delete a bracketTypeStack vector object + * BracketTypeStack did not work with the DeleteContainer template + */ +void ASFormatter::deleteContainer(vector*& container) +{ + if (container != NULL) + { + container->clear(); + delete (container); + container = NULL; + } +} + +/** + * delete a vector object + * T is the type of vector + * used for all vectors except bracketTypeStack + */ +template +void ASFormatter::deleteContainer(T& container) +{ + if (container != NULL) + { + container->clear(); + delete (container); + container = NULL; + } +} + +/** + * initialize a BracketType vector object + * BracketType did not work with the DeleteContainer template + */ +void ASFormatter::initContainer(vector*& container, vector* value) +{ + if (container != NULL) + deleteContainer(container); + container = value; +} + +/** + * initialize a vector object + * T is the type of vector + * used for all vectors except bracketTypeStack + */ +template +void ASFormatter::initContainer(T& container, T value) +{ + // since the ASFormatter object is never deleted, + // the existing vectors must be deleted before creating new ones + if (container != NULL) + deleteContainer(container); + container = value; +} + +/** + * convert a tab to spaces. + * charNum points to the current character to convert to spaces. + * tabIncrementIn is the increment that must be added for tab indent characters + * to get the correct column for the current tab. + * replaces the tab in currentLine with the required number of spaces. + * replaces the value of currentChar. + */ +void ASFormatter::convertTabToSpaces() +{ + assert(currentChar == '\t'); + + // do NOT replace if in quotes + if (isInQuote || isInQuoteContinuation) + return; + + size_t tabSize = getTabLength(); + size_t numSpaces = tabSize - ((tabIncrementIn + charNum) % tabSize); + currentLine.replace(charNum, 1, numSpaces, ' '); + currentChar = currentLine[charNum]; +} + +/** +* is it ok to break this block? +*/ +bool ASFormatter::isOkToBreakBlock(BracketType bracketType) const +{ + // Actually, there should not be an ARRAY_TYPE bracket here. + // But this will avoid breaking a one line block when there is. + // Otherwise they will be formatted differently on consecutive runs. + if (isBracketType(bracketType, ARRAY_TYPE) + && isBracketType(bracketType, SINGLE_LINE_TYPE)) + return false; + if (!isBracketType(bracketType, SINGLE_LINE_TYPE) + || shouldBreakOneLineBlocks + || breakCurrentOneLineBlock) + return true; + return false; +} + +/** +* check if a sharp header is a paren or non-paren header +*/ +bool ASFormatter::isSharpStyleWithParen(const string* header) const +{ + if (isSharpStyle() && peekNextChar() == '(' + && (header == &AS_CATCH + || header == &AS_DELEGATE)) + return true; + return false; +} + +/** + * Check for a following header when a comment is reached. + * firstLine must contain the start of the comment. + * return value is a pointer to the header or NULL. + */ +const string* ASFormatter::checkForHeaderFollowingComment(const string& firstLine) const +{ + assert(isInComment || isInLineComment); + assert(shouldBreakElseIfs || shouldBreakBlocks || isInSwitchStatement()); + // look ahead to find the next non-comment text + bool endOnEmptyLine = (currentHeader == NULL); + if (isInSwitchStatement()) + endOnEmptyLine = false; + string nextText = peekNextText(firstLine, endOnEmptyLine); + + if (nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) + return NULL; + + return ASBeautifier::findHeader(nextText, 0, headers); +} + +/** + * process preprocessor statements. + * charNum should be the index of the #. + * + * delete bracketTypeStack entries added by #if if a #else is found. + * prevents double entries in the bracketTypeStack. + */ +void ASFormatter::processPreprocessor() +{ + assert(currentChar == '#'); + + const size_t preproc = currentLine.find_first_not_of(" \t", charNum + 1); + + if (preproc == string::npos) + return; + + if (currentLine.compare(preproc, 2, "if") == 0) + { + preprocBracketTypeStackSize = bracketTypeStack->size(); + } + else if (currentLine.compare(preproc, 4, "else") == 0) + { + // delete stack entries added in #if + // should be replaced by #else + if (preprocBracketTypeStackSize > 0) + { + int addedPreproc = bracketTypeStack->size() - preprocBracketTypeStackSize; + for (int i = 0; i < addedPreproc; i++) + bracketTypeStack->pop_back(); + } + } +} + +/** + * determine if the next line starts a comment + * and a header follows the comment or comments. + */ +bool ASFormatter::commentAndHeaderFollows() +{ + // called ONLY IF shouldDeleteEmptyLines and shouldBreakBlocks are TRUE. + assert(shouldDeleteEmptyLines && shouldBreakBlocks); + + // is the next line a comment + if (!sourceIterator->hasMoreLines()) + return false; + string nextLine_ = sourceIterator->peekNextLine(); + size_t firstChar = nextLine_.find_first_not_of(" \t"); + if (firstChar == string::npos + || !(nextLine_.compare(firstChar, 2, "//") == 0 + || nextLine_.compare(firstChar, 2, "/*") == 0)) + { + sourceIterator->peekReset(); + return false; + } + + // find the next non-comment text, and reset + string nextText = peekNextText(nextLine_, false, true); + if (nextText.length() == 0 || !isCharPotentialHeader(nextText, 0)) + return false; + + const string* newHeader = ASBeautifier::findHeader(nextText, 0, headers); + + if (newHeader == NULL) + return false; + + // if a closing header, reset break unless break is requested + if (isClosingHeader(newHeader) && !shouldBreakClosingHeaderBlocks) + { + isAppendPostBlockEmptyLineRequested = false; + return false; + } + + return true; +} + +/** + * determine if a bracket should be attached or broken + * uses brackets in the bracketTypeStack + * the last bracket in the bracketTypeStack is the one being formatted + * returns true if the bracket should be broken + */ +bool ASFormatter::isCurrentBracketBroken() const +{ + assert(bracketTypeStack->size() > 1); + + bool breakBracket = false; + size_t stackEnd = bracketTypeStack->size() - 1; + + // check bracket modifiers + if (shouldAttachExternC + && isBracketType((*bracketTypeStack)[stackEnd], EXTERN_TYPE)) + { + return false; + } + if (shouldAttachNamespace + && isBracketType((*bracketTypeStack)[stackEnd], NAMESPACE_TYPE)) + { + return false; + } + else if (shouldAttachClass + && (isBracketType((*bracketTypeStack)[stackEnd], CLASS_TYPE) + || isBracketType((*bracketTypeStack)[stackEnd], INTERFACE_TYPE))) + { + return false; + } + else if (shouldAttachInline + && isCStyle() // for C++ only + && bracketFormatMode != RUN_IN_MODE + && isBracketType((*bracketTypeStack)[stackEnd], COMMAND_TYPE)) + { + size_t i; + for (i = 1; i < bracketTypeStack->size(); i++) + if (isBracketType((*bracketTypeStack)[i], CLASS_TYPE) + || isBracketType((*bracketTypeStack)[i], STRUCT_TYPE)) + return false; + } + + // check brackets + if (isBracketType((*bracketTypeStack)[stackEnd], EXTERN_TYPE)) + { + if (currentLineBeginsWithBracket + || bracketFormatMode == RUN_IN_MODE) + breakBracket = true; + } + else if (bracketFormatMode == NONE_MODE) + { + if (currentLineBeginsWithBracket + && (int) currentLineFirstBracketNum == charNum) + breakBracket = true; + } + else if (bracketFormatMode == BREAK_MODE || bracketFormatMode == RUN_IN_MODE) + { + breakBracket = true; + } + else if (bracketFormatMode == LINUX_MODE || bracketFormatMode == STROUSTRUP_MODE) + { + // break a namespace, class, or interface if Linux + if (isBracketType((*bracketTypeStack)[stackEnd], NAMESPACE_TYPE) + || isBracketType((*bracketTypeStack)[stackEnd], CLASS_TYPE) + || isBracketType((*bracketTypeStack)[stackEnd], INTERFACE_TYPE)) + { + if (bracketFormatMode == LINUX_MODE) + breakBracket = true; + } + // break the first bracket if a function + else if (isBracketType((*bracketTypeStack)[stackEnd], COMMAND_TYPE)) + { + if (stackEnd == 1) + { + breakBracket = true; + } + else if (stackEnd > 1) + { + // break the first bracket after these if a function + if (isBracketType((*bracketTypeStack)[stackEnd - 1], NAMESPACE_TYPE) + || isBracketType((*bracketTypeStack)[stackEnd - 1], CLASS_TYPE) + || isBracketType((*bracketTypeStack)[stackEnd - 1], ARRAY_TYPE) + || isBracketType((*bracketTypeStack)[stackEnd - 1], STRUCT_TYPE) + || isBracketType((*bracketTypeStack)[stackEnd - 1], EXTERN_TYPE)) + { + breakBracket = true; + } + } + } + } + return breakBracket; +} + +/** + * format comment body + * the calling function should have a continue statement after calling this method + */ +void ASFormatter::formatCommentBody() +{ + assert(isInComment); + + // append the comment + while (charNum < (int) currentLine.length()) + { + currentChar = currentLine[charNum]; + if (currentLine.compare(charNum, 2, "*/") == 0) + { + formatCommentCloser(); + break; + } + if (currentChar == '\t' && shouldConvertTabs) + convertTabToSpaces(); + appendCurrentChar(); + ++charNum; + } + if (shouldStripCommentPrefix) + stripCommentPrefix(); +} + +/** + * format a comment opener + * the comment opener will be appended to the current formattedLine or a new formattedLine as necessary + * the calling function should have a continue statement after calling this method + */ +void ASFormatter::formatCommentOpener() +{ + assert(isSequenceReached("/*")); + + isInComment = isInCommentStartLine = true; + isImmediatelyPostLineComment = false; + if (previousNonWSChar == '}') + resetEndOfStatement(); + + // Check for a following header. + // For speed do not check multiple comment lines more than once. + // For speed do not check shouldBreakBlocks if previous line is empty, a comment, or a '{'. + const string* followingHeader = NULL; + if ((doesLineStartComment + && !isImmediatelyPostCommentOnly + && isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + && (shouldBreakElseIfs + || isInSwitchStatement() + || (shouldBreakBlocks + && !isImmediatelyPostEmptyLine + && previousCommandChar != '{'))) + followingHeader = checkForHeaderFollowingComment(currentLine.substr(charNum)); + + if (spacePadNum != 0 && !isInLineBreak) + adjustComments(); + formattedLineCommentNum = formattedLine.length(); + + // must be done BEFORE appendSequence + if (previousCommandChar == '{' + && !isImmediatelyPostComment + && !isImmediatelyPostLineComment) + { + if (bracketFormatMode == NONE_MODE) + { + // should a run-in statement be attached? + if (currentLineBeginsWithBracket) + formatRunIn(); + } + else if (bracketFormatMode == ATTACH_MODE) + { + // if the bracket was not attached? + if (formattedLine.length() > 0 && formattedLine[0] == '{' + && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE)) + isInLineBreak = true; + } + else if (bracketFormatMode == RUN_IN_MODE) + { + // should a run-in statement be attached? + if (formattedLine.length() > 0 && formattedLine[0] == '{') + formatRunIn(); + } + } + else if (!doesLineStartComment) + noTrimCommentContinuation = true; + + // ASBeautifier needs to know the following statements + if (shouldBreakElseIfs && followingHeader == &AS_ELSE) + elseHeaderFollowsComments = true; + if (followingHeader == &AS_CASE || followingHeader == &AS_DEFAULT) + caseHeaderFollowsComments = true; + + // appendSequence will write the previous line + appendSequence(AS_OPEN_COMMENT); + goForward(1); + + // must be done AFTER appendSequence + + // Break before the comment if a header follows the line comment. + // But not break if previous line is empty, a comment, or a '{'. + if (shouldBreakBlocks + && followingHeader != NULL + && !isImmediatelyPostEmptyLine + && previousCommandChar != '{') + { + if (isClosingHeader(followingHeader)) + { + if (!shouldBreakClosingHeaderBlocks) + isPrependPostBlockEmptyLineRequested = false; + } + // if an opening header, break before the comment + else + isPrependPostBlockEmptyLineRequested = true; + } + + if (previousCommandChar == '}') + currentHeader = NULL; +} + +/** + * format a comment closer + * the comment closer will be appended to the current formattedLine + */ +void ASFormatter::formatCommentCloser() +{ + isInComment = false; + noTrimCommentContinuation = false; + isImmediatelyPostComment = true; + appendSequence(AS_CLOSE_COMMENT); + goForward(1); + if (doesLineStartComment + && (currentLine.find_first_not_of(" \t", charNum + 1) == string::npos)) + lineEndsInCommentOnly = true; + if (peekNextChar() == '}' + && previousCommandChar != ';' + && !isBracketType(bracketTypeStack->back(), ARRAY_TYPE) + && !isInPreprocessor + && isOkToBreakBlock(bracketTypeStack->back())) + { + isInLineBreak = true; + shouldBreakLineAtNextChar = true; + } +} + +/** + * format a line comment body + * the calling function should have a continue statement after calling this method + */ +void ASFormatter::formatLineCommentBody() +{ + assert(isInLineComment); + + // append the comment + while (charNum < (int) currentLine.length()) +// && !isLineReady // commented out in release 2.04, unnecessary + { + currentChar = currentLine[charNum]; + if (currentChar == '\t' && shouldConvertTabs) + convertTabToSpaces(); + appendCurrentChar(); + ++charNum; + } + + // explicitly break a line when a line comment's end is found. + if (charNum == (int) currentLine.length()) + { + isInLineBreak = true; + isInLineComment = false; + isImmediatelyPostLineComment = true; + currentChar = 0; //make sure it is a neutral char. + } +} + +/** + * format a line comment opener + * the line comment opener will be appended to the current formattedLine or a new formattedLine as necessary + * the calling function should have a continue statement after calling this method + */ +void ASFormatter::formatLineCommentOpener() +{ + assert(isSequenceReached("//")); + + if ((int) currentLine.length() > charNum + 2 + && currentLine[charNum + 2] == '\xf2') // check for windows line marker + isAppendPostBlockEmptyLineRequested = false; + + isInLineComment = true; + isCharImmediatelyPostComment = false; + if (previousNonWSChar == '}') + resetEndOfStatement(); + + // Check for a following header. + // For speed do not check multiple comment lines more than once. + // For speed do not check shouldBreakBlocks if previous line is empty, a comment, or a '{'. + const string* followingHeader = NULL; + if ((lineIsLineCommentOnly + && !isImmediatelyPostCommentOnly + && isBracketType(bracketTypeStack->back(), COMMAND_TYPE)) + && (shouldBreakElseIfs + || isInSwitchStatement() + || (shouldBreakBlocks + && !isImmediatelyPostEmptyLine + && previousCommandChar != '{'))) + followingHeader = checkForHeaderFollowingComment(currentLine.substr(charNum)); + + // do not indent if in column 1 or 2 + // or in a namespace before the opening bracket + if ((!shouldIndentCol1Comments && !lineCommentNoIndent) + || foundNamespaceHeader) + { + if (charNum == 0) + lineCommentNoIndent = true; + else if (charNum == 1 && currentLine[0] == ' ') + lineCommentNoIndent = true; + } + // move comment if spaces were added or deleted + if (lineCommentNoIndent == false && spacePadNum != 0 && !isInLineBreak) + adjustComments(); + formattedLineCommentNum = formattedLine.length(); + + // must be done BEFORE appendSequence + // check for run-in statement + if (previousCommandChar == '{' + && !isImmediatelyPostComment + && !isImmediatelyPostLineComment) + { + if (bracketFormatMode == NONE_MODE) + { + if (currentLineBeginsWithBracket) + formatRunIn(); + } + else if (bracketFormatMode == RUN_IN_MODE) + { + if (!lineCommentNoIndent) + formatRunIn(); + else + isInLineBreak = true; + } + else if (bracketFormatMode == BREAK_MODE) + { + if (formattedLine.length() > 0 && formattedLine[0] == '{') + isInLineBreak = true; + } + else + { + if (currentLineBeginsWithBracket) + isInLineBreak = true; + } + } + + // ASBeautifier needs to know the following statements + if (shouldBreakElseIfs && followingHeader == &AS_ELSE) + elseHeaderFollowsComments = true; + if (followingHeader == &AS_CASE || followingHeader == &AS_DEFAULT) + caseHeaderFollowsComments = true; + + // appendSequence will write the previous line + appendSequence(AS_OPEN_LINE_COMMENT); + goForward(1); + + // must be done AFTER appendSequence + + // Break before the comment if a header follows the line comment. + // But do not break if previous line is empty, a comment, or a '{'. + if (shouldBreakBlocks + && followingHeader != NULL + && !isImmediatelyPostEmptyLine + && previousCommandChar != '{') + { + if (isClosingHeader(followingHeader)) + { + if (!shouldBreakClosingHeaderBlocks) + isPrependPostBlockEmptyLineRequested = false; + } + // if an opening header, break before the comment + else + isPrependPostBlockEmptyLineRequested = true; + } + + if (previousCommandChar == '}') + currentHeader = NULL; + + // if tabbed input don't convert the immediately following tabs to spaces + if (getIndentString() == "\t" && lineCommentNoIndent) + { + while (charNum + 1 < (int) currentLine.length() + && currentLine[charNum + 1] == '\t') + { + currentChar = currentLine[++charNum]; + appendCurrentChar(); + } + } + + // explicitly break a line when a line comment's end is found. + if (charNum + 1 == (int) currentLine.length()) + { + isInLineBreak = true; + isInLineComment = false; + isImmediatelyPostLineComment = true; + currentChar = 0; //make sure it is a neutral char. + } +} + +/** + * format quote body + * the calling function should have a continue statement after calling this method + */ +void ASFormatter::formatQuoteBody() +{ + assert(isInQuote); + + if (isSpecialChar) + { + isSpecialChar = false; + } + else if (currentChar == '\\' && !isInVerbatimQuote) + { + if (peekNextChar() == ' ') // is this '\' at end of line + haveLineContinuationChar = true; + else + isSpecialChar = true; + } + else if (isInVerbatimQuote && currentChar == '"') + { + if (isCStyle()) + { + string delim = ')' + verbatimDelimiter; + int delimStart = charNum - delim.length(); + if (delimStart > 0 && currentLine.substr(delimStart, delim.length()) == delim) + { + isInQuote = false; + isInVerbatimQuote = false; + } + } + else if (isSharpStyle()) + { + if (peekNextChar() == '"') // check consecutive quotes + { + appendSequence("\"\""); + goForward(1); + return; + } + else + { + isInQuote = false; + isInVerbatimQuote = false; + } + } + } + else if (quoteChar == currentChar) + { + isInQuote = false; + } + + appendCurrentChar(); + + // append the text to the ending quoteChar or an escape sequence + // tabs in quotes are NOT changed by convert-tabs + if (isInQuote && currentChar != '\\') + { + while (charNum + 1 < (int) currentLine.length() + && currentLine[charNum + 1] != quoteChar + && currentLine[charNum + 1] != '\\') + { + currentChar = currentLine[++charNum]; + appendCurrentChar(); + } + } +} + +/** + * format a quote opener + * the quote opener will be appended to the current formattedLine or a new formattedLine as necessary + * the calling function should have a continue statement after calling this method + */ +void ASFormatter::formatQuoteOpener() +{ + assert(currentChar == '"' + || (currentChar == '\'' && !isDigitSeparator(currentLine, charNum))); + + isInQuote = true; + quoteChar = currentChar; + if (isCStyle() && previousChar == 'R') + { + int parenPos = currentLine.find('(', charNum); + if (parenPos != -1) + { + isInVerbatimQuote = true; + verbatimDelimiter = currentLine.substr(charNum + 1, parenPos - charNum - 1); + } + } + else if (isSharpStyle() && previousChar == '@') + isInVerbatimQuote = true; + + // a quote following a bracket is an array + if (previousCommandChar == '{' + && !isImmediatelyPostComment + && !isImmediatelyPostLineComment + && isNonInStatementArray + && !isBracketType(bracketTypeStack->back(), SINGLE_LINE_TYPE) + && !isWhiteSpace(peekNextChar())) + { + if (bracketFormatMode == NONE_MODE) + { + if (currentLineBeginsWithBracket) + formatRunIn(); + } + else if (bracketFormatMode == RUN_IN_MODE) + { + formatRunIn(); + } + else if (bracketFormatMode == BREAK_MODE) + { + if (formattedLine.length() > 0 && formattedLine[0] == '{') + isInLineBreak = true; + } + else + { + if (currentLineBeginsWithBracket) + isInLineBreak = true; + } + } + previousCommandChar = ' '; + appendCurrentChar(); +} + +/** + * get the next line comment adjustment that results from breaking a closing bracket. + * the bracket must be on the same line as the closing header. + * i.e "} else" changed to "} else". + */ +int ASFormatter::getNextLineCommentAdjustment() +{ + assert(foundClosingHeader && previousNonWSChar == '}'); + if (charNum < 1) // "else" is in column 1 + return 0; + size_t lastBracket = currentLine.rfind('}', charNum - 1); + if (lastBracket != string::npos) + return (lastBracket - charNum); // return a negative number + return 0; +} + +// for console build only +LineEndFormat ASFormatter::getLineEndFormat() const +{ + return lineEnd; +} + +/** + * get the current line comment adjustment that results from attaching + * a closing header to a closing bracket. + * the bracket must be on the line previous to the closing header. + * the adjustment is 2 chars, one for the bracket and one for the space. + * i.e "} else" changed to "} else". + */ +int ASFormatter::getCurrentLineCommentAdjustment() +{ + assert(foundClosingHeader && previousNonWSChar == '}'); + if (charNum < 1) + return 2; + size_t lastBracket = currentLine.rfind('}', charNum - 1); + if (lastBracket == string::npos) + return 2; + return 0; +} + +/** + * get the previous word on a line + * the argument 'currPos' must point to the current position. + * + * @return is the previous word or an empty string if none found. + */ +string ASFormatter::getPreviousWord(const string& line, int currPos) const +{ + // get the last legal word (may be a number) + if (currPos == 0) + return string(); + + size_t end = line.find_last_not_of(" \t", currPos - 1); + if (end == string::npos || !isLegalNameChar(line[end])) + return string(); + + int start; // start of the previous word + for (start = end; start > -1; start--) + { + if (!isLegalNameChar(line[start]) || line[start] == '.') + break; + } + start++; + + return (line.substr(start, end - start + 1)); +} + +/** + * check if a line break is needed when a closing bracket + * is followed by a closing header. + * the break depends on the bracketFormatMode and other factors. + */ +void ASFormatter::isLineBreakBeforeClosingHeader() +{ + assert(foundClosingHeader && previousNonWSChar == '}'); + if (bracketFormatMode == BREAK_MODE + || bracketFormatMode == RUN_IN_MODE + || attachClosingBracketMode) + { + isInLineBreak = true; + } + else if (bracketFormatMode == NONE_MODE) + { + if (shouldBreakClosingHeaderBrackets + || getBracketIndent() || getBlockIndent()) + { + isInLineBreak = true; + } + else + { + appendSpacePad(); + // is closing bracket broken? + size_t i = currentLine.find_first_not_of(" \t"); + if (i != string::npos && currentLine[i] == '}') + isInLineBreak = false; + + if (shouldBreakBlocks) + isAppendPostBlockEmptyLineRequested = false; + } + } + // bracketFormatMode == ATTACH_MODE, LINUX_MODE, STROUSTRUP_MODE + else + { + if (shouldBreakClosingHeaderBrackets + || getBracketIndent() || getBlockIndent()) + { + isInLineBreak = true; + } + else + { + // if a blank line does not precede this + // or last line is not a one line block, attach header + bool previousLineIsEmpty = isEmptyLine(formattedLine); + int previousLineIsOneLineBlock = 0; + size_t firstBracket = findNextChar(formattedLine, '{'); + if (firstBracket != string::npos) + previousLineIsOneLineBlock = isOneLineBlockReached(formattedLine, firstBracket); + if (!previousLineIsEmpty + && previousLineIsOneLineBlock == 0) + { + isInLineBreak = false; + appendSpacePad(); + spacePadNum = 0; // don't count as comment padding + } + + if (shouldBreakBlocks) + isAppendPostBlockEmptyLineRequested = false; + } + } +} + +/** + * Add brackets to a single line statement following a header. + * Brackets are not added if the proper conditions are not met. + * Brackets are added to the currentLine. + */ +bool ASFormatter::addBracketsToStatement() +{ + assert(isImmediatelyPostHeader); + + if (currentHeader != &AS_IF + && currentHeader != &AS_ELSE + && currentHeader != &AS_FOR + && currentHeader != &AS_WHILE + && currentHeader != &AS_DO + && currentHeader != &AS_FOREACH + && currentHeader != &AS_QFOREACH + && currentHeader != &AS_QFOREVER + && currentHeader != &AS_FOREVER) + return false; + + if (currentHeader == &AS_WHILE && foundClosingHeader) // do-while + return false; + + // do not bracket an empty statement + if (currentChar == ';') + return false; + + // do not add if a header follows + if (isCharPotentialHeader(currentLine, charNum)) + if (findHeader(headers) != NULL) + return false; + + // find the next semi-colon + size_t nextSemiColon = charNum; + if (currentChar != ';') + nextSemiColon = findNextChar(currentLine, ';', charNum + 1); + if (nextSemiColon == string::npos) + return false; + + // add closing bracket before changing the line length + if (nextSemiColon == currentLine.length() - 1) + currentLine.append(" }"); + else + currentLine.insert(nextSemiColon + 1, " }"); + // add opening bracket + currentLine.insert(charNum, "{ "); + assert(computeChecksumIn("{}")); + currentChar = '{'; + // remove extra spaces + if (!shouldAddOneLineBrackets) + { + size_t lastText = formattedLine.find_last_not_of(" \t"); + if ((formattedLine.length() - 1) - lastText > 1) + formattedLine.erase(lastText + 1); + } + return true; +} + +/** + * Remove brackets from a single line statement following a header. + * Brackets are not removed if the proper conditions are not met. + * The first bracket is replaced by a space. + */ +bool ASFormatter::removeBracketsFromStatement() +{ + assert(isImmediatelyPostHeader); + assert(currentChar == '{'); + + if (currentHeader != &AS_IF + && currentHeader != &AS_ELSE + && currentHeader != &AS_FOR + && currentHeader != &AS_WHILE + && currentHeader != &AS_FOREACH) + return false; + + if (currentHeader == &AS_WHILE && foundClosingHeader) // do-while + return false; + + bool isFirstLine = true; + bool needReset = false; + string nextLine_; + // leave nextLine_ empty if end of line comment follows + if (!isBeforeAnyLineEndComment(charNum) || currentLineBeginsWithBracket) + nextLine_ = currentLine.substr(charNum + 1); + size_t nextChar = 0; + + // find the first non-blank text + while (sourceIterator->hasMoreLines() || isFirstLine) + { + if (isFirstLine) + isFirstLine = false; + else + { + nextLine_ = sourceIterator->peekNextLine(); + nextChar = 0; + needReset = true; + } + + nextChar = nextLine_.find_first_not_of(" \t", nextChar); + if (nextChar != string::npos) + break; + } + + // don't remove if comments or a header follow the bracket + if ((nextLine_.compare(nextChar, 2, "/*") == 0) + || (nextLine_.compare(nextChar, 2, "//") == 0) + || (isCharPotentialHeader(nextLine_, nextChar) + && ASBeautifier::findHeader(nextLine_, nextChar, headers) != NULL)) + { + if (needReset) + sourceIterator->peekReset(); + return false; + } + + // find the next semi-colon + size_t nextSemiColon = nextChar; + if (nextLine_[nextChar] != ';') + nextSemiColon = findNextChar(nextLine_, ';', nextChar + 1); + if (nextSemiColon == string::npos) + { + if (needReset) + sourceIterator->peekReset(); + return false; + } + + // find the closing bracket + isFirstLine = true; + nextChar = nextSemiColon + 1; + while (sourceIterator->hasMoreLines() || isFirstLine) + { + if (isFirstLine) + isFirstLine = false; + else + { + nextLine_ = sourceIterator->peekNextLine(); + nextChar = 0; + needReset = true; + } + nextChar = nextLine_.find_first_not_of(" \t", nextChar); + if (nextChar != string::npos) + break; + } + if (nextLine_.length() == 0 || nextLine_[nextChar] != '}') + { + if (needReset) + sourceIterator->peekReset(); + return false; + } + + // remove opening bracket + currentLine[charNum] = currentChar = ' '; + assert(adjustChecksumIn(-'{')); + if (needReset) + sourceIterator->peekReset(); + return true; +} + +/** + * Find the next character that is not in quotes or a comment. + * + * @param line the line to be searched. + * @param searchChar the char to find. + * @param searchStart the start position on the line (default is 0). + * @return the position on the line or string::npos if not found. + */ +size_t ASFormatter::findNextChar(string& line, char searchChar, int searchStart /*0*/) const +{ + // find the next searchChar + size_t i; + for (i = searchStart; i < line.length(); i++) + { + if (line.compare(i, 2, "//") == 0) + return string::npos; + if (line.compare(i, 2, "/*") == 0) + { + size_t endComment = line.find("*/", i + 2); + if (endComment == string::npos) + return string::npos; + i = endComment + 2; + if (i >= line.length()) + return string::npos; + } + if (line[i] == '"' + || (line[i] == '\'' && !isDigitSeparator(line, i))) + { + char quote = line[i]; + while (i < line.length()) + { + size_t endQuote = line.find(quote, i + 1); + if (endQuote == string::npos) + return string::npos; + i = endQuote; + if (line[endQuote - 1] != '\\') // check for '\"' + break; + if (line[endQuote - 2] == '\\') // check for '\\' + break; + } + } + + if (line[i] == searchChar) + break; + + // for now don't process C# 'delegate' brackets + // do this last in case the search char is a '{' + if (line[i] == '{') + return string::npos; + } + if (i >= line.length()) // didn't find searchChar + return string::npos; + + return i; +} + +/** + * Look ahead in the file to see if a struct has access modifiers. + * + * @param firstLine a reference to the line to indent. + * @param index the current line index. + * @return true if the struct has access modifiers. + */ +bool ASFormatter::isStructAccessModified(string& firstLine, size_t index) const +{ + assert(firstLine[index] == '{'); + assert(isCStyle()); + + bool isFirstLine = true; + bool needReset = false; + size_t bracketCount = 1; + string nextLine_ = firstLine.substr(index + 1); + + // find the first non-blank text, bypassing all comments and quotes. + bool isInComment_ = false; + bool isInQuote_ = false; + char quoteChar_ = ' '; + while (sourceIterator->hasMoreLines() || isFirstLine) + { + if (isFirstLine) + isFirstLine = false; + else + { + nextLine_ = sourceIterator->peekNextLine(); + needReset = true; + } + // parse the line + for (size_t i = 0; i < nextLine_.length(); i++) + { + if (isWhiteSpace(nextLine_[i])) + continue; + if (nextLine_.compare(i, 2, "/*") == 0) + isInComment_ = true; + if (isInComment_) + { + if (nextLine_.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + if (nextLine_[i] == '\\') + { + ++i; + continue; + } + + if (isInQuote_) + { + if (nextLine_[i] == quoteChar_) + isInQuote_ = false; + continue; + } + + if (nextLine_[i] == '"' + || (nextLine_[i] == '\'' && !isDigitSeparator(nextLine_, i))) + { + isInQuote_ = true; + quoteChar_ = nextLine_[i]; + continue; + } + if (nextLine_.compare(i, 2, "//") == 0) + { + i = nextLine_.length(); + continue; + } + // handle brackets + if (nextLine_[i] == '{') + ++bracketCount; + if (nextLine_[i] == '}') + --bracketCount; + if (bracketCount == 0) + { + if (needReset) + sourceIterator->peekReset(); + return false; + } + // check for access modifiers + if (isCharPotentialHeader(nextLine_, i)) + { + if (findKeyword(nextLine_, i, AS_PUBLIC) + || findKeyword(nextLine_, i, AS_PRIVATE) + || findKeyword(nextLine_, i, AS_PROTECTED)) + { + if (needReset) + sourceIterator->peekReset(); + return true; + } + string name = getCurrentWord(nextLine_, i); + i += name.length() - 1; + } + } // end of for loop + } // end of while loop + + if (needReset) + sourceIterator->peekReset(); + return false; +} + +/** +* Look ahead in the file to see if a preprocessor block is indentable. +* +* @param firstLine a reference to the line to indent. +* @param index the current line index. +* @return true if the block is indentable. +*/ +bool ASFormatter::isIndentablePreprocessorBlock(string& firstLine, size_t index) +{ + assert(firstLine[index] == '#'); + + bool isFirstLine = true; + bool needReset = false; + bool isInIndentableBlock = false; + bool blockContainsBrackets = false; + bool blockContainsDefineContinuation = false; + bool isInClassConstructor = false; + int numBlockIndents = 0; + int lineParenCount = 0; + string nextLine_ = firstLine.substr(index); + + // find end of the block, bypassing all comments and quotes. + bool isInComment_ = false; + bool isInQuote_ = false; + char quoteChar_ = ' '; + while (sourceIterator->hasMoreLines() || isFirstLine) + { + if (isFirstLine) + isFirstLine = false; + else + { + nextLine_ = sourceIterator->peekNextLine(); + needReset = true; + } + // parse the line + for (size_t i = 0; i < nextLine_.length(); i++) + { + if (isWhiteSpace(nextLine_[i])) + continue; + if (nextLine_.compare(i, 2, "/*") == 0) + isInComment_ = true; + if (isInComment_) + { + if (nextLine_.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + if (nextLine_[i] == '\\') + { + ++i; + continue; + } + if (isInQuote_) + { + if (nextLine_[i] == quoteChar_) + isInQuote_ = false; + continue; + } + + if (nextLine_[i] == '"' + || (nextLine_[i] == '\'' && !isDigitSeparator(nextLine_, i))) + { + isInQuote_ = true; + quoteChar_ = nextLine_[i]; + continue; + } + if (nextLine_.compare(i, 2, "//") == 0) + { + i = nextLine_.length(); + continue; + } + // handle preprocessor statement + if (nextLine_[i] == '#') + { + string preproc = ASBeautifier::extractPreprocessorStatement(nextLine_); + if (preproc.length() >= 2 && preproc.substr(0, 2) == "if") // #if, #ifdef, #ifndef + { + numBlockIndents += 1; + isInIndentableBlock = true; + // flag first preprocessor conditional for header include guard check + if (!processedFirstConditional) + { + processedFirstConditional = true; + isFirstPreprocConditional = true; + } + } + else if (preproc == "endif" || preproc == "end") + { + if (numBlockIndents > 0) + numBlockIndents -= 1; + // must exit BOTH loops + if (numBlockIndents == 0) + goto EndOfWhileLoop; + } + else if (preproc == "define" && nextLine_[nextLine_.length() - 1] == '\\') + { + blockContainsDefineContinuation = true; + } + i = nextLine_.length(); + continue; + } + // handle exceptions + if (nextLine_[i] == '{' || nextLine_[i] == '}') + blockContainsBrackets = true; + else if (nextLine_[i] == '(') + ++lineParenCount; + else if (nextLine_[i] == ')') + --lineParenCount; + else if (nextLine_[i] == ':') + { + // check for '::' + if (nextLine_.length() > i && nextLine_[i + 1] == ':') + ++i; + else + isInClassConstructor = true; + } + // bypass unnecessary parsing - must exit BOTH loops + if (blockContainsBrackets || isInClassConstructor || blockContainsDefineContinuation) + goto EndOfWhileLoop; + } // end of for loop, end of line + if (lineParenCount != 0) + break; + } // end of while loop +EndOfWhileLoop: + preprocBlockEnd = sourceIterator->tellg(); + if (preprocBlockEnd < 0) + preprocBlockEnd = sourceIterator->getStreamLength(); + if (blockContainsBrackets + || isInClassConstructor + || blockContainsDefineContinuation + || lineParenCount != 0 + || numBlockIndents != 0) + isInIndentableBlock = false; + // find next executable instruction + // this WILL RESET the get pointer + string nextText = peekNextText("", false, needReset); + // bypass header include guards, with an exception for small test files + if (isFirstPreprocConditional) + { + isFirstPreprocConditional = false; + if (nextText.empty() && sourceIterator->getStreamLength() > 250) + { + isInIndentableBlock = false; + preprocBlockEnd = 0; + } + } + // this allows preprocessor blocks within this block to be indented + if (!isInIndentableBlock) + preprocBlockEnd = 0; + // peekReset() is done by previous peekNextText() + return isInIndentableBlock; +} + +/** + * Check to see if this is an EXEC SQL statement. + * + * @param line a reference to the line to indent. + * @param index the current line index. + * @return true if the statement is EXEC SQL. + */ +bool ASFormatter::isExecSQL(string& line, size_t index) const +{ + if (line[index] != 'e' && line[index] != 'E') // quick check to reject most + return false; + string word; + if (isCharPotentialHeader(line, index)) + word = getCurrentWord(line, index); + for (size_t i = 0; i < word.length(); i++) + word[i] = (char) toupper(word[i]); + if (word != "EXEC") + return false; + size_t index2 = index + word.length(); + index2 = line.find_first_not_of(" \t", index2); + if (index2 == string::npos) + return false; + word.erase(); + if (isCharPotentialHeader(line, index2)) + word = getCurrentWord(line, index2); + for (size_t i = 0; i < word.length(); i++) + word[i] = (char) toupper(word[i]); + if (word != "SQL") + return false; + return true; +} + +/** + * The continuation lines must be adjusted so the leading spaces + * is equivalent to the text on the opening line. + * + * Updates currentLine and charNum. + */ +void ASFormatter::trimContinuationLine() +{ + size_t len = currentLine.length(); + size_t tabSize = getTabLength(); + charNum = 0; + + if (leadingSpaces > 0 && len > 0) + { + size_t i; + size_t continuationIncrementIn = 0; + for (i = 0; (i < len) && (i + continuationIncrementIn < leadingSpaces); i++) + { + if (!isWhiteSpace(currentLine[i])) // don't delete any text + { + if (i < continuationIncrementIn) + leadingSpaces = i + tabIncrementIn; + continuationIncrementIn = tabIncrementIn; + break; + } + if (currentLine[i] == '\t') + continuationIncrementIn += tabSize - 1 - ((continuationIncrementIn + i) % tabSize); + } + + if ((int) continuationIncrementIn == tabIncrementIn) + charNum = i; + else + { + // build a new line with the equivalent leading chars + string newLine; + int leadingChars = 0; + if ((int) leadingSpaces > tabIncrementIn) + leadingChars = leadingSpaces - tabIncrementIn; + newLine.append(leadingChars, ' '); + newLine.append(currentLine, i, len - i); + currentLine = newLine; + charNum = leadingChars; + if (currentLine.length() == 0) + currentLine = string(" "); // a null is inserted if this is not done + } + if (i >= len) + charNum = 0; + } + return; +} + +/** + * Determine if a header is a closing header + * + * @return true if the header is a closing header. + */ +bool ASFormatter::isClosingHeader(const string* header) const +{ + return (header == &AS_ELSE + || header == &AS_CATCH + || header == &AS_FINALLY); +} + +/** + * Determine if a * following a closing paren is immediately. + * after a cast. If so it is a deference and not a multiply. + * e.g. "(int*) *ptr" is a deference. + */ +bool ASFormatter::isImmediatelyPostCast() const +{ + assert(previousNonWSChar == ')' && currentChar == '*'); + // find preceding closing paren on currentLine or readyFormattedLine + string line; // currentLine or readyFormattedLine + size_t paren = currentLine.rfind(")", charNum); + if (paren != string::npos) + line = currentLine; + // if not on currentLine it must be on the previous line + else + { + line = readyFormattedLine; + paren = line.rfind(")"); + if (paren == string::npos) + return false; + } + if (paren == 0) + return false; + + // find character preceding the closing paren + size_t lastChar = line.find_last_not_of(" \t", paren - 1); + if (lastChar == string::npos) + return false; + // check for pointer cast + if (line[lastChar] == '*') + return true; + return false; +} + +/** + * Determine if a < is a template definition or instantiation. + * Sets the class variables isInTemplate and templateDepth. + */ +void ASFormatter::checkIfTemplateOpener() +{ + assert(!isInTemplate && currentChar == '<'); + + // find first char after the '<' operators + size_t firstChar = currentLine.find_first_not_of("< \t", charNum); + if (firstChar == string::npos + || currentLine[firstChar] == '=') + { + // this is not a template -> leave... + isInTemplate = false; + return; + } + + bool isFirstLine = true; + bool needReset = false; + int parenDepth_ = 0; + int maxTemplateDepth = 0; + templateDepth = 0; + string nextLine_ = currentLine.substr(charNum); + + // find the angle brackets, bypassing all comments and quotes. + bool isInComment_ = false; + bool isInQuote_ = false; + char quoteChar_ = ' '; + while (sourceIterator->hasMoreLines() || isFirstLine) + { + if (isFirstLine) + isFirstLine = false; + else + { + nextLine_ = sourceIterator->peekNextLine(); + needReset = true; + } + // parse the line + for (size_t i = 0; i < nextLine_.length(); i++) + { + char currentChar_ = nextLine_[i]; + if (isWhiteSpace(currentChar_)) + continue; + if (nextLine_.compare(i, 2, "/*") == 0) + isInComment_ = true; + if (isInComment_) + { + if (nextLine_.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + if (currentChar_ == '\\') + { + ++i; + continue; + } + + if (isInQuote_) + { + if (currentChar_ == quoteChar_) + isInQuote_ = false; + continue; + } + + if (currentChar_ == '"' + || (currentChar_ == '\'' && !isDigitSeparator(nextLine_, i))) + { + isInQuote_ = true; + quoteChar_ = currentChar_; + continue; + } + if (nextLine_.compare(i, 2, "//") == 0) + { + i = nextLine_.length(); + continue; + } + + // not in a comment or quote + if (currentChar_ == '<') + { + ++templateDepth; + ++maxTemplateDepth; + continue; + } + else if (currentChar_ == '>') + { + --templateDepth; + if (templateDepth == 0) + { + if (parenDepth_ == 0) + { + // this is a template! + isInTemplate = true; + templateDepth = maxTemplateDepth; + } + goto exitFromSearch; + } + continue; + } + else if (currentChar_ == '(' || currentChar_ == ')') + { + if (currentChar_ == '(') + ++parenDepth_; + else + --parenDepth_; + if (parenDepth_ >= 0) + continue; + // this is not a template -> leave... + isInTemplate = false; + goto exitFromSearch; + } + else if (nextLine_.compare(i, 2, AS_AND) == 0 + || nextLine_.compare(i, 2, AS_OR) == 0) + { + // this is not a template -> leave... + isInTemplate = false; + goto exitFromSearch; + } + else if (currentChar_ == ',' // comma, e.g. A + || currentChar_ == '&' // reference, e.g. A + || currentChar_ == '*' // pointer, e.g. A + || currentChar_ == '^' // C++/CLI managed pointer, e.g. A + || currentChar_ == ':' // ::, e.g. std::string + || currentChar_ == '=' // assign e.g. default parameter + || currentChar_ == '[' // [] e.g. string[] + || currentChar_ == ']' // [] e.g. string[] + || currentChar_ == '(' // (...) e.g. function definition + || currentChar_ == ')' // (...) e.g. function definition + || (isJavaStyle() && currentChar_ == '?') // Java wildcard + ) + { + continue; + } + else if (!isLegalNameChar(currentChar_)) + { + // this is not a template -> leave... + isInTemplate = false; + templateDepth = 0; + goto exitFromSearch; + } + string name = getCurrentWord(nextLine_, i); + i += name.length() - 1; + } // end of for loop + } // end of while loop + + // goto needed to exit from two loops +exitFromSearch: + if (needReset) + sourceIterator->peekReset(); +} + +void ASFormatter::updateFormattedLineSplitPoints(char appendedChar) +{ + assert(maxCodeLength != string::npos); + assert(formattedLine.length() > 0); + + if (!isOkToSplitFormattedLine()) + return; + + char nextChar = peekNextChar(); + + // don't split before an end of line comment + if (nextChar == '/') + return; + + // don't split before or after a bracket + if (appendedChar == '{' || appendedChar == '}' + || previousNonWSChar == '{' || previousNonWSChar == '}' + || nextChar == '{' || nextChar == '}' + || currentChar == '{' || currentChar == '}') // currentChar tests for an appended bracket + return; + + // don't split before or after a block paren + if (appendedChar == '[' || appendedChar == ']' + || previousNonWSChar == '[' + || nextChar == '[' || nextChar == ']') + return; + + if (isWhiteSpace(appendedChar)) + { + if (nextChar != ')' // space before a closing paren + && nextChar != '(' // space before an opening paren + && nextChar != '/' // space before a comment + && nextChar != ':' // space before a colon + && currentChar != ')' // appended space before and after a closing paren + && currentChar != '(' // appended space before and after a opening paren + && previousNonWSChar != '(' // decided at the '(' + // don't break before a pointer or reference aligned to type + && !(nextChar == '*' + && !isCharPotentialOperator(previousNonWSChar) + && pointerAlignment == PTR_ALIGN_TYPE) + && !(nextChar == '&' + && !isCharPotentialOperator(previousNonWSChar) + && (referenceAlignment == REF_ALIGN_TYPE + || (referenceAlignment == REF_SAME_AS_PTR && pointerAlignment == PTR_ALIGN_TYPE))) + ) + { + if (formattedLine.length() - 1 <= maxCodeLength) + maxWhiteSpace = formattedLine.length() - 1; + else + maxWhiteSpacePending = formattedLine.length() - 1; + } + } + // unpadded closing parens may split after the paren (counts as whitespace) + else if (appendedChar == ')') + { + if (nextChar != ')' + && nextChar != ' ' + && nextChar != ';' + && nextChar != ',' + && nextChar != '.' + && !(nextChar == '-' && pointerSymbolFollows())) // check for -> + { + if (formattedLine.length() <= maxCodeLength) + maxWhiteSpace = formattedLine.length(); + else + maxWhiteSpacePending = formattedLine.length(); + } + } + // unpadded commas may split after the comma + else if (appendedChar == ',') + { + if (formattedLine.length() <= maxCodeLength) + maxComma = formattedLine.length(); + else + maxCommaPending = formattedLine.length(); + } + else if (appendedChar == '(') + { + if (nextChar != ')' && nextChar != '(' && nextChar != '"' && nextChar != '\'') + { + // if follows an operator break before + size_t parenNum; + if (isCharPotentialOperator(previousNonWSChar)) + parenNum = formattedLine.length() - 1 ; + else + parenNum = formattedLine.length(); + if (formattedLine.length() <= maxCodeLength) + maxParen = parenNum; + else + maxParenPending = parenNum; + } + } + else if (appendedChar == ';') + { + if (nextChar != ' ' && nextChar != '}' && nextChar != '/') // check for following comment + { + if (formattedLine.length() <= maxCodeLength) + maxSemi = formattedLine.length(); + else + maxSemiPending = formattedLine.length(); + } + } +} + +void ASFormatter::updateFormattedLineSplitPointsOperator(const string& sequence) +{ + assert(maxCodeLength != string::npos); + assert(formattedLine.length() > 0); + + if (!isOkToSplitFormattedLine()) + return; + + char nextChar = peekNextChar(); + + // don't split before an end of line comment + if (nextChar == '/') + return; + + // check for logical conditional + if (sequence == "||" || sequence == "&&" || sequence == "or" || sequence == "and") + { + if (shouldBreakLineAfterLogical) + { + if (formattedLine.length() <= maxCodeLength) + maxAndOr = formattedLine.length(); + else + maxAndOrPending = formattedLine.length(); + } + else + { + // adjust for leading space in the sequence + size_t sequenceLength = sequence.length(); + if (formattedLine.length() > sequenceLength + && isWhiteSpace(formattedLine[formattedLine.length() - sequenceLength - 1])) + sequenceLength++; + if (formattedLine.length() - sequenceLength <= maxCodeLength) + maxAndOr = formattedLine.length() - sequenceLength; + else + maxAndOrPending = formattedLine.length() - sequenceLength; + } + } + // comparison operators will split after the operator (counts as whitespace) + else if (sequence == "==" || sequence == "!=" || sequence == ">=" || sequence == "<=") + { + if (formattedLine.length() <= maxCodeLength) + maxWhiteSpace = formattedLine.length(); + else + maxWhiteSpacePending = formattedLine.length(); + } + // unpadded operators that will split BEFORE the operator (counts as whitespace) + else if (sequence == "+" || sequence == "-" || sequence == "?") + { + if (charNum > 0 + && (isLegalNameChar(currentLine[charNum - 1]) + || currentLine[charNum - 1] == ')' + || currentLine[charNum - 1] == ']' + || currentLine[charNum - 1] == '\"')) + { + if (formattedLine.length() - 1 <= maxCodeLength) + maxWhiteSpace = formattedLine.length() - 1; + else + maxWhiteSpacePending = formattedLine.length() - 1; + } + } + // unpadded operators that will USUALLY split AFTER the operator (counts as whitespace) + else if (sequence == "=" || sequence == ":") + { + // split BEFORE if the line is too long + // do NOT use <= here, must allow for a bracket attached to an array + size_t splitPoint = 0; + if (formattedLine.length() < maxCodeLength) + splitPoint = formattedLine.length(); + else + splitPoint = formattedLine.length() - 1; + // padded or unpadded arrays + if (previousNonWSChar == ']') + { + if (formattedLine.length() - 1 <= maxCodeLength) + maxWhiteSpace = splitPoint; + else + maxWhiteSpacePending = splitPoint; + } + else if (charNum > 0 + && (isLegalNameChar(currentLine[charNum - 1]) + || currentLine[charNum - 1] == ')' + || currentLine[charNum - 1] == ']')) + { + if (formattedLine.length() <= maxCodeLength) + maxWhiteSpace = splitPoint; + else + maxWhiteSpacePending = splitPoint; + } + } +} + +/** + * Update the split point when a pointer or reference is formatted. + * The argument is the maximum index of the last whitespace character. + */ +void ASFormatter::updateFormattedLineSplitPointsPointerOrReference(size_t index) +{ + assert(maxCodeLength != string::npos); + assert(formattedLine.length() > 0); + assert(index < formattedLine.length()); + + if (!isOkToSplitFormattedLine()) + return; + + if (index < maxWhiteSpace) // just in case + return; + + if (index <= maxCodeLength) + maxWhiteSpace = index; + else + maxWhiteSpacePending = index; +} + +bool ASFormatter::isOkToSplitFormattedLine() +{ + assert(maxCodeLength != string::npos); + // Is it OK to split the line? + if (shouldKeepLineUnbroken + || isInLineComment + || isInComment + || isInQuote + || isInCase + || isInPreprocessor + || isInExecSQL + || isInAsm || isInAsmOneLine || isInAsmBlock + || isInTemplate) + return false; + + if (!isOkToBreakBlock(bracketTypeStack->back()) && currentChar != '{') + { + shouldKeepLineUnbroken = true; + clearFormattedLineSplitPoints(); + return false; + } + else if (isBracketType(bracketTypeStack->back(), ARRAY_TYPE)) + { + shouldKeepLineUnbroken = true; + if (!isBracketType(bracketTypeStack->back(), ARRAY_NIS_TYPE)) + clearFormattedLineSplitPoints(); + return false; + } + return true; +} + +/* This is called if the option maxCodeLength is set. + */ +void ASFormatter::testForTimeToSplitFormattedLine() +{ + // DO NOT ASSERT maxCodeLength HERE + // should the line be split + if (formattedLine.length() > maxCodeLength && !isLineReady) + { + size_t splitPoint = findFormattedLineSplitPoint(); + if (splitPoint > 0 && splitPoint < formattedLine.length()) + { + string splitLine = formattedLine.substr(splitPoint); + formattedLine = formattedLine.substr(0, splitPoint); + breakLine(true); + formattedLine = splitLine; + // if break-blocks is requested and this is a one-line statement + string nextWord = ASBeautifier::getNextWord(currentLine, charNum - 1); + if (isAppendPostBlockEmptyLineRequested + && (nextWord == "break" || nextWord == "continue")) + { + isAppendPostBlockEmptyLineRequested = false; + isPrependPostBlockEmptyLineRequested = true; + } + else + isPrependPostBlockEmptyLineRequested = false; + // adjust max split points + maxAndOr = (maxAndOr > splitPoint) ? (maxAndOr - splitPoint) : 0; + maxSemi = (maxSemi > splitPoint) ? (maxSemi - splitPoint) : 0; + maxComma = (maxComma > splitPoint) ? (maxComma - splitPoint) : 0; + maxParen = (maxParen > splitPoint) ? (maxParen - splitPoint) : 0; + maxWhiteSpace = (maxWhiteSpace > splitPoint) ? (maxWhiteSpace - splitPoint) : 0; + if (maxSemiPending > 0) + { + maxSemi = (maxSemiPending > splitPoint) ? (maxSemiPending - splitPoint) : 0; + maxSemiPending = 0; + } + if (maxAndOrPending > 0) + { + maxAndOr = (maxAndOrPending > splitPoint) ? (maxAndOrPending - splitPoint) : 0; + maxAndOrPending = 0; + } + if (maxCommaPending > 0) + { + maxComma = (maxCommaPending > splitPoint) ? (maxCommaPending - splitPoint) : 0; + maxCommaPending = 0; + } + if (maxParenPending > 0) + { + maxParen = (maxParenPending > splitPoint) ? (maxParenPending - splitPoint) : 0; + maxParenPending = 0; + } + if (maxWhiteSpacePending > 0) + { + maxWhiteSpace = (maxWhiteSpacePending > splitPoint) ? (maxWhiteSpacePending - splitPoint) : 0; + maxWhiteSpacePending = 0; + } + // don't allow an empty formatted line + size_t firstText = formattedLine.find_first_not_of(" \t"); + if (firstText == string::npos && formattedLine.length() > 0) + { + formattedLine.erase(); + clearFormattedLineSplitPoints(); + if (isWhiteSpace(currentChar)) + for (size_t i = charNum + 1; i < currentLine.length() && isWhiteSpace(currentLine[i]); i++) + goForward(1); + } + else if (firstText > 0) + { + formattedLine.erase(0, firstText); + maxSemi = (maxSemi > firstText) ? (maxSemi - firstText) : 0; + maxAndOr = (maxAndOr > firstText) ? (maxAndOr - firstText) : 0; + maxComma = (maxComma > firstText) ? (maxComma - firstText) : 0; + maxParen = (maxParen > firstText) ? (maxParen - firstText) : 0; + maxWhiteSpace = (maxWhiteSpace > firstText) ? (maxWhiteSpace - firstText) : 0; + } + // reset formattedLineCommentNum + if (formattedLineCommentNum != string::npos) + { + formattedLineCommentNum = formattedLine.find("//"); + if (formattedLineCommentNum == string::npos) + formattedLineCommentNum = formattedLine.find("/*"); + } + } + } +} + +size_t ASFormatter::findFormattedLineSplitPoint() const +{ + assert(maxCodeLength != string::npos); + // determine where to split + size_t minCodeLength = 10; + size_t splitPoint = 0; + splitPoint = maxSemi; + if (maxAndOr >= minCodeLength) + splitPoint = maxAndOr; + if (splitPoint < minCodeLength) + { + splitPoint = maxWhiteSpace; + // use maxParen instead if it is long enough + if (maxParen > splitPoint + || maxParen >= maxCodeLength * .7) + splitPoint = maxParen; + // use maxComma instead if it is long enough + // increasing the multiplier causes more splits at whitespace + if (maxComma > splitPoint + || maxComma >= maxCodeLength * .3) + splitPoint = maxComma; + } + // replace split point with first available break point + if (splitPoint < minCodeLength) + { + splitPoint = string::npos; + if (maxSemiPending > 0 && maxSemiPending < splitPoint) + splitPoint = maxSemiPending; + if (maxAndOrPending > 0 && maxAndOrPending < splitPoint) + splitPoint = maxAndOrPending; + if (maxCommaPending > 0 && maxCommaPending < splitPoint) + splitPoint = maxCommaPending; + if (maxParenPending > 0 && maxParenPending < splitPoint) + splitPoint = maxParenPending; + if (maxWhiteSpacePending > 0 && maxWhiteSpacePending < splitPoint) + splitPoint = maxWhiteSpacePending; + if (splitPoint == string::npos) + splitPoint = 0; + } + // if remaining line after split is too long + else if (formattedLine.length() - splitPoint > maxCodeLength) + { + // if end of the currentLine, find a new split point + size_t newCharNum; + if (isCharPotentialHeader(currentLine, charNum)) + newCharNum = getCurrentWord(currentLine, charNum).length() + charNum; + else + newCharNum = charNum + 2; + if (newCharNum + 1 > currentLine.length()) + { + // don't move splitPoint from before a conditional to after + if (maxWhiteSpace > splitPoint + 3) + splitPoint = maxWhiteSpace; + if (maxParen > splitPoint) + splitPoint = maxParen; + } + } + + return splitPoint; +} + +void ASFormatter::clearFormattedLineSplitPoints() +{ + maxSemi = 0; + maxAndOr = 0; + maxComma = 0; + maxParen = 0; + maxWhiteSpace = 0; + maxSemiPending = 0; + maxAndOrPending = 0; + maxCommaPending = 0; + maxParenPending = 0; + maxWhiteSpacePending = 0; +} + +/** + * Check if a pointer symbol (->) follows on the currentLine. + */ +bool ASFormatter::pointerSymbolFollows() const +{ + size_t peekNum = currentLine.find_first_not_of(" \t", charNum + 1); + if (peekNum == string::npos || currentLine.compare(peekNum, 2, "->") != 0) + return false; + return true; +} + +/** + * Compute the input checksum. + * This is called as an assert so it for is debug config only + */ +bool ASFormatter::computeChecksumIn(const string& currentLine_) +{ + for (size_t i = 0; i < currentLine_.length(); i++) + if (!isWhiteSpace(currentLine_[i])) + checksumIn += currentLine_[i]; + return true; +} + +/** + * Adjust the input checksum for deleted chars. + * This is called as an assert so it for is debug config only + */ +bool ASFormatter::adjustChecksumIn(int adjustment) +{ + checksumIn += adjustment; + return true; +} + +/** + * get the value of checksumIn for unit testing + * + * @return checksumIn. + */ +size_t ASFormatter::getChecksumIn() const +{ + return checksumIn; +} + +/** + * Compute the output checksum. + * This is called as an assert so it is for debug config only + */ +bool ASFormatter::computeChecksumOut(const string& beautifiedLine) +{ + for (size_t i = 0; i < beautifiedLine.length(); i++) + if (!isWhiteSpace(beautifiedLine[i])) + checksumOut += beautifiedLine[i]; + return true; +} + +/** + * Return isLineReady for the final check at end of file. + */ +bool ASFormatter::getIsLineReady() const +{ + return isLineReady; +} + +/** + * get the value of checksumOut for unit testing + * + * @return checksumOut. + */ +size_t ASFormatter::getChecksumOut() const +{ + return checksumOut; +} + +/** + * Return the difference in checksums. + * If zero all is okay. + */ +int ASFormatter::getChecksumDiff() const +{ + return checksumOut - checksumIn; +} + +// for unit testing +int ASFormatter::getFormatterFileType() const +{ + return formatterFileType; +} + +// Check if an operator follows the next word. +// The next word must be a legal name. +const string* ASFormatter::getFollowingOperator() const +{ + // find next word + size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextNum == string::npos) + return NULL; + + if (!isLegalNameChar(currentLine[nextNum])) + return NULL; + + // bypass next word and following spaces + while (nextNum < currentLine.length()) + { + if (!isLegalNameChar(currentLine[nextNum]) + && !isWhiteSpace(currentLine[nextNum])) + break; + nextNum++; + } + + if (nextNum >= currentLine.length() + || !isCharPotentialOperator(currentLine[nextNum]) + || currentLine[nextNum] == '/') // comment + return NULL; + + const string* newOperator = ASBeautifier::findOperator(currentLine, nextNum, operators); + return newOperator; +} + +// Check following data to determine if the current character is an array operator. +bool ASFormatter::isArrayOperator() const +{ + assert(currentChar == '*' || currentChar == '&' || currentChar == '^'); + assert(isBracketType(bracketTypeStack->back(), ARRAY_TYPE)); + + // find next word + size_t nextNum = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextNum == string::npos) + return false; + + if (!isLegalNameChar(currentLine[nextNum])) + return false; + + // bypass next word and following spaces + while (nextNum < currentLine.length()) + { + if (!isLegalNameChar(currentLine[nextNum]) + && !isWhiteSpace(currentLine[nextNum])) + break; + nextNum++; + } + + // check for characters that indicate an operator + if (currentLine[nextNum] == ',' + || currentLine[nextNum] == '}' + || currentLine[nextNum] == ')' + || currentLine[nextNum] == '(') + return true; + return false; +} + +// Reset the flags that indicate various statement information. +void ASFormatter::resetEndOfStatement() +{ + foundQuestionMark = false; + foundNamespaceHeader = false; + foundClassHeader = false; + foundStructHeader = false; + foundInterfaceHeader = false; + foundPreDefinitionHeader = false; + foundPreCommandHeader = false; + foundPreCommandMacro = false; + foundCastOperator = false; + isInPotentialCalculation = false; + isSharpAccessor = false; + isSharpDelegate = false; + isInObjCMethodDefinition = false; + isInObjCInterface = false; + isInObjCSelector = false; + isInEnum = false; + isInExternC = false; + elseHeaderFollowsComments = false; + nonInStatementBracket = 0; + while (!questionMarkStack->empty()) + questionMarkStack->pop_back(); +} + +// Find the colon alignment for an Objective-C method definition. +int ASFormatter::findObjCColonAlignment() const +{ + assert(currentChar == '+' || currentChar == '-'); + assert(getAlignMethodColon()); + + bool isFirstLine = true; + bool haveFirstColon = false; + bool needReset = false; + bool isInComment_ = false; + bool isInQuote_ = false; + char quoteChar_ = ' '; + int colonAdjust = 0; + int colonAlign = 0; + string nextLine_ = currentLine; + + // peek next line + while (sourceIterator->hasMoreLines() || isFirstLine) + { + if (!isFirstLine) + { + nextLine_ = sourceIterator->peekNextLine(); + needReset = true; + } + // parse the line + haveFirstColon = false; + nextLine_ = ASBeautifier::trim(nextLine_); + for (size_t i = 0; i < nextLine_.length(); i++) + { + if (isWhiteSpace(nextLine_[i])) + continue; + if (nextLine_.compare(i, 2, "/*") == 0) + isInComment_ = true; + if (isInComment_) + { + if (nextLine_.compare(i, 2, "*/") == 0) + { + isInComment_ = false; + ++i; + } + continue; + } + if (nextLine_[i] == '\\') + { + ++i; + continue; + } + if (isInQuote_) + { + if (nextLine_[i] == quoteChar_) + isInQuote_ = false; + continue; + } + + if (nextLine_[i] == '"' + || (nextLine_[i] == '\'' && !isDigitSeparator(nextLine_, i))) + { + isInQuote_ = true; + quoteChar_ = nextLine_[i]; + continue; + } + if (nextLine_.compare(i, 2, "//") == 0) + { + i = nextLine_.length(); + continue; + } + // process the current char + if (nextLine_[i] == '{' || nextLine_[i] == ';') + goto EndOfWhileLoop; + if (isFirstLine) // colon align does not include the first line + continue; + if (haveFirstColon) + continue; + // compute colon adjustment + if (nextLine_[i] == ':') + { + haveFirstColon = true; + if (shouldPadMethodColon) + { + int spacesStart; + for (spacesStart = i; spacesStart > 0; spacesStart--) + if (!isWhiteSpace(nextLine_[spacesStart - 1])) + break; + int spaces = i - spacesStart; + if (objCColonPadMode == COLON_PAD_ALL || objCColonPadMode == COLON_PAD_BEFORE) + colonAdjust = 1 - spaces; + else if (objCColonPadMode == COLON_PAD_NONE || objCColonPadMode == COLON_PAD_AFTER) + colonAdjust = 0 - spaces; + } + // compute alignment + int colonPosition = i + colonAdjust; + if (colonPosition > colonAlign) + colonAlign = colonPosition; + } + } // end of for loop + isFirstLine = false; + } // end of while loop +EndOfWhileLoop: + if (needReset) + sourceIterator->peekReset(); + return colonAlign; +} + +// pad an Objective-C method colon +void ASFormatter::padObjCMethodColon() +{ + assert(currentChar == ':'); + int commentAdjust = 0; + char nextChar = peekNextChar(); + if (objCColonPadMode == COLON_PAD_NONE + || objCColonPadMode == COLON_PAD_AFTER + || nextChar == ')') + { + // remove spaces before + for (int i = formattedLine.length() - 1; (i > -1) && isWhiteSpace(formattedLine[i]); i--) + { + formattedLine.erase(i); + --commentAdjust; + } + } + else + { + // pad space before + for (int i = formattedLine.length() - 1; (i > 0) && isWhiteSpace(formattedLine[i]); i--) + if (isWhiteSpace(formattedLine[i - 1])) + { + formattedLine.erase(i); + --commentAdjust; + } + appendSpacePad(); + } + if (objCColonPadMode == COLON_PAD_NONE + || objCColonPadMode == COLON_PAD_BEFORE + || nextChar == ')') + { + // remove spaces after + int nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText == (int)string::npos) + nextText = currentLine.length(); + int spaces = nextText - charNum - 1; + if (spaces > 0) + { + // do not use goForward here + currentLine.erase(charNum + 1, spaces); + spacePadNum -= spaces; + } + } + else + { + // pad space after + int nextText = currentLine.find_first_not_of(" \t", charNum + 1); + if (nextText == (int)string::npos) + nextText = currentLine.length(); + int spaces = nextText - charNum - 1; + if (spaces == 0) + { + currentLine.insert(charNum + 1, 1, ' '); + spacePadNum += 1; + } + else if (spaces > 1) + { + // do not use goForward here + currentLine.erase(charNum + 1, spaces - 1); + spacePadNum -= spaces - 1; + } + } + spacePadNum += commentAdjust; +} + +// Remove the leading '*' from a comment line and indent to the next tab. +void ASFormatter::stripCommentPrefix() +{ + int firstChar = formattedLine.find_first_not_of(" \t"); + if (firstChar < 0) + return; + + if (isInCommentStartLine) + { + // comment opener must begin the line + if (formattedLine.compare(firstChar, 2, "/*") != 0) + return; + int commentOpener = firstChar; + // ignore single line comments + int commentEnd = formattedLine.find("*/", firstChar + 2); + if (commentEnd != -1) + return; + // first char after the comment opener must be at least one indent + int followingText = formattedLine.find_first_not_of(" \t", commentOpener + 2); + if (followingText < 0) + return; + if (formattedLine[followingText] == '*' || formattedLine[followingText] == '!') + followingText = formattedLine.find_first_not_of(" \t", followingText + 1); + if (followingText < 0) + return; + if (formattedLine[followingText] == '*') + return; + int indentLen = getIndentLength(); + int followingTextIndent = followingText - commentOpener; + if (followingTextIndent < indentLen) + { + string stringToInsert(indentLen - followingTextIndent, ' '); + formattedLine.insert(followingText, stringToInsert); + } + return; + } + // comment body including the closer + else if (formattedLine[firstChar] == '*') + { + if (formattedLine.compare(firstChar, 2, "*/") == 0) + { + // line starts with an end comment + formattedLine = "*/"; + } + else + { + // build a new line with one indent + int secondChar = formattedLine.find_first_not_of(" \t", firstChar + 1); + if (secondChar < 0) + { + adjustChecksumIn(-'*'); + formattedLine.erase(); + return; + } + if (formattedLine[secondChar] == '*') + return; + // replace the leading '*' + int indentLen = getIndentLength(); + adjustChecksumIn(-'*'); + // second char must be at least one indent + if (formattedLine.substr(0, secondChar).find('\t') != string::npos) + { + formattedLine.erase(firstChar, 1); + } + else + { + int spacesToInsert = 0; + if (secondChar >= indentLen) + spacesToInsert = secondChar; + else + spacesToInsert = indentLen; + formattedLine = string(spacesToInsert, ' ') + formattedLine.substr(secondChar); + } + // remove a trailing '*' + int lastChar = formattedLine.find_last_not_of(" \t"); + if (lastChar > -1 && formattedLine[lastChar] == '*') + { + adjustChecksumIn(-'*'); + formattedLine[lastChar] = ' '; + } + } + } + else + { + // first char not a '*' + // first char must be at least one indent + if (formattedLine.substr(0, firstChar).find('\t') == string::npos) + { + int indentLen = getIndentLength(); + if (firstChar < indentLen) + { + string stringToInsert(indentLen, ' '); + formattedLine = stringToInsert + formattedLine.substr(firstChar); + } + } + } +} + +} // end namespace astyle diff --git a/External/Tools/AStyle/src/ASLocalizer.cpp b/External/Tools/AStyle/src/ASLocalizer.cpp new file mode 100644 index 0000000000..aac76a95bf --- /dev/null +++ b/External/Tools/AStyle/src/ASLocalizer.cpp @@ -0,0 +1,881 @@ +// FILE ENCODING IS UTF-8 WITHOUT A BOM. +// русский 中文(简体) 日本 한국의 +// +// ASLocalizer.cpp +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * + * To add a new language: + * + * Add a new translation class to ASLocalizer.h. + * Add the Add the English-Translation pair to the constructor in ASLocalizer.cpp. + * Update the WinLangCode array, if necessary. + * Add the language code to the function setTranslationClass(). + * + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + */ + +//---------------------------------------------------------------------------- +// headers +//---------------------------------------------------------------------------- + +#include "ASLocalizer.h" + +#ifdef _WIN32 + #include +#endif + +#ifdef __DMC__ + // digital mars doesn't have these + const size_t SUBLANG_CHINESE_MACAU = 5; + const size_t LANG_HINDI = 57; +#endif + +#ifdef __VMS + #define __USE_STD_IOSTREAM 1 + #include +#else + #include +#endif + +#include +#include +#include // needed by some compilers +#include +#include + +#ifdef _MSC_VER + #pragma warning(disable: 4996) // secure version deprecation warnings +#endif + +#ifdef __BORLANDC__ + #pragma warn -8104 // Local Static with constructor dangerous for multi-threaded apps +#endif + +#ifdef __INTEL_COMPILER + #pragma warning(disable: 383) // value copied to temporary, reference to temporary used + #pragma warning(disable: 981) // operands are evaluated in unspecified order +#endif + +#ifdef __clang__ + #pragma clang diagnostic ignored "-Wdeprecated-declarations" // wcstombs +#endif + +namespace astyle { + +#ifndef ASTYLE_LIB + +//---------------------------------------------------------------------------- +// ASLocalizer class methods. +//---------------------------------------------------------------------------- + +ASLocalizer::ASLocalizer() +// Set the locale information. +{ + // set language default values to english (ascii) + // this will be used if a locale or a language cannot be found + m_localeName = "UNKNOWN"; + m_langID = "en"; + m_lcid = 0; + m_subLangID.clear(); + m_translation = NULL; + + // Not all compilers support the C++ function locale::global(locale("")); + // For testing on Windows change the "Region and Language" settings or use AppLocale. + // For testing on Linux change the LANG environment variable: LANG=fr_FR.UTF-8. + // setlocale() will use the LANG environment variable on Linux. + + char* localeName = setlocale(LC_ALL, ""); + if (localeName == NULL) // use the english (ascii) defaults + { + fprintf(stderr, "\n%s\n\n", "Cannot set native locale, reverting to English"); + setTranslationClass(); + return; + } + // set the class variables +#ifdef _WIN32 + size_t lcid = GetUserDefaultLCID(); + setLanguageFromLCID(lcid); +#else + setLanguageFromName(localeName); +#endif +} + +ASLocalizer::~ASLocalizer() +// Delete dynamically allocated memory. +{ + delete m_translation; +} + +#ifdef _WIN32 + +struct WinLangCode +{ + size_t winLang; + char canonicalLang[3]; +}; + +static WinLangCode wlc[] = +// primary language identifier http://msdn.microsoft.com/en-us/library/aa912554.aspx +// sublanguage identifier http://msdn.microsoft.com/en-us/library/aa913256.aspx +// language ID http://msdn.microsoft.com/en-us/library/ee797784%28v=cs.20%29.aspx +{ + { LANG_CHINESE, "zh" }, + { LANG_DUTCH, "nl" }, + { LANG_ENGLISH, "en" }, + { LANG_FINNISH, "fi" }, + { LANG_FRENCH, "fr" }, + { LANG_GERMAN, "de" }, + { LANG_HINDI, "hi" }, + { LANG_ITALIAN, "it" }, + { LANG_JAPANESE, "ja" }, + { LANG_KOREAN, "ko" }, + { LANG_POLISH, "pl" }, + { LANG_PORTUGUESE, "pt" }, + { LANG_RUSSIAN, "ru" }, + { LANG_SPANISH, "es" }, + { LANG_SWEDISH, "sv" }, + { LANG_UKRAINIAN, "uk" }, +}; + +void ASLocalizer::setLanguageFromLCID(size_t lcid) +// Windows get the language to use from the user locale. +// NOTE: GetUserDefaultLocaleName() gets nearly the same name as Linux. +// But it needs Windows Vista or higher. +// Same with LCIDToLocaleName(). +{ + m_lcid = lcid; + m_langID = "en"; // default to english + + size_t lang = PRIMARYLANGID(LANGIDFROMLCID(m_lcid)); + size_t sublang = SUBLANGID(LANGIDFROMLCID(m_lcid)); + // find language in the wlc table + size_t count = sizeof(wlc) / sizeof(wlc[0]); + for (size_t i = 0; i < count; i++) + { + if (wlc[i].winLang == lang) + { + m_langID = wlc[i].canonicalLang; + break; + } + } + if (m_langID == "zh") + { + if (sublang == SUBLANG_CHINESE_SIMPLIFIED || sublang == SUBLANG_CHINESE_SINGAPORE) + m_subLangID = "CHS"; + else + m_subLangID = "CHT"; // default + } + setTranslationClass(); +} + +#endif // _win32 + +string ASLocalizer::getLanguageID() const +// Returns the language ID in m_langID. +{ + return m_langID; +} + +const Translation* ASLocalizer::getTranslationClass() const +// Returns the name of the translation class in m_translation. Used for testing. +{ + assert(m_translation); + return m_translation; +} + +void ASLocalizer::setLanguageFromName(const char* langID) +// Linux set the language to use from the langID. +// +// the language string has the following form +// +// lang[_LANG][.encoding][@modifier] +// +// (see environ(5) in the Open Unix specification) +// +// where lang is the primary language, LANG is a sublang/territory, +// encoding is the charset to use and modifier "allows the user to select +// a specific instance of localization data within a single category" +// +// for example, the following strings are valid: +// fr +// fr_FR +// de_DE.iso88591 +// de_DE@euro +// de_DE.iso88591@euro +{ + // the constants describing the format of lang_LANG locale string + static const size_t LEN_LANG = 2; + + m_lcid = 0; + string langStr = langID; + m_langID = langStr.substr(0, LEN_LANG); + + // need the sublang for chinese + if (m_langID == "zh" && langStr[LEN_LANG] == '_') + { + string subLang = langStr.substr(LEN_LANG + 1, LEN_LANG); + if (subLang == "CN" || subLang == "SG") + m_subLangID = "CHS"; + else + m_subLangID = "CHT"; // default + } + setTranslationClass(); +} + +const char* ASLocalizer::settext(const char* textIn) const +// Call the settext class and return the value. +{ + assert(m_translation); + const string stringIn = textIn; + return m_translation->translate(stringIn).c_str(); +} + +void ASLocalizer::setTranslationClass() +// Return the required translation class. +// Sets the class variable m_translation from the value of m_langID. +// Get the language ID at http://msdn.microsoft.com/en-us/library/ee797784%28v=cs.20%29.aspx +{ + assert(m_langID.length()); + // delete previously set (--ascii option) + if (m_translation) + { + delete m_translation; + m_translation = NULL; + } + if (m_langID == "zh" && m_subLangID == "CHS") + m_translation = new ChineseSimplified; + else if (m_langID == "zh" && m_subLangID == "CHT") + m_translation = new ChineseTraditional; + else if (m_langID == "nl") + m_translation = new Dutch; + else if (m_langID == "en") + m_translation = new English; + else if (m_langID == "fi") + m_translation = new Finnish; + else if (m_langID == "fr") + m_translation = new French; + else if (m_langID == "de") + m_translation = new German; + else if (m_langID == "hi") + m_translation = new Hindi; + else if (m_langID == "it") + m_translation = new Italian; + else if (m_langID == "ja") + m_translation = new Japanese; + else if (m_langID == "ko") + m_translation = new Korean; + else if (m_langID == "pl") + m_translation = new Polish; + else if (m_langID == "pt") + m_translation = new Portuguese; + else if (m_langID == "ru") + m_translation = new Russian; + else if (m_langID == "es") + m_translation = new Spanish; + else if (m_langID == "sv") + m_translation = new Swedish; + else if (m_langID == "uk") + m_translation = new Ukrainian; + else // default + m_translation = new English; +} + +//---------------------------------------------------------------------------- +// Translation base class methods. +//---------------------------------------------------------------------------- + +void Translation::addPair(const string& english, const wstring& translated) +// Add a string pair to the translation vector. +{ + pair entry(english, translated); + m_translation.push_back(entry); +} + +string Translation::convertToMultiByte(const wstring& wideStr) const +// Convert wchar_t to a multibyte string using the currently assigned locale. +// Return an empty string if an error occurs. +{ + static bool msgDisplayed = false; + // get length of the output excluding the NULL and validate the parameters + size_t mbLen = wcstombs(NULL, wideStr.c_str(), 0); + if (mbLen == string::npos) + { + if (!msgDisplayed) + { + fprintf(stderr, "\n%s\n\n", "Cannot convert to multi-byte string, reverting to English"); + msgDisplayed = true; + } + return ""; + } + // convert the characters + char* mbStr = new(nothrow) char[mbLen + 1]; + if (mbStr == NULL) + { + if (!msgDisplayed) + { + fprintf(stderr, "\n%s\n\n", "Bad memory alloc for multi-byte string, reverting to English"); + msgDisplayed = true; + } + return ""; + } + wcstombs(mbStr, wideStr.c_str(), mbLen + 1); + // return the string + string mbTranslation = mbStr; + delete [] mbStr; + return mbTranslation; +} + +size_t Translation::getTranslationVectorSize() const +// Return the translation vector size. Used for testing. +{ + return m_translation.size(); +} + +bool Translation::getWideTranslation(const string& stringIn, wstring& wideOut) const +// Get the wide translation string. Used for testing. +{ + for (size_t i = 0; i < m_translation.size(); i++) + { + if (m_translation[i].first == stringIn) + { + wideOut = m_translation[i].second; + return true; + } + } + // not found + wideOut = L""; + return false; +} + +string& Translation::translate(const string& stringIn) const +// Translate a string. +// Return a static string instead of a member variable so the method can have a "const" designation. +// This allows "settext" to be called from a "const" method. +{ + static string mbTranslation; + mbTranslation.clear(); + for (size_t i = 0; i < m_translation.size(); i++) + { + if (m_translation[i].first == stringIn) + { + mbTranslation = convertToMultiByte(m_translation[i].second); + break; + } + } + // not found, return english + if (mbTranslation.empty()) + mbTranslation = stringIn; + return mbTranslation; +} + +//---------------------------------------------------------------------------- +// Translation class methods. +// These classes have only a constructor which builds the language vector. +//---------------------------------------------------------------------------- + +ChineseSimplified::ChineseSimplified() // 中文(简体) +{ + addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"未改变 %s\n"); // should align with formatted + addPair("Directory %s\n", L"目录 %s\n"); + addPair("Exclude %s\n", L"排除 %s\n"); + addPair("Exclude (unmatched) %s\n", L"排除(无匹配项) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改变 "); + addPair(" seconds ", L" 秒 "); + addPair("%d min %d sec ", L"%d 分 %d 秒 "); + addPair("%s lines\n", L"%s 行\n"); + addPair("Using default options file %s\n", L"使用默认配置文件 %s\n"); + addPair("Opening HTML documentation %s\n", L"打开HTML文档 %s\n"); + addPair("Invalid option file options:", L"无效的配置文件选项:"); + addPair("Invalid command line options:", L"无效的命令行选项:"); + addPair("For help on options type 'astyle -h'", L"输入 'astyle -h' 以获得有关命令行的帮助"); + addPair("Cannot open options file", L"无法打开配置文件"); + addPair("Cannot open directory", L"无法打开目录"); + addPair("Cannot open HTML file %s\n", L"无法打开HTML文件 %s\n"); + addPair("Command execute failure", L"执行命令失败"); + addPair("Command is not installed", L"未安装命令"); + addPair("Missing filename in %s\n", L"在%s缺少文件名\n"); + addPair("Recursive option with no wildcard", L"递归选项没有通配符"); + addPair("Did you intend quote the filename", L"你打算引用文件名"); + addPair("No file to process %s\n", L"没有文件可处理 %s\n"); + addPair("Did you intend to use --recursive", L"你打算使用 --recursive"); + addPair("Cannot process UTF-32 encoding", L"不能处理UTF-32编码"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style 已经终止运行"); +} + +ChineseTraditional::ChineseTraditional() // 中文(繁體) +{ + addPair("Formatted %s\n", L"格式化 %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"未改變 %s\n"); // should align with formatted + addPair("Directory %s\n", L"目錄 %s\n"); + addPair("Exclude %s\n", L"排除 %s\n"); + addPair("Exclude (unmatched) %s\n", L"排除(無匹配項) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s 格式化 %s 未改變 "); + addPair(" seconds ", L" 秒 "); + addPair("%d min %d sec ", L"%d 分 %d 秒 "); + addPair("%s lines\n", L"%s 行\n"); + addPair("Using default options file %s\n", L"使用默認配置文件 %s\n"); + addPair("Opening HTML documentation %s\n", L"打開HTML文檔 %s\n"); + addPair("Invalid option file options:", L"無效的配置文件選項:"); + addPair("Invalid command line options:", L"無效的命令行選項:"); + addPair("For help on options type 'astyle -h'", L"輸入'astyle -h'以獲得有關命令行的幫助:"); + addPair("Cannot open options file", L"無法打開配置文件"); + addPair("Cannot open directory", L"無法打開目錄"); + addPair("Cannot open HTML file %s\n", L"無法打開HTML文件 %s\n"); + addPair("Command execute failure", L"執行命令失敗"); + addPair("Command is not installed", L"未安裝命令"); + addPair("Missing filename in %s\n", L"在%s缺少文件名\n"); + addPair("Recursive option with no wildcard", L"遞歸選項沒有通配符"); + addPair("Did you intend quote the filename", L"你打算引用文件名"); + addPair("No file to process %s\n", L"沒有文件可處理 %s\n"); + addPair("Did you intend to use --recursive", L"你打算使用 --recursive"); + addPair("Cannot process UTF-32 encoding", L"不能處理UTF-32編碼"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style 已經終止運行"); +} + +Dutch::Dutch() // Nederlandse +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Geformatteerd %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Onveranderd %s\n"); // should align with formatted + addPair("Directory %s\n", L"Directory %s\n"); + addPair("Exclude %s\n", L"Uitsluiten %s\n"); + addPair("Exclude (unmatched) %s\n", L"Uitgesloten (ongeëvenaarde) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s geformatteerd %s onveranderd "); + addPair(" seconds ", L" seconden "); + addPair("%d min %d sec ", L"%d min %d sec "); + addPair("%s lines\n", L"%s lijnen\n"); + addPair("Using default options file %s\n", L"Met behulp van standaard opties bestand %s\n"); + addPair("Opening HTML documentation %s\n", L"Het openen van HTML-documentatie %s\n"); + addPair("Invalid option file options:", L"Ongeldige optie file opties:"); + addPair("Invalid command line options:", L"Ongeldige command line opties:"); + addPair("For help on options type 'astyle -h'", L"Voor hulp bij 'astyle-h' opties het type"); + addPair("Cannot open options file", L"Kan niet worden geopend options bestand"); + addPair("Cannot open directory", L"Kan niet open directory"); + addPair("Cannot open HTML file %s\n", L"Kan HTML-bestand niet openen %s\n"); + addPair("Command execute failure", L"Voeren commando falen"); + addPair("Command is not installed", L"Command is niet geïnstalleerd"); + addPair("Missing filename in %s\n", L"Ontbrekende bestandsnaam in %s\n"); + addPair("Recursive option with no wildcard", L"Recursieve optie met geen wildcard"); + addPair("Did you intend quote the filename", L"Heeft u van plan citaat van de bestandsnaam"); + addPair("No file to process %s\n", L"Geen bestand te verwerken %s\n"); + addPair("Did you intend to use --recursive", L"Hebt u van plan bent te gebruiken --recursive"); + addPair("Cannot process UTF-32 encoding", L"Kan niet verwerken UTF-32 codering"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style heeft beëindigd"); +} + +English::English() +// this class is NOT translated +{} + +Finnish::Finnish() // Suomeksi +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Muotoiltu %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Ennallaan %s\n"); // should align with formatted + addPair("Directory %s\n", L"Directory %s\n"); + addPair("Exclude %s\n", L"Sulkea %s\n"); + addPair("Exclude (unmatched) %s\n", L"Sulkea (verraton) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s muotoiltu %s ennallaan "); + addPair(" seconds ", L" sekuntia "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s linjat\n"); + addPair("Using default options file %s\n", L"Käyttämällä oletusasetuksia tiedosto %s\n"); + addPair("Opening HTML documentation %s\n", L"Avaaminen HTML asiakirjat %s\n"); + addPair("Invalid option file options:", L"Virheellinen vaihtoehto tiedosto vaihtoehtoja:"); + addPair("Invalid command line options:", L"Virheellinen komentorivin:"); + addPair("For help on options type 'astyle -h'", L"Apua vaihtoehdoista tyyppi 'astyle -h'"); + addPair("Cannot open options file", L"Ei voi avata vaihtoehtoja tiedostoa"); + addPair("Cannot open directory", L"Ei Open Directory"); + addPair("Cannot open HTML file %s\n", L"Ei voi avata HTML-tiedoston %s\n"); + addPair("Command execute failure", L"Suorita komento vika"); + addPair("Command is not installed", L"Komento ei ole asennettu"); + addPair("Missing filename in %s\n", L"Puuttuvat tiedostonimi %s\n"); + addPair("Recursive option with no wildcard", L"Rekursiivinen vaihtoehto ilman wildcard"); + addPair("Did you intend quote the filename", L"Oletko aio lainata tiedostonimi"); + addPair("No file to process %s\n", L"Ei tiedostoa käsitellä %s\n"); + addPair("Did you intend to use --recursive", L"Oliko aiot käyttää --recursive"); + addPair("Cannot process UTF-32 encoding", L"Ei voi käsitellä UTF-32 koodausta"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style on päättynyt"); +} + +French::French() // Française +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formaté %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Inchangée %s\n"); // should align with formatted + addPair("Directory %s\n", L"Répertoire %s\n"); + addPair("Exclude %s\n", L"Exclure %s\n"); + addPair("Exclude (unmatched) %s\n", L"Exclure (non appariés) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formaté %s inchangée "); + addPair(" seconds ", L" seconde "); + addPair("%d min %d sec ", L"%d min %d sec "); + addPair("%s lines\n", L"%s lignes\n"); + addPair("Using default options file %s\n", L"Options par défaut utilisation du fichier %s\n"); + addPair("Opening HTML documentation %s\n", L"Ouverture documentation HTML %s\n"); + addPair("Invalid option file options:", L"Options Blancs option du fichier:"); + addPair("Invalid command line options:", L"Blancs options ligne de commande:"); + addPair("For help on options type 'astyle -h'", L"Pour de l'aide sur les options tapez 'astyle -h'"); + addPair("Cannot open options file", L"Impossible d'ouvrir le fichier d'options"); + addPair("Cannot open directory", L"Impossible d'ouvrir le répertoire"); + addPair("Cannot open HTML file %s\n", L"Impossible d'ouvrir le fichier HTML %s\n"); + addPair("Command execute failure", L"Exécuter échec de la commande"); + addPair("Command is not installed", L"Commande n'est pas installé"); + addPair("Missing filename in %s\n", L"Nom de fichier manquant dans %s\n"); + addPair("Recursive option with no wildcard", L"Option récursive sans joker"); + addPair("Did you intend quote the filename", L"Avez-vous l'intention de citer le nom de fichier"); + addPair("No file to process %s\n", L"Aucun fichier à traiter %s\n"); + addPair("Did you intend to use --recursive", L"Avez-vous l'intention d'utiliser --recursive"); + addPair("Cannot process UTF-32 encoding", L"Impossible de traiter codage UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style a mis fin"); +} + +German::German() // Deutsch +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formatiert %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Unverändert %s\n"); // should align with formatted + addPair("Directory %s\n", L"Verzeichnis %s\n"); + addPair("Exclude %s\n", L"Ausschließen %s\n"); + addPair("Exclude (unmatched) %s\n", L"Ausschließen (unerreichte) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formatiert %s unverändert "); + addPair(" seconds ", L" sekunden "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s linien\n"); + addPair("Using default options file %s\n", L"Mit Standard-Optionen Dat %s\n"); + addPair("Opening HTML documentation %s\n", L"Öffnen HTML-Dokumentation %s\n"); + addPair("Invalid option file options:", L"Ungültige Option Datei-Optionen:"); + addPair("Invalid command line options:", L"Ungültige Kommandozeilen-Optionen:"); + addPair("For help on options type 'astyle -h'", L"Für Hilfe zu den Optionen geben Sie 'astyle -h'"); + addPair("Cannot open options file", L"Kann nicht geöffnet werden Optionsdatei"); + addPair("Cannot open directory", L"Kann nicht geöffnet werden Verzeichnis"); + addPair("Cannot open HTML file %s\n", L"Kann nicht öffnen HTML-Datei %s\n"); + addPair("Command execute failure", L"Execute Befehl Scheitern"); + addPair("Command is not installed", L"Befehl ist nicht installiert"); + addPair("Missing filename in %s\n", L"Missing in %s Dateiname\n"); + addPair("Recursive option with no wildcard", L"Rekursive Option ohne Wildcard"); + addPair("Did you intend quote the filename", L"Haben Sie die Absicht Inhalte der Dateiname"); + addPair("No file to process %s\n", L"Keine Datei zu verarbeiten %s\n"); + addPair("Did you intend to use --recursive", L"Haben Sie verwenden möchten --recursive"); + addPair("Cannot process UTF-32 encoding", L"Nicht verarbeiten kann UTF-32 Codierung"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style ist beendet"); +} + +Hindi::Hindi() // हिन्दी +// build the translation vector in the Translation base class +{ + // NOTE: Scintilla based editors (CodeBlocks) cannot always edit Hindi. + // Use Visual Studio instead. + addPair("Formatted %s\n", L"स्वरूपित किया %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"अपरिवर्तित %s\n"); // should align with formatted + addPair("Directory %s\n", L"निर्देशिका %s\n"); + addPair("Exclude %s\n", L"निकालना %s\n"); + addPair("Exclude (unmatched) %s\n", L"अपवर्जित (बेजोड़) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s स्वरूपित किया %s अपरिवर्तित "); + addPair(" seconds ", L" सेकंड "); + addPair("%d min %d sec ", L"%d मिनट %d सेकंड "); + addPair("%s lines\n", L"%s लाइनों\n"); + addPair("Using default options file %s\n", L"डिफ़ॉल्ट विकल्प का उपयोग कर फ़ाइल %s\n"); + addPair("Opening HTML documentation %s\n", L"एचटीएमएल प्रलेखन खोलना %s\n"); + addPair("Invalid option file options:", L"अवैध विकल्प फ़ाइल विकल्प हैं:"); + addPair("Invalid command line options:", L"कमांड लाइन विकल्प अवैध:"); + addPair("For help on options type 'astyle -h'", L"विकल्पों पर मदद के लिए प्रकार 'astyle -h'"); + addPair("Cannot open options file", L"विकल्प फ़ाइल नहीं खोल सकता है"); + addPair("Cannot open directory", L"निर्देशिका नहीं खोल सकता"); + addPair("Cannot open HTML file %s\n", L"HTML फ़ाइल नहीं खोल सकता %s\n"); + addPair("Command execute failure", L"आदेश विफलता निष्पादित"); + addPair("Command is not installed", L"कमान स्थापित नहीं है"); + addPair("Missing filename in %s\n", L"लापता में फ़ाइलनाम %s\n"); + addPair("Recursive option with no wildcard", L"कोई वाइल्डकार्ड साथ पुनरावर्ती विकल्प"); + addPair("Did you intend quote the filename", L"क्या आप बोली फ़ाइलनाम का इरादा"); + addPair("No file to process %s\n", L"कोई फ़ाइल %s प्रक्रिया के लिए\n"); + addPair("Did you intend to use --recursive", L"क्या आप उपयोग करना चाहते हैं --recursive"); + addPair("Cannot process UTF-32 encoding", L"UTF-32 कूटबन्धन प्रक्रिया नहीं कर सकते"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style समाप्त किया है"); +} + +Italian::Italian() // Italiano +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formattata %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Immutato %s\n"); // should align with formatted + addPair("Directory %s\n", L"Elenco %s\n"); + addPair("Exclude %s\n", L"Escludere %s\n"); + addPair("Exclude (unmatched) %s\n", L"Escludere (senza pari) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s ormattata %s immutato "); + addPair(" seconds ", L" secondo "); + addPair("%d min %d sec ", L"%d min %d seg "); + addPair("%s lines\n", L"%s linee\n"); + addPair("Using default options file %s\n", L"Utilizzando file delle opzioni di default %s\n"); + addPair("Opening HTML documentation %s\n", L"Apertura di documenti HTML %s\n"); + addPair("Invalid option file options:", L"Opzione non valida file delle opzioni:"); + addPair("Invalid command line options:", L"Opzioni della riga di comando non valido:"); + addPair("For help on options type 'astyle -h'", L"Per informazioni sulle opzioni di tipo 'astyle-h'"); + addPair("Cannot open options file", L"Impossibile aprire il file opzioni"); + addPair("Cannot open directory", L"Impossibile aprire la directory"); + addPair("Cannot open HTML file %s\n", L"Impossibile aprire il file HTML %s\n"); + addPair("Command execute failure", L"Esegui fallimento comando"); + addPair("Command is not installed", L"Il comando non è installato"); + addPair("Missing filename in %s\n", L"Nome del file mancante in %s\n"); + addPair("Recursive option with no wildcard", L"Opzione ricorsiva senza jolly"); + addPair("Did you intend quote the filename", L"Avete intenzione citare il nome del file"); + addPair("No file to process %s\n", L"Nessun file al processo %s\n"); + addPair("Did you intend to use --recursive", L"Hai intenzione di utilizzare --recursive"); + addPair("Cannot process UTF-32 encoding", L"Non è possibile processo di codifica UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminato"); +} + +Japanese::Japanese() // 日本 +{ + addPair("Formatted %s\n", L"フォーマット %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"変更 %s\n"); // should align with formatted + addPair("Directory %s\n", L"ディレクトリ %s\n"); + addPair("Exclude %s\n", L"除外する %s\n"); + addPair("Exclude (unmatched) %s\n", L"除外(マッチせず) %s\n"); + addPair(" %s formatted %s unchanged ", L" %sフォーマット %s 変更 "); + addPair(" seconds ", L" 秒 "); + addPair("%d min %d sec ", L"%d 分 %d 秒 "); + addPair("%s lines\n", L"%s の行\n"); + addPair("Using default options file %s\n", L"デフォルトの設定ファイルを使用してください %s\n"); + addPair("Opening HTML documentation %s\n", L"HTML文書を開く %s\n"); + addPair("Invalid option file options:", L"無効なコンフィギュレーションファイルオプション:"); + addPair("Invalid command line options:", L"無効なコマンドラインオプション:"); + addPair("For help on options type 'astyle -h'", L"コマンドラインについてのヘルプは'astyle- h'を入力してください"); + addPair("Cannot open options file", L"コンフィギュレーションファイルを開くことができません"); + addPair("Cannot open directory", L"ディレクトリのオープンに失敗しました"); + addPair("Cannot open HTML file %s\n", L"HTMLファイルを開くことができません %s\n"); + addPair("Command execute failure", L"コマンドの失敗を実行"); + addPair("Command is not installed", L"コマンドがインストールされていません"); + addPair("Missing filename in %s\n", L"%s はファイル名で欠落しています\n"); + addPair("Recursive option with no wildcard", L"再帰的なオプションではワイルドカードではない"); + addPair("Did you intend quote the filename", L"あなたは、ファイル名を参照するつもり"); + addPair("No file to process %s\n", L"いいえファイルは処理できません %s\n"); + addPair("Did you intend to use --recursive", L"あなたが使用する予定 --recursive"); + addPair("Cannot process UTF-32 encoding", L"UTF- 32エンコーディングを処理できない"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style 実行が終了しました"); +} + +Korean::Korean() // 한국의 +{ + addPair("Formatted %s\n", L"수정됨 %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"변경없음 %s\n"); // should align with formatted + addPair("Directory %s\n", L"디렉토리 %s\n"); + addPair("Exclude %s\n", L"제외됨 %s\n"); + addPair("Exclude (unmatched) %s\n", L"제외 (NO 일치) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s 수정됨 %s 변경없음 "); + addPair(" seconds ", L" 초 "); + addPair("%d min %d sec ", L"%d 분 %d 초 "); + addPair("%s lines\n", L"%s 라인\n"); + addPair("Using default options file %s\n", L"기본 구성 파일을 사용 %s\n"); + addPair("Opening HTML documentation %s\n", L"HTML 문서를 열기 %s\n"); + addPair("Invalid option file options:", L"잘못된 구성 파일 옵션 :"); + addPair("Invalid command line options:", L"잘못된 명령줄 옵션 :"); + addPair("For help on options type 'astyle -h'", L"도움말을 보려면 옵션 유형 'astyle - H'를 사용합니다"); + addPair("Cannot open options file", L"구성 파일을 열 수 없습니다"); + addPair("Cannot open directory", L"디렉토리를 열지 못했습니다"); + addPair("Cannot open HTML file %s\n", L"HTML 파일을 열 수 없습니다 %s\n"); + addPair("Command execute failure", L"명령 실패를 실행"); + addPair("Command is not installed", L"명령이 설치되어 있지 않습니다"); + addPair("Missing filename in %s\n", L"%s 에서 누락된 파일 이름\n"); + addPair("Recursive option with no wildcard", L"와일드 카드없이 재귀 옵션"); + addPair("Did you intend quote the filename", L"당신은 파일 이름을 인용하고자하나요"); + addPair("No file to process %s\n", L"처리할 파일이 없습니다 %s\n"); + addPair("Did you intend to use --recursive", L"--recursive 를 사용하고자 하십니까"); + addPair("Cannot process UTF-32 encoding", L"UTF-32 인코딩을 처리할 수 없습니다"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style를 종료합니다"); +} + +Polish::Polish() // Polski +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Sformatowany %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Niezmienione %s\n"); // should align with formatted + addPair("Directory %s\n", L"Katalog %s\n"); + addPair("Exclude %s\n", L"Wykluczać %s\n"); + addPair("Exclude (unmatched) %s\n", L"Wyklucz (niezrównany) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s sformatowany %s niezmienione "); + addPair(" seconds ", L" sekund "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s linii\n"); + addPair("Using default options file %s\n", L"Korzystanie z domyślnej opcji %s plik\n"); + addPair("Opening HTML documentation %s\n", L"Otwarcie dokumentacji HTML %s\n"); + addPair("Invalid option file options:", L"Nieprawidłowy opcji pliku opcji:"); + addPair("Invalid command line options:", L"Nieprawidłowe opcje wiersza polecenia:"); + addPair("For help on options type 'astyle -h'", L"Aby uzyskać pomoc od rodzaju opcji 'astyle -h'"); + addPair("Cannot open options file", L"Nie można otworzyć pliku opcji"); + addPair("Cannot open directory", L"Nie można otworzyć katalogu"); + addPair("Cannot open HTML file %s\n", L"Nie można otworzyć pliku HTML %s\n"); + addPair("Command execute failure", L"Wykonaj polecenia niepowodzenia"); + addPair("Command is not installed", L"Polecenie nie jest zainstalowany"); + addPair("Missing filename in %s\n", L"Brakuje pliku w %s\n"); + addPair("Recursive option with no wildcard", L"Rekurencyjne opcja bez symboli"); + addPair("Did you intend quote the filename", L"Czy zamierza Pan podać nazwę pliku"); + addPair("No file to process %s\n", L"Brak pliku do procesu %s\n"); + addPair("Did you intend to use --recursive", L"Czy masz zamiar używać --recursive"); + addPair("Cannot process UTF-32 encoding", L"Nie można procesu kodowania UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style został zakończony"); +} + +Portuguese::Portuguese() // Português +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formatado %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Inalterado %s\n"); // should align with formatted + addPair("Directory %s\n", L"Diretório %s\n"); + addPair("Exclude %s\n", L"Excluir %s\n"); + addPair("Exclude (unmatched) %s\n", L"Excluir (incomparável) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formatado %s inalterado "); + addPair(" seconds ", L" segundo "); + addPair("%d min %d sec ", L"%d min %d seg "); + addPair("%s lines\n", L"%s linhas\n"); + addPair("Using default options file %s\n", L"Usando o arquivo de opções padrão %s\n"); + addPair("Opening HTML documentation %s\n", L"Abrindo a documentação HTML %s\n"); + addPair("Invalid option file options:", L"Opções de arquivo inválido opção:"); + addPair("Invalid command line options:", L"Opções de linha de comando inválida:"); + addPair("For help on options type 'astyle -h'", L"Para obter ajuda sobre as opções de tipo 'astyle -h'"); + addPair("Cannot open options file", L"Não é possível abrir arquivo de opções"); + addPair("Cannot open directory", L"Não é possível abrir diretório"); + addPair("Cannot open HTML file %s\n", L"Não é possível abrir arquivo HTML %s\n"); + addPair("Command execute failure", L"Executar falha de comando"); + addPair("Command is not installed", L"Comando não está instalado"); + addPair("Missing filename in %s\n", L"Filename faltando em %s\n"); + addPair("Recursive option with no wildcard", L"Opção recursiva sem curinga"); + addPair("Did you intend quote the filename", L"Será que você pretende citar o nome do arquivo"); + addPair("No file to process %s\n", L"Nenhum arquivo para processar %s\n"); + addPair("Did you intend to use --recursive", L"Será que você pretende usar --recursive"); + addPair("Cannot process UTF-32 encoding", L"Não pode processar a codificação UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style terminou"); +} + +Russian::Russian() // русский +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Форматированный %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"без изменений %s\n"); // should align with formatted + addPair("Directory %s\n", L"каталог %s\n"); + addPair("Exclude %s\n", L"исключать %s\n"); + addPair("Exclude (unmatched) %s\n", L"Исключить (непревзойденный) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s Форматированный %s без изменений "); + addPair(" seconds ", L" секунды "); + addPair("%d min %d sec ", L"%d мин %d сек "); + addPair("%s lines\n", L"%s линий\n"); + addPair("Using default options file %s\n", L"Использование опции по умолчанию файл %s\n"); + addPair("Opening HTML documentation %s\n", L"Открытие HTML документации %s\n"); + addPair("Invalid option file options:", L"Недопустимый файл опций опцию:"); + addPair("Invalid command line options:", L"Недопустимые параметры командной строки:"); + addPair("For help on options type 'astyle -h'", L"Для получения справки по 'astyle -h' опций типа"); + addPair("Cannot open options file", L"Не удается открыть файл параметров"); + addPair("Cannot open directory", L"Не могу открыть каталог"); + addPair("Cannot open HTML file %s\n", L"Не удается открыть файл HTML %s\n"); + addPair("Command execute failure", L"Выполнить команду недостаточности"); + addPair("Command is not installed", L"Не установлен Команда"); + addPair("Missing filename in %s\n", L"Отсутствует имя файла в %s\n"); + addPair("Recursive option with no wildcard", L"Рекурсивный вариант без каких-либо шаблона"); + addPair("Did you intend quote the filename", L"Вы намерены цитатой файла"); + addPair("No file to process %s\n", L"Нет файлов для обработки %s\n"); + addPair("Did you intend to use --recursive", L"Неужели вы собираетесь использовать --recursive"); + addPair("Cannot process UTF-32 encoding", L"Не удается обработать UTF-32 кодировке"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style прекратил"); +} + +Spanish::Spanish() // Español +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formato %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Inalterado %s\n"); // should align with formatted + addPair("Directory %s\n", L"Directorio %s\n"); + addPair("Exclude %s\n", L"Excluir %s\n"); + addPair("Exclude (unmatched) %s\n", L"Excluir (incomparable) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formato %s inalterado "); + addPair(" seconds ", L" segundo "); + addPair("%d min %d sec ", L"%d min %d seg "); + addPair("%s lines\n", L"%s líneas\n"); + addPair("Using default options file %s\n", L"Uso de las opciones por defecto del archivo %s\n"); + addPair("Opening HTML documentation %s\n", L"Apertura de documentación HTML %s\n"); + addPair("Invalid option file options:", L"Opción no válida opciones de archivo:"); + addPair("Invalid command line options:", L"No válido opciones de línea de comando:"); + addPair("For help on options type 'astyle -h'", L"Para obtener ayuda sobre las opciones tipo 'astyle -h'"); + addPair("Cannot open options file", L"No se puede abrir el archivo de opciones"); + addPair("Cannot open directory", L"No se puede abrir el directorio"); + addPair("Cannot open HTML file %s\n", L"No se puede abrir el archivo HTML %s\n"); + addPair("Command execute failure", L"Ejecutar el fracaso de comandos"); + addPair("Command is not installed", L"El comando no está instalado"); + addPair("Missing filename in %s\n", L"Falta nombre del archivo en %s\n"); + addPair("Recursive option with no wildcard", L"Recursiva opción sin comodín"); + addPair("Did you intend quote the filename", L"Se tiene la intención de citar el nombre de archivo"); + addPair("No file to process %s\n", L"No existe el fichero a procesar %s\n"); + addPair("Did you intend to use --recursive", L"Se va a utilizar --recursive"); + addPair("Cannot process UTF-32 encoding", L"No se puede procesar la codificación UTF-32"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style ha terminado"); +} + +Swedish::Swedish() // Svenska +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"Formaterade %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"Oförändrade %s\n"); // should align with formatted + addPair("Directory %s\n", L"Katalog %s\n"); + addPair("Exclude %s\n", L"Uteslut %s\n"); + addPair("Exclude (unmatched) %s\n", L"Uteslut (oöverträffad) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s formaterade %s oförändrade "); + addPair(" seconds ", L" sekunder "); + addPair("%d min %d sec ", L"%d min %d sek "); + addPair("%s lines\n", L"%s linjer\n"); + addPair("Using default options file %s\n", L"Använda standardalternativ fil %s\n"); + addPair("Opening HTML documentation %s\n", L"Öppna HTML-dokumentation %s\n"); + addPair("Invalid option file options:", L"Ogiltigt alternativ fil alternativ:"); + addPair("Invalid command line options:", L"Ogiltig kommandoraden alternativ:"); + addPair("For help on options type 'astyle -h'", L"För hjälp om alternativ typ 'astyle -h'"); + addPair("Cannot open options file", L"Kan inte öppna inställningsfilen"); + addPair("Cannot open directory", L"Kan inte öppna katalog"); + addPair("Cannot open HTML file %s\n", L"Kan inte öppna HTML-filen %s\n"); + addPair("Command execute failure", L"Utför kommando misslyckande"); + addPair("Command is not installed", L"Kommandot är inte installerat"); + addPair("Missing filename in %s\n", L"Saknade filnamn i %s\n"); + addPair("Recursive option with no wildcard", L"Rekursiva alternativ utan jokertecken"); + addPair("Did you intend quote the filename", L"Visste du tänker citera filnamnet"); + addPair("No file to process %s\n", L"Ingen fil att bearbeta %s\n"); + addPair("Did you intend to use --recursive", L"Har du för avsikt att använda --recursive"); + addPair("Cannot process UTF-32 encoding", L"Kan inte hantera UTF-32 kodning"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style har upphört"); +} + +Ukrainian::Ukrainian() // Український +// build the translation vector in the Translation base class +{ + addPair("Formatted %s\n", L"форматований %s\n"); // should align with unchanged + addPair("Unchanged %s\n", L"без змін %s\n"); // should align with formatted + addPair("Directory %s\n", L"Каталог %s\n"); + addPair("Exclude %s\n", L"Виключити %s\n"); + addPair("Exclude (unmatched) %s\n", L"Виключити (неперевершений) %s\n"); + addPair(" %s formatted %s unchanged ", L" %s відформатований %s без змін "); + addPair(" seconds ", L" секунди "); + addPair("%d min %d sec ", L"%d хви %d cek "); + addPair("%s lines\n", L"%s ліній\n"); + addPair("Using default options file %s\n", L"Використання файлів опцій за замовчуванням %s\n"); + addPair("Opening HTML documentation %s\n", L"Відкриття HTML документації %s\n"); + addPair("Invalid option file options:", L"Неприпустимий файл опцій опцію:"); + addPair("Invalid command line options:", L"Неприпустима параметри командного рядка:"); + addPair("For help on options type 'astyle -h'", L"Для отримання довідки по 'astyle -h' опцій типу"); + addPair("Cannot open options file", L"Не вдається відкрити файл параметрів"); + addPair("Cannot open directory", L"Не можу відкрити каталог"); + addPair("Cannot open HTML file %s\n", L"Не вдається відкрити файл HTML %s\n"); + addPair("Command execute failure", L"Виконати команду недостатності"); + addPair("Command is not installed", L"Не встановлений Команда"); + addPair("Missing filename in %s\n", L"Відсутня назва файлу в %s\n"); + addPair("Recursive option with no wildcard", L"Рекурсивний варіант без будь-яких шаблону"); + addPair("Did you intend quote the filename", L"Ви маєте намір цитатою файлу"); + addPair("No file to process %s\n", L"Немає файлів для обробки %s\n"); + addPair("Did you intend to use --recursive", L"Невже ви збираєтеся використовувати --recursive"); + addPair("Cannot process UTF-32 encoding", L"Не вдається обробити UTF-32 кодуванні"); + addPair("\nArtistic Style has terminated", L"\nArtistic Style припинив"); +} + + +#endif // ASTYLE_LIB + +} // end of namespace astyle + diff --git a/External/Tools/AStyle/src/ASLocalizer.h b/External/Tools/AStyle/src/ASLocalizer.h new file mode 100644 index 0000000000..eb6a9f3b4c --- /dev/null +++ b/External/Tools/AStyle/src/ASLocalizer.h @@ -0,0 +1,189 @@ +// ASLocalizer.h +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. +// License.txt describes the conditions under which this software may be distributed. + + +#ifndef ASLOCALIZER_H +#define ASLOCALIZER_H + +#include +#include + +namespace astyle { + +using namespace std; + +#ifndef ASTYLE_LIB + +//----------------------------------------------------------------------------- +// ASLocalizer class for console build. +// This class encapsulates all language-dependent settings and is a +// generalization of the C locale concept. +//----------------------------------------------------------------------------- +class Translation; + +class ASLocalizer +{ +public: // functions + ASLocalizer(); + virtual ~ASLocalizer(); + string getLanguageID() const; + const Translation* getTranslationClass() const; +#ifdef _WIN32 + void setLanguageFromLCID(size_t lcid); +#endif + void setLanguageFromName(const char* langID); + const char* settext(const char* textIn) const; + +private: // functions + void setTranslationClass(); + +private: // variables + Translation* m_translation; // pointer to a polymorphic Translation class + string m_langID; // language identifier from the locale + string m_subLangID; // sub language identifier, if needed + string m_localeName; // name of the current locale (Linux only) + size_t m_lcid; // LCID of the user locale (Windows only) +}; + +//---------------------------------------------------------------------------- +// Translation base class. +//---------------------------------------------------------------------------- + +class Translation +// This base class is inherited by the language translation classes. +// Polymorphism is used to call the correct language translator. +// This class contains the translation vector and settext translation method. +// The language vector is built by the language sub classes. +// NOTE: This class must have virtual methods for typeid() to work. +// typeid() is used by AStyleTestI18n_Localizer.cpp. +{ +public: + Translation() {} + virtual ~Translation() {} + string convertToMultiByte(const wstring& wideStr) const; + size_t getTranslationVectorSize() const; + bool getWideTranslation(const string& stringIn, wstring& wideOut) const; + string& translate(const string& stringIn) const; + +protected: + void addPair(const string& english, const wstring& translated); + // variables + vector > m_translation; // translation vector +}; + +//---------------------------------------------------------------------------- +// Translation classes +// One class for each language. +// These classes have only a constructor which builds the language vector. +//---------------------------------------------------------------------------- + +class ChineseSimplified : public Translation +{ +public: + ChineseSimplified(); +}; + +class ChineseTraditional : public Translation +{ +public: + ChineseTraditional(); +}; + +class Dutch : public Translation +{ +public: + Dutch(); +}; + +class English : public Translation +{ +public: + English(); +}; + +class Finnish : public Translation +{ +public: + Finnish(); +}; + +class French : public Translation +{ +public: + French(); +}; + +class German : public Translation +{ +public: + German(); +}; + +class Hindi : public Translation +{ +public: + Hindi(); +}; + +class Italian : public Translation +{ +public: + Italian(); +}; + +class Japanese : public Translation +{ +public: + Japanese(); +}; + +class Korean : public Translation +{ +public: + Korean(); +}; + +class Polish : public Translation +{ +public: + Polish(); +}; + +class Portuguese : public Translation +{ +public: + Portuguese(); +}; + +class Russian : public Translation +{ +public: + Russian(); +}; + +class Spanish : public Translation +{ +public: + Spanish(); +}; + +class Swedish : public Translation +{ +public: + Swedish(); +}; + +class Ukrainian : public Translation +{ +public: + Ukrainian(); +}; + + +#endif // ASTYLE_LIB + +} // namespace astyle + +#endif // ASLOCALIZER_H diff --git a/External/Tools/AStyle/src/ASResource.cpp b/External/Tools/AStyle/src/ASResource.cpp new file mode 100644 index 0000000000..012d2dba41 --- /dev/null +++ b/External/Tools/AStyle/src/ASResource.cpp @@ -0,0 +1,667 @@ +// ASResource.cpp +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. +// License.txt describes the conditions under which this software may be distributed. + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- + +#include "astyle.h" +#include + +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- + +namespace astyle { +// +const string ASResource::AS_IF = string("if"); +const string ASResource::AS_ELSE = string("else"); +const string ASResource::AS_FOR = string("for"); +const string ASResource::AS_DO = string("do"); +const string ASResource::AS_WHILE = string("while"); +const string ASResource::AS_SWITCH = string("switch"); +const string ASResource::AS_CASE = string("case"); +const string ASResource::AS_DEFAULT = string("default"); +const string ASResource::AS_CLASS = string("class"); +const string ASResource::AS_VOLATILE = string("volatile"); +const string ASResource::AS_INTERRUPT = string("interrupt"); +const string ASResource::AS_NOEXCEPT = string("noexcept"); +const string ASResource::AS_AUTORELEASEPOOL = string("autoreleasepool"); +const string ASResource::AS_STRUCT = string("struct"); +const string ASResource::AS_UNION = string("union"); +const string ASResource::AS_INTERFACE = string("interface"); +const string ASResource::AS_NAMESPACE = string("namespace"); +const string ASResource::AS_END = string("end"); +const string ASResource::AS_SELECTOR = string("selector"); +const string ASResource::AS_EXTERN = string("extern"); +const string ASResource::AS_ENUM = string("enum"); +const string ASResource::AS_PUBLIC = string("public"); +const string ASResource::AS_PROTECTED = string("protected"); +const string ASResource::AS_PRIVATE = string("private"); +const string ASResource::AS_STATIC = string("static"); +const string ASResource::AS_SYNCHRONIZED = string("synchronized"); +const string ASResource::AS_OPERATOR = string("operator"); +const string ASResource::AS_TEMPLATE = string("template"); +const string ASResource::AS_TRY = string("try"); +const string ASResource::AS_CATCH = string("catch"); +const string ASResource::AS_THROW = string("throw"); +const string ASResource::AS_FINALLY = string("finally"); +const string ASResource::AS_USING = string("using"); +const string ASResource::_AS_TRY = string("__try"); +const string ASResource::_AS_FINALLY = string("__finally"); +const string ASResource::_AS_EXCEPT = string("__except"); +const string ASResource::AS_THROWS = string("throws"); +const string ASResource::AS_CONST = string("const"); +const string ASResource::AS_SEALED = string("sealed"); +const string ASResource::AS_OVERRIDE = string("override"); +const string ASResource::AS_WHERE = string("where"); +const string ASResource::AS_LET = string("let"); +const string ASResource::AS_NEW = string("new"); + +const string ASResource::AS_ASM = string("asm"); +const string ASResource::AS__ASM__ = string("__asm__"); +const string ASResource::AS_MS_ASM = string("_asm"); +const string ASResource::AS_MS__ASM = string("__asm"); + +const string ASResource::AS_BAR_DEFINE = string("#define"); +const string ASResource::AS_BAR_INCLUDE = string("#include"); +const string ASResource::AS_BAR_IF = string("#if"); +const string ASResource::AS_BAR_EL = string("#el"); +const string ASResource::AS_BAR_ENDIF = string("#endif"); + +const string ASResource::AS_OPEN_BRACKET = string("{"); +const string ASResource::AS_CLOSE_BRACKET = string("}"); +const string ASResource::AS_OPEN_LINE_COMMENT = string("//"); +const string ASResource::AS_OPEN_COMMENT = string("/*"); +const string ASResource::AS_CLOSE_COMMENT = string("*/"); + +const string ASResource::AS_ASSIGN = string("="); +const string ASResource::AS_PLUS_ASSIGN = string("+="); +const string ASResource::AS_MINUS_ASSIGN = string("-="); +const string ASResource::AS_MULT_ASSIGN = string("*="); +const string ASResource::AS_DIV_ASSIGN = string("/="); +const string ASResource::AS_MOD_ASSIGN = string("%="); +const string ASResource::AS_OR_ASSIGN = string("|="); +const string ASResource::AS_AND_ASSIGN = string("&="); +const string ASResource::AS_XOR_ASSIGN = string("^="); +const string ASResource::AS_GR_GR_ASSIGN = string(">>="); +const string ASResource::AS_LS_LS_ASSIGN = string("<<="); +const string ASResource::AS_GR_GR_GR_ASSIGN = string(">>>="); +const string ASResource::AS_LS_LS_LS_ASSIGN = string("<<<="); +const string ASResource::AS_GCC_MIN_ASSIGN = string("?"); + +const string ASResource::AS_RETURN = string("return"); +const string ASResource::AS_CIN = string("cin"); +const string ASResource::AS_COUT = string("cout"); +const string ASResource::AS_CERR = string("cerr"); + +const string ASResource::AS_EQUAL = string("=="); +const string ASResource::AS_PLUS_PLUS = string("++"); +const string ASResource::AS_MINUS_MINUS = string("--"); +const string ASResource::AS_NOT_EQUAL = string("!="); +const string ASResource::AS_GR_EQUAL = string(">="); +const string ASResource::AS_GR_GR = string(">>"); +const string ASResource::AS_GR_GR_GR = string(">>>"); +const string ASResource::AS_LS_EQUAL = string("<="); +const string ASResource::AS_LS_LS = string("<<"); +const string ASResource::AS_LS_LS_LS = string("<<<"); +const string ASResource::AS_QUESTION_QUESTION = string("??"); +const string ASResource::AS_LAMBDA = string("=>"); // C# lambda expression arrow +const string ASResource::AS_ARROW = string("->"); +const string ASResource::AS_AND = string("&&"); +const string ASResource::AS_OR = string("||"); +const string ASResource::AS_SCOPE_RESOLUTION = string("::"); + +const string ASResource::AS_PLUS = string("+"); +const string ASResource::AS_MINUS = string("-"); +const string ASResource::AS_MULT = string("*"); +const string ASResource::AS_DIV = string("/"); +const string ASResource::AS_MOD = string("%"); +const string ASResource::AS_GR = string(">"); +const string ASResource::AS_LS = string("<"); +const string ASResource::AS_NOT = string("!"); +const string ASResource::AS_BIT_OR = string("|"); +const string ASResource::AS_BIT_AND = string("&"); +const string ASResource::AS_BIT_NOT = string("~"); +const string ASResource::AS_BIT_XOR = string("^"); +const string ASResource::AS_QUESTION = string("?"); +const string ASResource::AS_COLON = string(":"); +const string ASResource::AS_COMMA = string(","); +const string ASResource::AS_SEMICOLON = string(";"); + +const string ASResource::AS_QFOREACH = string("Q_FOREACH"); +const string ASResource::AS_QFOREVER = string("Q_FOREVER"); +const string ASResource::AS_FOREVER = string("forever"); +const string ASResource::AS_FOREACH = string("foreach"); +const string ASResource::AS_LOCK = string("lock"); +const string ASResource::AS_UNSAFE = string("unsafe"); +const string ASResource::AS_FIXED = string("fixed"); +const string ASResource::AS_GET = string("get"); +const string ASResource::AS_SET = string("set"); +const string ASResource::AS_ADD = string("add"); +const string ASResource::AS_REMOVE = string("remove"); +const string ASResource::AS_DELEGATE = string("delegate"); +const string ASResource::AS_UNCHECKED = string("unchecked"); + +const string ASResource::AS_CONST_CAST = string("const_cast"); +const string ASResource::AS_DYNAMIC_CAST = string("dynamic_cast"); +const string ASResource::AS_REINTERPRET_CAST = string("reinterpret_cast"); +const string ASResource::AS_STATIC_CAST = string("static_cast"); + +const string ASResource::AS_NS_DURING = string("NS_DURING"); +const string ASResource::AS_NS_HANDLER = string("NS_HANDLER"); + +/** + * Sort comparison function. + * Compares the length of the value of pointers in the vectors. + * The LONGEST strings will be first in the vector. + * + * @param a and b, the string pointers to be compared. + */ +bool sortOnLength(const string* a, const string* b) +{ + return (*a).length() > (*b).length(); +} + +/** + * Sort comparison function. + * Compares the value of pointers in the vectors. + * + * @param a and b, the string pointers to be compared. + */ +bool sortOnName(const string* a, const string* b) +{ + return *a < *b; +} + +/** + * Build the vector of assignment operators. + * Used by BOTH ASFormatter.cpp and ASBeautifier.cpp + * + * @param assignmentOperators a reference to the vector to be built. + */ +void ASResource::buildAssignmentOperators(vector* assignmentOperators) +{ + assignmentOperators->push_back(&AS_ASSIGN); + assignmentOperators->push_back(&AS_PLUS_ASSIGN); + assignmentOperators->push_back(&AS_MINUS_ASSIGN); + assignmentOperators->push_back(&AS_MULT_ASSIGN); + assignmentOperators->push_back(&AS_DIV_ASSIGN); + assignmentOperators->push_back(&AS_MOD_ASSIGN); + assignmentOperators->push_back(&AS_OR_ASSIGN); + assignmentOperators->push_back(&AS_AND_ASSIGN); + assignmentOperators->push_back(&AS_XOR_ASSIGN); + + // Java + assignmentOperators->push_back(&AS_GR_GR_GR_ASSIGN); + assignmentOperators->push_back(&AS_GR_GR_ASSIGN); + assignmentOperators->push_back(&AS_LS_LS_ASSIGN); + + // Unknown + assignmentOperators->push_back(&AS_LS_LS_LS_ASSIGN); + + sort(assignmentOperators->begin(), assignmentOperators->end(), sortOnLength); +} + +/** + * Build the vector of C++ cast operators. + * Used by ONLY ASFormatter.cpp + * + * @param castOperators a reference to the vector to be built. + */ +void ASResource::buildCastOperators(vector* castOperators) +{ + castOperators->push_back(&AS_CONST_CAST); + castOperators->push_back(&AS_DYNAMIC_CAST); + castOperators->push_back(&AS_REINTERPRET_CAST); + castOperators->push_back(&AS_STATIC_CAST); +} + +/** + * Build the vector of header words. + * Used by BOTH ASFormatter.cpp and ASBeautifier.cpp + * + * @param headers a reference to the vector to be built. + */ +void ASResource::buildHeaders(vector* headers, int fileType, bool beautifier) +{ + headers->push_back(&AS_IF); + headers->push_back(&AS_ELSE); + headers->push_back(&AS_FOR); + headers->push_back(&AS_WHILE); + headers->push_back(&AS_DO); + headers->push_back(&AS_SWITCH); + headers->push_back(&AS_CASE); + headers->push_back(&AS_DEFAULT); + headers->push_back(&AS_TRY); + headers->push_back(&AS_CATCH); + headers->push_back(&AS_QFOREACH); // QT + headers->push_back(&AS_QFOREVER); // QT + headers->push_back(&AS_FOREACH); // QT & C# + headers->push_back(&AS_FOREVER); // Qt & Boost + + if (fileType == C_TYPE) + { + headers->push_back(&_AS_TRY); // __try + headers->push_back(&_AS_FINALLY); // __finally + headers->push_back(&_AS_EXCEPT); // __except + } + if (fileType == JAVA_TYPE) + { + headers->push_back(&AS_FINALLY); + headers->push_back(&AS_SYNCHRONIZED); + } + + if (fileType == SHARP_TYPE) + { + headers->push_back(&AS_FINALLY); + headers->push_back(&AS_LOCK); + headers->push_back(&AS_FIXED); + headers->push_back(&AS_GET); + headers->push_back(&AS_SET); + headers->push_back(&AS_ADD); + headers->push_back(&AS_REMOVE); + headers->push_back(&AS_USING); + } + + if (beautifier) + { + if (fileType == C_TYPE) + { + headers->push_back(&AS_TEMPLATE); + } + + if (fileType == JAVA_TYPE) + { + headers->push_back(&AS_STATIC); // for static constructor + } + } + sort(headers->begin(), headers->end(), sortOnName); +} + +/** + * Build the vector of indentable headers. + * Used by ONLY ASBeautifier.cpp + * + * @param indentableHeaders a reference to the vector to be built. + */ +void ASResource::buildIndentableHeaders(vector* indentableHeaders) +{ + indentableHeaders->push_back(&AS_RETURN); + + sort(indentableHeaders->begin(), indentableHeaders->end(), sortOnName); +} + +/** +* Build the vector of indentable macros pairs. +* Initialized by ASFormatter, used by ONLY ASEnhancer.cpp +* +* @param indentableMacros a reference to the vector to be built. +*/ +void ASResource::buildIndentableMacros(vector* >* indentableMacros) +{ + typedef pair macro_pair; + + // the pairs must be retained in memory + static const macro_pair macros[] = + { + // wxWidgets + macro_pair("BEGIN_EVENT_TABLE", "END_EVENT_TABLE"), + macro_pair("wxBEGIN_EVENT_TABLE", "wxEND_EVENT_TABLE"), + // MFC + macro_pair("BEGIN_DISPATCH_MAP", "END_DISPATCH_MAP"), + macro_pair("BEGIN_EVENT_MAP", "END_EVENT_MAP"), + macro_pair("BEGIN_MESSAGE_MAP", "END_MESSAGE_MAP"), + macro_pair("BEGIN_PROPPAGEIDS", "END_PROPPAGEIDS"), + }; + + size_t elements = sizeof(macros) / sizeof(macros[0]); + for (size_t i = 0; i < elements; i++) + indentableMacros->push_back(¯os[i]); +} + +/** + * Build the vector of non-assignment operators. + * Used by ONLY ASBeautifier.cpp + * + * @param nonAssignmentOperators a reference to the vector to be built. + */ +void ASResource::buildNonAssignmentOperators(vector* nonAssignmentOperators) +{ + nonAssignmentOperators->push_back(&AS_EQUAL); + nonAssignmentOperators->push_back(&AS_PLUS_PLUS); + nonAssignmentOperators->push_back(&AS_MINUS_MINUS); + nonAssignmentOperators->push_back(&AS_NOT_EQUAL); + nonAssignmentOperators->push_back(&AS_GR_EQUAL); + nonAssignmentOperators->push_back(&AS_GR_GR_GR); + nonAssignmentOperators->push_back(&AS_GR_GR); + nonAssignmentOperators->push_back(&AS_LS_EQUAL); + nonAssignmentOperators->push_back(&AS_LS_LS_LS); + nonAssignmentOperators->push_back(&AS_LS_LS); + nonAssignmentOperators->push_back(&AS_ARROW); + nonAssignmentOperators->push_back(&AS_AND); + nonAssignmentOperators->push_back(&AS_OR); + nonAssignmentOperators->push_back(&AS_LAMBDA); + + sort(nonAssignmentOperators->begin(), nonAssignmentOperators->end(), sortOnLength); +} + +/** + * Build the vector of header non-paren headers. + * Used by BOTH ASFormatter.cpp and ASBeautifier.cpp. + * NOTE: Non-paren headers should also be included in the headers vector. + * + * @param nonParenHeaders a reference to the vector to be built. + */ +void ASResource::buildNonParenHeaders(vector* nonParenHeaders, int fileType, bool beautifier) +{ + nonParenHeaders->push_back(&AS_ELSE); + nonParenHeaders->push_back(&AS_DO); + nonParenHeaders->push_back(&AS_TRY); + nonParenHeaders->push_back(&AS_CATCH); // can be paren or non-paren + nonParenHeaders->push_back(&AS_CASE); // can be paren or non-paren + nonParenHeaders->push_back(&AS_DEFAULT); + nonParenHeaders->push_back(&AS_QFOREVER); // QT + nonParenHeaders->push_back(&AS_FOREVER); // Boost + + if (fileType == C_TYPE) + { + nonParenHeaders->push_back(&_AS_TRY); // __try + nonParenHeaders->push_back(&_AS_FINALLY); // __finally + } + if (fileType == JAVA_TYPE) + { + nonParenHeaders->push_back(&AS_FINALLY); + } + + if (fileType == SHARP_TYPE) + { + nonParenHeaders->push_back(&AS_FINALLY); + nonParenHeaders->push_back(&AS_GET); + nonParenHeaders->push_back(&AS_SET); + nonParenHeaders->push_back(&AS_ADD); + nonParenHeaders->push_back(&AS_REMOVE); + } + + if (beautifier) + { + if (fileType == C_TYPE) + { + nonParenHeaders->push_back(&AS_TEMPLATE); + } + if (fileType == JAVA_TYPE) + { + nonParenHeaders->push_back(&AS_STATIC); + } + } + sort(nonParenHeaders->begin(), nonParenHeaders->end(), sortOnName); +} + +/** + * Build the vector of operators. + * Used by ONLY ASFormatter.cpp + * + * @param operators a reference to the vector to be built. + */ +void ASResource::buildOperators(vector* operators, int fileType) +{ + operators->push_back(&AS_PLUS_ASSIGN); + operators->push_back(&AS_MINUS_ASSIGN); + operators->push_back(&AS_MULT_ASSIGN); + operators->push_back(&AS_DIV_ASSIGN); + operators->push_back(&AS_MOD_ASSIGN); + operators->push_back(&AS_OR_ASSIGN); + operators->push_back(&AS_AND_ASSIGN); + operators->push_back(&AS_XOR_ASSIGN); + operators->push_back(&AS_EQUAL); + operators->push_back(&AS_PLUS_PLUS); + operators->push_back(&AS_MINUS_MINUS); + operators->push_back(&AS_NOT_EQUAL); + operators->push_back(&AS_GR_EQUAL); + operators->push_back(&AS_GR_GR_GR_ASSIGN); + operators->push_back(&AS_GR_GR_ASSIGN); + operators->push_back(&AS_GR_GR_GR); + operators->push_back(&AS_GR_GR); + operators->push_back(&AS_LS_EQUAL); + operators->push_back(&AS_LS_LS_LS_ASSIGN); + operators->push_back(&AS_LS_LS_ASSIGN); + operators->push_back(&AS_LS_LS_LS); + operators->push_back(&AS_LS_LS); + operators->push_back(&AS_QUESTION_QUESTION); + operators->push_back(&AS_LAMBDA); + operators->push_back(&AS_ARROW); + operators->push_back(&AS_AND); + operators->push_back(&AS_OR); + operators->push_back(&AS_SCOPE_RESOLUTION); + operators->push_back(&AS_PLUS); + operators->push_back(&AS_MINUS); + operators->push_back(&AS_MULT); + operators->push_back(&AS_DIV); + operators->push_back(&AS_MOD); + operators->push_back(&AS_QUESTION); + operators->push_back(&AS_COLON); + operators->push_back(&AS_ASSIGN); + operators->push_back(&AS_LS); + operators->push_back(&AS_GR); + operators->push_back(&AS_NOT); + operators->push_back(&AS_BIT_OR); + operators->push_back(&AS_BIT_AND); + operators->push_back(&AS_BIT_NOT); + operators->push_back(&AS_BIT_XOR); + if (fileType == C_TYPE) + { + operators->push_back(&AS_GCC_MIN_ASSIGN); + operators->push_back(&AS_GCC_MAX_ASSIGN); + } + sort(operators->begin(), operators->end(), sortOnLength); +} + +/** + * Build the vector of pre-block statements. + * Used by ONLY ASBeautifier.cpp + * NOTE: Cannot be both a header and a preBlockStatement. + * + * @param preBlockStatements a reference to the vector to be built. + */ +void ASResource::buildPreBlockStatements(vector* preBlockStatements, int fileType) +{ + preBlockStatements->push_back(&AS_CLASS); + if (fileType == C_TYPE) + { + preBlockStatements->push_back(&AS_STRUCT); + preBlockStatements->push_back(&AS_UNION); + preBlockStatements->push_back(&AS_NAMESPACE); + } + if (fileType == JAVA_TYPE) + { + preBlockStatements->push_back(&AS_INTERFACE); + preBlockStatements->push_back(&AS_THROWS); + } + if (fileType == SHARP_TYPE) + { + preBlockStatements->push_back(&AS_INTERFACE); + preBlockStatements->push_back(&AS_NAMESPACE); + preBlockStatements->push_back(&AS_WHERE); + preBlockStatements->push_back(&AS_STRUCT); + } + sort(preBlockStatements->begin(), preBlockStatements->end(), sortOnName); +} + +/** + * Build the vector of pre-command headers. + * Used by BOTH ASFormatter.cpp and ASBeautifier.cpp. + * NOTE: Cannot be both a header and a preCommandHeader. + * + * A preCommandHeader is in a function definition between + * the closing paren and the opening bracket. + * e.g. in "void foo() const {}", "const" is a preCommandHeader. + */ +void ASResource::buildPreCommandHeaders(vector* preCommandHeaders, int fileType) +{ + if (fileType == C_TYPE) + { + preCommandHeaders->push_back(&AS_CONST); + preCommandHeaders->push_back(&AS_VOLATILE); + preCommandHeaders->push_back(&AS_INTERRUPT); + preCommandHeaders->push_back(&AS_NOEXCEPT); + preCommandHeaders->push_back(&AS_OVERRIDE); + preCommandHeaders->push_back(&AS_SEALED); // Visual C only + preCommandHeaders->push_back(&AS_AUTORELEASEPOOL); // Obj-C only + } + + if (fileType == JAVA_TYPE) + { + preCommandHeaders->push_back(&AS_THROWS); + } + + if (fileType == SHARP_TYPE) + { + preCommandHeaders->push_back(&AS_WHERE); + } + + sort(preCommandHeaders->begin(), preCommandHeaders->end(), sortOnName); +} + +/** + * Build the vector of pre-definition headers. + * Used by ONLY ASFormatter.cpp + * NOTE: Do NOT add 'enum' here. It is an array type bracket. + * NOTE: Do NOT add 'extern' here. Do not want an extra indent. + * + * @param preDefinitionHeaders a reference to the vector to be built. + */ +void ASResource::buildPreDefinitionHeaders(vector* preDefinitionHeaders, int fileType) +{ + preDefinitionHeaders->push_back(&AS_CLASS); + if (fileType == C_TYPE) + { + preDefinitionHeaders->push_back(&AS_STRUCT); + preDefinitionHeaders->push_back(&AS_UNION); + preDefinitionHeaders->push_back(&AS_NAMESPACE); + } + if (fileType == JAVA_TYPE) + { + preDefinitionHeaders->push_back(&AS_INTERFACE); + } + if (fileType == SHARP_TYPE) + { + preDefinitionHeaders->push_back(&AS_STRUCT); + preDefinitionHeaders->push_back(&AS_INTERFACE); + preDefinitionHeaders->push_back(&AS_NAMESPACE); + } + sort(preDefinitionHeaders->begin(), preDefinitionHeaders->end(), sortOnName); +} + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * ASBase Functions + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +// check if a specific line position contains a keyword. +bool ASBase::findKeyword(const string& line, int i, const string& keyword) const +{ + assert(isCharPotentialHeader(line, i)); + // check the word + const size_t keywordLength = keyword.length(); + const size_t wordEnd = i + keywordLength; + if (wordEnd > line.length()) + return false; + if (line.compare(i, keywordLength, keyword) != 0) + return false; + // check that this is not part of a longer word + if (wordEnd == line.length()) + return true; + if (isLegalNameChar(line[wordEnd])) + return false; + // is not a keyword if part of a definition + const char peekChar = peekNextChar(line, wordEnd - 1); + if (peekChar == ',' || peekChar == ')') + return false; + return true; +} + +// get the current word on a line +// index must point to the beginning of the word +string ASBase::getCurrentWord(const string& line, size_t index) const +{ + assert(isCharPotentialHeader(line, index)); + size_t lineLength = line.length(); + size_t i; + for (i = index; i < lineLength; i++) + { + if (!isLegalNameChar(line[i])) + break; + } + return line.substr(index, i - index); +} + +// check if a specific character can be used in a legal variable/method/class name +bool ASBase::isLegalNameChar(char ch) const +{ + if (isWhiteSpace(ch)) return false; + if ((unsigned) ch > 127) return false; + return (isalnum((unsigned char) ch) + || ch == '.' || ch == '_' + || (isJavaStyle() && ch == '$') + || (isSharpStyle() && ch == '@')); // may be used as a prefix +} + +// check if a specific character can be part of a header +bool ASBase::isCharPotentialHeader(const string& line, size_t i) const +{ + assert(!isWhiteSpace(line[i])); + char prevCh = ' '; + if (i > 0) prevCh = line[i - 1]; + if (!isLegalNameChar(prevCh) && isLegalNameChar(line[i])) + return true; + return false; +} + +// check if a specific character can be part of an operator +bool ASBase::isCharPotentialOperator(char ch) const +{ + assert(!isWhiteSpace(ch)); + if ((unsigned) ch > 127) return false; + return (ispunct((unsigned char) ch) + && ch != '{' && ch != '}' + && ch != '(' && ch != ')' + && ch != '[' && ch != ']' + && ch != ';' && ch != ',' + && ch != '#' && ch != '\\' + && ch != '\'' && ch != '\"'); +} + +// check if a specific character is a digit +// NOTE: Visual C isdigit() gives assert error if char > 256 +bool ASBase::isDigit(char ch) const +{ + return (ch >= '0' && ch <= '9'); +} + +// check if a specific character is a digit separator +bool ASBase::isDigitSeparator(const string& line, int i) const +{ + assert(line[i] == '\''); + // casting to (unsigned char) eliminates negative characters + // will get a "Debug Assertion Failed" if not cast + bool foundDigitSeparator = i > 0 + && isxdigit((unsigned char) line[i - 1]) + && i < (int) line.length() - 1 + && isxdigit((unsigned char) line[i + 1]); + return foundDigitSeparator; +} + +// peek at the next unread character. +char ASBase::peekNextChar(const string& line, int i) const +{ + char ch = ' '; + size_t peekNum = line.find_first_not_of(" \t", i + 1); + if (peekNum == string::npos) + return ch; + ch = line[peekNum]; + return ch; +} + +} // end namespace astyle diff --git a/External/Tools/AStyle/src/astyle.h b/External/Tools/AStyle/src/astyle.h new file mode 100644 index 0000000000..2c667a3cfb --- /dev/null +++ b/External/Tools/AStyle/src/astyle.h @@ -0,0 +1,996 @@ +// astyle.h +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. +// License.txt describes the conditions under which this software may be distributed. + +#ifndef ASTYLE_H +#define ASTYLE_H + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- + +#ifdef __VMS + #define __USE_STD_IOSTREAM 1 + #include +#else + #include +#endif + +#include +#include // for cout +#include +#include + +//----------------------------------------------------------------------------- +// declarations +//----------------------------------------------------------------------------- + +#ifdef __GNUC__ + #include // need both string and string.h for GCC +#endif + +#ifdef _MSC_VER + #pragma warning(disable: 4267) // conversion from size_t to int + #pragma warning(disable: 4996) // secure version deprecation warnings +#endif + +#ifdef __BORLANDC__ + #pragma warn -8004 // variable is assigned a value that is never used +#endif + +#ifdef __INTEL_COMPILER + #pragma warning(disable: 383) // value copied to temporary, reference to temporary used + #pragma warning(disable: 981) // operands are evaluated in unspecified order +#endif + +#ifdef __clang__ + #pragma clang diagnostic ignored "-Wdeprecated-declarations" // strcpy, getenv + #pragma clang diagnostic ignored "-Wshorten-64-to-32" +#endif + +//----------------------------------------------------------------------------- +// astyle namespace +//----------------------------------------------------------------------------- + +namespace astyle { +// +using namespace std; + +//---------------------------------------------------------------------------- +// definitions +//---------------------------------------------------------------------------- + +enum FileType { C_TYPE = 0, JAVA_TYPE = 1, SHARP_TYPE = 2 }; + +/* The enums below are not recognized by 'vectors' in Microsoft Visual C++ + V5 when they are part of a namespace!!! Use Visual C++ V6 or higher. +*/ +enum FormatStyle +{ + STYLE_NONE, + STYLE_ALLMAN, + STYLE_JAVA, + STYLE_KR, + STYLE_STROUSTRUP, + STYLE_WHITESMITH, + STYLE_VTK, + STYLE_BANNER, + STYLE_GNU, + STYLE_LINUX, + STYLE_HORSTMANN, + STYLE_1TBS, + STYLE_GOOGLE, + STYLE_PICO, + STYLE_LISP +}; + +enum BracketMode +{ + NONE_MODE, + ATTACH_MODE, + BREAK_MODE, + LINUX_MODE, + STROUSTRUP_MODE, + RUN_IN_MODE +}; + +enum BracketType +{ + NULL_TYPE = 0, + NAMESPACE_TYPE = 1, // also a DEFINITION_TYPE + CLASS_TYPE = 2, // also a DEFINITION_TYPE + STRUCT_TYPE = 4, // also a DEFINITION_TYPE + INTERFACE_TYPE = 8, // also a DEFINITION_TYPE + DEFINITION_TYPE = 16, + COMMAND_TYPE = 32, + ARRAY_NIS_TYPE = 64, // also an ARRAY_TYPE + ENUM_TYPE = 128, // also an ARRAY_TYPE + INIT_TYPE = 256, // also an ARRAY_TYPE + ARRAY_TYPE = 512, + EXTERN_TYPE = 1024, // extern "C", not a command type extern + SINGLE_LINE_TYPE = 2048 +}; + +enum MinConditional +{ + MINCOND_ZERO, + MINCOND_ONE, + MINCOND_TWO, + MINCOND_ONEHALF, + MINCOND_END +}; + +enum ObjCColonPad +{ + COLON_PAD_NO_CHANGE, + COLON_PAD_NONE, + COLON_PAD_ALL, + COLON_PAD_AFTER, + COLON_PAD_BEFORE +}; + +enum PointerAlign +{ + PTR_ALIGN_NONE, + PTR_ALIGN_TYPE, + PTR_ALIGN_MIDDLE, + PTR_ALIGN_NAME +}; + +enum ReferenceAlign +{ + REF_ALIGN_NONE = PTR_ALIGN_NONE, + REF_ALIGN_TYPE = PTR_ALIGN_TYPE, + REF_ALIGN_MIDDLE = PTR_ALIGN_MIDDLE, + REF_ALIGN_NAME = PTR_ALIGN_NAME, + REF_SAME_AS_PTR +}; + +enum FileEncoding +{ + ENCODING_8BIT, + UTF_16BE, + UTF_16LE, // Windows default + UTF_32BE, + UTF_32LE +}; + +enum LineEndFormat +{ + LINEEND_DEFAULT, // Use line break that matches most of the file + LINEEND_WINDOWS, + LINEEND_LINUX, + LINEEND_MACOLD, + LINEEND_CRLF = LINEEND_WINDOWS, + LINEEND_LF = LINEEND_LINUX, + LINEEND_CR = LINEEND_MACOLD +}; + +//----------------------------------------------------------------------------- +// Class ASSourceIterator +// A pure virtual class is used by ASFormatter and ASBeautifier instead of +// ASStreamIterator. This allows programs using AStyle as a plug-in to define +// their own ASStreamIterator. The ASStreamIterator class must inherit +// this class. +//----------------------------------------------------------------------------- + +class ASSourceIterator +{ +public: + ASSourceIterator() {} + virtual ~ASSourceIterator() {} + virtual int getStreamLength() const = 0; + virtual bool hasMoreLines() const = 0; + virtual string nextLine(bool emptyLineWasDeleted = false) = 0; + virtual string peekNextLine() = 0; + virtual void peekReset() = 0; + virtual streamoff tellg() = 0; +}; + +//----------------------------------------------------------------------------- +// Class ASResource +//----------------------------------------------------------------------------- + +class ASResource +{ +public: + ASResource() {} + virtual ~ASResource() {} + void buildAssignmentOperators(vector* assignmentOperators); + void buildCastOperators(vector* castOperators); + void buildHeaders(vector* headers, int fileType, bool beautifier = false); + void buildIndentableMacros(vector* >* indentableMacros); + void buildIndentableHeaders(vector* indentableHeaders); + void buildNonAssignmentOperators(vector* nonAssignmentOperators); + void buildNonParenHeaders(vector* nonParenHeaders, int fileType, bool beautifier = false); + void buildOperators(vector* operators, int fileType); + void buildPreBlockStatements(vector* preBlockStatements, int fileType); + void buildPreCommandHeaders(vector* preCommandHeaders, int fileType); + void buildPreDefinitionHeaders(vector* preDefinitionHeaders, int fileType); + +public: + static const string AS_IF, AS_ELSE; + static const string AS_DO, AS_WHILE; + static const string AS_FOR; + static const string AS_SWITCH, AS_CASE, AS_DEFAULT; + static const string AS_TRY, AS_CATCH, AS_THROW, AS_THROWS, AS_FINALLY, AS_USING; + static const string _AS_TRY, _AS_FINALLY, _AS_EXCEPT; + static const string AS_PUBLIC, AS_PROTECTED, AS_PRIVATE; + static const string AS_CLASS, AS_STRUCT, AS_UNION, AS_INTERFACE, AS_NAMESPACE; + static const string AS_END; + static const string AS_SELECTOR; + static const string AS_EXTERN, AS_ENUM; + static const string AS_STATIC, AS_CONST, AS_SEALED, AS_OVERRIDE, AS_VOLATILE, AS_NEW; + static const string AS_NOEXCEPT, AS_INTERRUPT, AS_AUTORELEASEPOOL; + static const string AS_WHERE, AS_LET, AS_SYNCHRONIZED; + static const string AS_OPERATOR, AS_TEMPLATE; + static const string AS_OPEN_BRACKET, AS_CLOSE_BRACKET; + static const string AS_OPEN_LINE_COMMENT, AS_OPEN_COMMENT, AS_CLOSE_COMMENT; + static const string AS_BAR_DEFINE, AS_BAR_INCLUDE, AS_BAR_IF, AS_BAR_EL, AS_BAR_ENDIF; + static const string AS_RETURN; + static const string AS_CIN, AS_COUT, AS_CERR; + static const string AS_ASSIGN, AS_PLUS_ASSIGN, AS_MINUS_ASSIGN, AS_MULT_ASSIGN; + static const string AS_DIV_ASSIGN, AS_MOD_ASSIGN, AS_XOR_ASSIGN, AS_OR_ASSIGN, AS_AND_ASSIGN; + static const string AS_GR_GR_ASSIGN, AS_LS_LS_ASSIGN, AS_GR_GR_GR_ASSIGN, AS_LS_LS_LS_ASSIGN; + static const string AS_GCC_MIN_ASSIGN, AS_GCC_MAX_ASSIGN; + static const string AS_EQUAL, AS_PLUS_PLUS, AS_MINUS_MINUS, AS_NOT_EQUAL, AS_GR_EQUAL, AS_GR_GR_GR, AS_GR_GR; + static const string AS_LS_EQUAL, AS_LS_LS_LS, AS_LS_LS; + static const string AS_QUESTION_QUESTION, AS_LAMBDA; + static const string AS_ARROW, AS_AND, AS_OR; + static const string AS_SCOPE_RESOLUTION; + static const string AS_PLUS, AS_MINUS, AS_MULT, AS_DIV, AS_MOD, AS_GR, AS_LS; + static const string AS_NOT, AS_BIT_XOR, AS_BIT_OR, AS_BIT_AND, AS_BIT_NOT; + static const string AS_QUESTION, AS_COLON, AS_SEMICOLON, AS_COMMA; + static const string AS_ASM, AS__ASM__, AS_MS_ASM, AS_MS__ASM; + static const string AS_QFOREACH, AS_QFOREVER, AS_FOREVER; + static const string AS_FOREACH, AS_LOCK, AS_UNSAFE, AS_FIXED; + static const string AS_GET, AS_SET, AS_ADD, AS_REMOVE; + static const string AS_DELEGATE, AS_UNCHECKED; + static const string AS_CONST_CAST, AS_DYNAMIC_CAST, AS_REINTERPRET_CAST, AS_STATIC_CAST; + static const string AS_NS_DURING, AS_NS_HANDLER; +}; // Class ASResource + +//----------------------------------------------------------------------------- +// Class ASBase +// Functions definitions are at the end of ASResource.cpp. +//----------------------------------------------------------------------------- + +class ASBase +{ +private: + // all variables should be set by the "init" function + int baseFileType; // a value from enum FileType + +protected: + ASBase() : baseFileType(C_TYPE) { } + +protected: // inline functions + void init(int fileTypeArg) { baseFileType = fileTypeArg; } + bool isCStyle() const { return (baseFileType == C_TYPE); } + bool isJavaStyle() const { return (baseFileType == JAVA_TYPE); } + bool isSharpStyle() const { return (baseFileType == SHARP_TYPE); } + bool isWhiteSpace(char ch) const { return (ch == ' ' || ch == '\t'); } + +protected: // functions definitions are at the end of ASResource.cpp + bool findKeyword(const string& line, int i, const string& keyword) const; + string getCurrentWord(const string& line, size_t index) const; + bool isDigit(char ch) const; + bool isLegalNameChar(char ch) const; + bool isCharPotentialHeader(const string& line, size_t i) const; + bool isCharPotentialOperator(char ch) const; + bool isDigitSeparator(const string& line, int i) const; + char peekNextChar(const string& line, int i) const; + +}; // Class ASBase + +//----------------------------------------------------------------------------- +// Class ASBeautifier +//----------------------------------------------------------------------------- + +class ASBeautifier : protected ASResource, protected ASBase +{ +public: + ASBeautifier(); + virtual ~ASBeautifier(); + virtual void init(ASSourceIterator* iter); + virtual string beautify(const string& line); + void setCaseIndent(bool state); + void setClassIndent(bool state); + void setCStyle(); + void setDefaultTabLength(); + void setEmptyLineFill(bool state); + void setForceTabXIndentation(int length); + void setJavaStyle(); + void setLabelIndent(bool state); + void setMaxInStatementIndentLength(int max); + void setMinConditionalIndentOption(int min); + void setMinConditionalIndentLength(); + void setModeManuallySet(bool state); + void setModifierIndent(bool state); + void setNamespaceIndent(bool state); + void setAlignMethodColon(bool state); + void setSharpStyle(); + void setSpaceIndentation(int length = 4); + void setSwitchIndent(bool state); + void setTabIndentation(int length = 4, bool forceTabs = false); + void setPreprocDefineIndent(bool state); + void setPreprocConditionalIndent(bool state); + int getBeautifierFileType() const; + int getFileType() const; + int getIndentLength(void) const; + int getTabLength(void) const; + string getIndentString(void) const; + string getNextWord(const string& line, size_t currPos) const; + bool getAlignMethodColon(void) const; + bool getBracketIndent(void) const; + bool getBlockIndent(void) const; + bool getCaseIndent(void) const; + bool getClassIndent(void) const; + bool getEmptyLineFill(void) const; + bool getForceTabIndentation(void) const; + bool getModeManuallySet(void) const; + bool getModifierIndent(void) const; + bool getNamespaceIndent(void) const; + bool getPreprocDefineIndent(void) const; + bool getSwitchIndent(void) const; + +protected: + void deleteBeautifierVectors(); + const string* findHeader(const string& line, int i, + const vector* possibleHeaders) const; + const string* findOperator(const string& line, int i, + const vector* possibleOperators) const; + int getNextProgramCharDistance(const string& line, int i) const; + int indexOf(vector& container, const string* element) const; + void setBlockIndent(bool state); + void setBracketIndent(bool state); + void setBracketIndentVtk(bool state); + string extractPreprocessorStatement(const string& line) const; + string trim(const string& str) const; + string rtrim(const string& str) const; + + // variables set by ASFormatter - must be updated in activeBeautifierStack + int inLineNumber; + int horstmannIndentInStatement; + int nonInStatementBracket; + int objCColonAlignSubsequent; // for subsequent lines not counting indent + bool lineCommentNoBeautify; + bool isElseHeaderIndent; + bool isCaseHeaderCommentIndent; + bool isNonInStatementArray; + bool isSharpAccessor; + bool isSharpDelegate; + bool isInExternC; + bool isInBeautifySQL; + bool isInIndentableStruct; + bool isInIndentablePreproc; + +private: // functions + ASBeautifier(const ASBeautifier& copy); // inline functions + ASBeautifier& operator=(ASBeautifier&); // not to be implemented + + void adjustParsedLineIndentation(size_t iPrelim, bool isInExtraHeaderIndent); + void computePreliminaryIndentation(); + void parseCurrentLine(const string& line); + void popLastInStatementIndent(); + void processPreprocessor(const string& preproc, const string& line); + void registerInStatementIndent(const string& line, int i, int spaceIndentCount, + int tabIncrementIn, int minIndent, bool updateParenStack); + void registerInStatementIndentColon(const string& line, int i, int tabIncrementIn); + void initVectors(); + void initTempStacksContainer(vector*>*& container, + vector*>* value); + void clearObjCMethodDefinitionAlignment(); + void deleteBeautifierContainer(vector*& container); + void deleteTempStacksContainer(vector*>*& container); + int adjustIndentCountForBreakElseIfComments() const; + int computeObjCColonAlignment(string& line, int colonAlignPosition) const; + int convertTabToSpaces(int i, int tabIncrementIn) const; + int getInStatementIndentAssign(const string& line, size_t currPos) const; + int getInStatementIndentComma(const string& line, size_t currPos) const; + bool isIndentedPreprocessor(const string& line, size_t currPos) const; + bool isLineEndComment(const string& line, int startPos) const; + bool isPreprocessorConditionalCplusplus(const string& line) const; + bool isInPreprocessorUnterminatedComment(const string& line); + bool statementEndsWithComma(const string& line, int index) const; + string& getIndentedLineReturn(string& newLine, const string& originalLine) const; + string preLineWS(int lineIndentCount, int lineSpaceIndentCount) const; + template void deleteContainer(T& container); + template void initContainer(T& container, T value); + vector*>* copyTempStacks(const ASBeautifier& other) const; + pair computePreprocessorIndent(); + +private: // variables + int beautifierFileType; + vector* headers; + vector* nonParenHeaders; + vector* preBlockStatements; + vector* preCommandHeaders; + vector* assignmentOperators; + vector* nonAssignmentOperators; + vector* indentableHeaders; + + vector* waitingBeautifierStack; + vector* activeBeautifierStack; + vector* waitingBeautifierStackLengthStack; + vector* activeBeautifierStackLengthStack; + vector* headerStack; + vector* >* tempStacks; + vector* blockParenDepthStack; + vector* blockStatementStack; + vector* parenStatementStack; + vector* bracketBlockStateStack; + vector* inStatementIndentStack; + vector* inStatementIndentStackSizeStack; + vector* parenIndentStack; + vector >* preprocIndentStack; + + ASSourceIterator* sourceIterator; + const string* currentHeader; + const string* previousLastLineHeader; + const string* probationHeader; + const string* lastLineHeader; + string indentString; + string verbatimDelimiter; + bool isInQuote; + bool isInVerbatimQuote; + bool haveLineContinuationChar; + bool isInAsm; + bool isInAsmOneLine; + bool isInAsmBlock; + bool isInComment; + bool isInPreprocessorComment; + bool isInHorstmannComment; + bool isInCase; + bool isInQuestion; + bool isInStatement; + bool isInHeader; + bool isInTemplate; + bool isInDefine; + bool isInDefineDefinition; + bool classIndent; + bool isIndentModeOff; + bool isInClassHeader; // is in a class before the opening bracket + bool isInClassHeaderTab; // is in an indentable class header line + bool isInClassInitializer; // is in a class after the ':' initializer + bool isInClass; // is in a class after the opening bracket + bool isInObjCMethodDefinition; + bool isImmediatelyPostObjCMethodDefinition; + bool isInIndentablePreprocBlock; + bool isInObjCInterface; + bool isInEnum; + bool isInEnumTypeID; + bool isInLet; + bool modifierIndent; + bool switchIndent; + bool caseIndent; + bool namespaceIndent; + bool bracketIndent; + bool bracketIndentVtk; + bool blockIndent; + bool labelIndent; + bool shouldIndentPreprocDefine; + bool isInConditional; + bool isModeManuallySet; + bool shouldForceTabIndentation; + bool emptyLineFill; + bool backslashEndsPrevLine; + bool lineOpensWithLineComment; + bool lineOpensWithComment; + bool lineStartsInComment; + bool blockCommentNoIndent; + bool blockCommentNoBeautify; + bool previousLineProbationTab; + bool lineBeginsWithOpenBracket; + bool lineBeginsWithCloseBracket; + bool lineBeginsWithComma; + bool lineIsCommentOnly; + bool lineIsLineCommentOnly; + bool shouldIndentBrackettedLine; + bool isInSwitch; + bool foundPreCommandHeader; + bool foundPreCommandMacro; + bool shouldAlignMethodColon; + bool shouldIndentPreprocConditional; + int indentCount; + int spaceIndentCount; + int spaceIndentObjCMethodDefinition; + int colonIndentObjCMethodDefinition; + int lineOpeningBlocksNum; + int lineClosingBlocksNum; + int fileType; + int minConditionalOption; + int minConditionalIndent; + int parenDepth; + int indentLength; + int tabLength; + int blockTabCount; + int maxInStatementIndent; + int classInitializerIndents; + int templateDepth; + int squareBracketCount; + int prevFinalLineSpaceIndentCount; + int prevFinalLineIndentCount; + int defineIndentCount; + int preprocBlockIndent; + char quoteChar; + char prevNonSpaceCh; + char currentNonSpaceCh; + char currentNonLegalCh; + char prevNonLegalCh; +}; // Class ASBeautifier + +//----------------------------------------------------------------------------- +// Class ASEnhancer +//----------------------------------------------------------------------------- + +class ASEnhancer : protected ASBase +{ +public: // functions + ASEnhancer(); + virtual ~ASEnhancer(); + void init(int, int, int, bool, bool, bool, bool, bool, bool, bool, + vector* >*); + void enhance(string& line, bool isInNamespace, bool isInPreprocessor, bool isInSQL); + +private: // functions + void convertForceTabIndentToSpaces(string& line) const; + void convertSpaceIndentToForceTab(string& line) const; + size_t findCaseColon(string& line, size_t caseIndex) const; + int indentLine(string& line, int indent) const; + bool isBeginDeclareSectionSQL(string& line, size_t index) const; + bool isEndDeclareSectionSQL(string& line, size_t index) const; + bool isOneLineBlockReached(string& line, int startChar) const; + void parseCurrentLine(string& line, bool isInPreprocessor, bool isInSQL); + size_t processSwitchBlock(string& line, size_t index); + int unindentLine(string& line, int unindent) const; + +private: + // options from command line or options file + int indentLength; + int tabLength; + bool useTabs; + bool forceTab; + bool namespaceIndent; + bool caseIndent; + bool preprocBlockIndent; + bool preprocDefineIndent; + bool emptyLineFill; + + // parsing variables + int lineNumber; + bool isInQuote; + bool isInComment; + char quoteChar; + + // unindent variables + int bracketCount; + int switchDepth; + int eventPreprocDepth; + bool lookingForCaseBracket; + bool unindentNextLine; + bool shouldUnindentLine; + bool shouldUnindentComment; + + // struct used by ParseFormattedLine function + // contains variables used to unindent the case blocks + struct switchVariables + { + int switchBracketCount; + int unindentDepth; + bool unindentCase; + }; + + switchVariables sw; // switch variables struct + vector switchStack; // stack vector of switch variables + + // event table variables + bool nextLineIsEventIndent; // begin event table indent is reached + bool isInEventTable; // need to indent an event table + vector* >* indentableMacros; + + // SQL variables + bool nextLineIsDeclareIndent; // begin declare section indent is reached + bool isInDeclareSection; // need to indent a declare section + +}; // Class ASEnhancer + +//----------------------------------------------------------------------------- +// Class ASFormatter +//----------------------------------------------------------------------------- + +class ASFormatter : public ASBeautifier +{ +public: // functions + ASFormatter(); + virtual ~ASFormatter(); + virtual void init(ASSourceIterator* iter); + virtual bool hasMoreLines() const; + virtual string nextLine(); + LineEndFormat getLineEndFormat() const; + bool getIsLineReady() const; + void setFormattingStyle(FormatStyle style); + void setAddBracketsMode(bool state); + void setAddOneLineBracketsMode(bool state); + void setRemoveBracketsMode(bool state); + void setAttachClass(bool state); + void setAttachExternC(bool state); + void setAttachNamespace(bool state); + void setAttachInline(bool state); + void setBracketFormatMode(BracketMode mode); + void setBreakAfterMode(bool state); + void setBreakClosingHeaderBracketsMode(bool state); + void setBreakBlocksMode(bool state); + void setBreakClosingHeaderBlocksMode(bool state); + void setBreakElseIfsMode(bool state); + void setBreakOneLineBlocksMode(bool state); + void setMethodPrefixPaddingMode(bool state); + void setMethodPrefixUnPaddingMode(bool state); + void setReturnTypePaddingMode(bool state); + void setReturnTypeUnPaddingMode(bool state); + void setCloseTemplatesMode(bool state); + void setCommaPaddingMode(bool state); + void setDeleteEmptyLinesMode(bool state); + void setIndentCol1CommentsMode(bool state); + void setLineEndFormat(LineEndFormat fmt); + void setMaxCodeLength(int max); + void setObjCColonPaddingMode(ObjCColonPad mode); + void setOperatorPaddingMode(bool mode); + void setParensOutsidePaddingMode(bool mode); + void setParensFirstPaddingMode(bool mode); + void setParensInsidePaddingMode(bool mode); + void setParensHeaderPaddingMode(bool mode); + void setParensUnPaddingMode(bool state); + void setPointerAlignment(PointerAlign alignment); + void setPreprocBlockIndent(bool state); + void setReferenceAlignment(ReferenceAlign alignment); + void setSingleStatementsMode(bool state); + void setStripCommentPrefix(bool state); + void setTabSpaceConversionMode(bool state); + size_t getChecksumIn() const; + size_t getChecksumOut() const; + int getChecksumDiff() const; + int getFormatterFileType() const; + +private: // functions + ASFormatter(const ASFormatter& copy); // not to be implemented + ASFormatter& operator=(ASFormatter&); // not to be implemented + template void deleteContainer(T& container); + template void initContainer(T& container, T value); + char peekNextChar() const; + BracketType getBracketType(); + bool adjustChecksumIn(int adjustment); + bool computeChecksumIn(const string& currentLine_); + bool computeChecksumOut(const string& beautifiedLine); + bool addBracketsToStatement(); + bool removeBracketsFromStatement(); + bool commentAndHeaderFollows(); + bool getNextChar(); + bool getNextLine(bool emptyLineWasDeleted = false); + bool isArrayOperator() const; + bool isBeforeComment() const; + bool isBeforeAnyComment() const; + bool isBeforeAnyLineEndComment(int startPos) const; + bool isBeforeMultipleLineEndComments(int startPos) const; + bool isBracketType(BracketType a, BracketType b) const; + bool isClassInitializer() const; + bool isClosingHeader(const string* header) const; + bool isCurrentBracketBroken() const; + bool isDereferenceOrAddressOf() const; + bool isExecSQL(string& line, size_t index) const; + bool isEmptyLine(const string& line) const; + bool isExternC() const; + bool isNextWordSharpNonParenHeader(int startChar) const; + bool isNonInStatementArrayBracket() const; + bool isOkToSplitFormattedLine(); + bool isPointerOrReference() const; + bool isPointerOrReferenceCentered() const; + bool isPointerOrReferenceVariable(string& word) const; + bool isSharpStyleWithParen(const string* header) const; + bool isStructAccessModified(string& firstLine, size_t index) const; + bool isIndentablePreprocessorBlock(string& firstLine, size_t index); + bool isUnaryOperator() const; + bool isUniformInitializerBracket() const; + bool isImmediatelyPostCast() const; + bool isInExponent() const; + bool isInSwitchStatement() const; + bool isNextCharOpeningBracket(int startChar) const; + bool isOkToBreakBlock(BracketType bracketType) const; + bool isOperatorPaddingDisabled() const; + bool pointerSymbolFollows() const; + int findObjCColonAlignment() const; + int getCurrentLineCommentAdjustment(); + int getNextLineCommentAdjustment(); + int isOneLineBlockReached(string& line, int startChar) const; + void adjustComments(); + void appendChar(char ch, bool canBreakLine); + void appendCharInsideComments(); + void appendOperator(const string& sequence, bool canBreakLine = true); + void appendSequence(const string& sequence, bool canBreakLine = true); + void appendSpacePad(); + void appendSpaceAfter(); + void breakLine(bool isSplitLine = false); + void buildLanguageVectors(); + void updateFormattedLineSplitPoints(char appendedChar); + void updateFormattedLineSplitPointsOperator(const string& sequence); + void checkIfTemplateOpener(); + void clearFormattedLineSplitPoints(); + void convertTabToSpaces(); + void deleteContainer(vector*& container); + void formatArrayRunIn(); + void formatRunIn(); + void formatArrayBrackets(BracketType bracketType, bool isOpeningArrayBracket); + void formatClosingBracket(BracketType bracketType); + void formatCommentBody(); + void formatCommentOpener(); + void formatCommentCloser(); + void formatLineCommentBody(); + void formatLineCommentOpener(); + void formatOpeningBracket(BracketType bracketType); + void formatQuoteBody(); + void formatQuoteOpener(); + void formatPointerOrReference(); + void formatPointerOrReferenceCast(); + void formatPointerOrReferenceToMiddle(); + void formatPointerOrReferenceToName(); + void formatPointerOrReferenceToType(); + void fixOptionVariableConflicts(); + void goForward(int i); + void isLineBreakBeforeClosingHeader(); + void initContainer(vector*& container, vector* value); + void initNewLine(); + void padObjCMethodColon(); + void padOperators(const string* newOperator); + void padParens(); + void padParenObjC(void); + void processPreprocessor(); + void resetEndOfStatement(); + void setAttachClosingBracketMode(bool state); + void stripCommentPrefix(); + void testForTimeToSplitFormattedLine(); + void trimContinuationLine(); + void updateFormattedLineSplitPointsPointerOrReference(size_t index); + size_t findFormattedLineSplitPoint() const; + size_t findNextChar(string& line, char searchChar, int searchStart = 0) const; + const string* checkForHeaderFollowingComment(const string& firstLine) const; + const string* getFollowingOperator() const; + string getPreviousWord(const string& line, int currPos) const; + string peekNextText(const string& firstLine, bool endOnEmptyLine = false, bool shouldReset = false) const; + +private: // variables + int formatterFileType; + vector* headers; + vector* nonParenHeaders; + vector* preDefinitionHeaders; + vector* preCommandHeaders; + vector* operators; + vector* assignmentOperators; + vector* castOperators; + vector* >* indentableMacros; // for ASEnhancer + + ASSourceIterator* sourceIterator; + ASEnhancer* enhancer; + + vector* preBracketHeaderStack; + vector* bracketTypeStack; + vector* parenStack; + vector* structStack; + vector* questionMarkStack; + + string currentLine; + string formattedLine; + string readyFormattedLine; + string verbatimDelimiter; + const string* currentHeader; + const string* previousOperator; // used ONLY by pad-oper + char currentChar; + char previousChar; + char previousNonWSChar; + char previousCommandChar; + char quoteChar; + streamoff preprocBlockEnd; + int charNum; + int horstmannIndentChars; + int nextLineSpacePadNum; + int objCColonAlign; + int preprocBracketTypeStackSize; + int spacePadNum; + int tabIncrementIn; + int templateDepth; + int squareBracketCount; + size_t checksumIn; + size_t checksumOut; + size_t currentLineFirstBracketNum; // first bracket location on currentLine + size_t formattedLineCommentNum; // comment location on formattedLine + size_t leadingSpaces; + size_t maxCodeLength; + + // possible split points + size_t maxSemi; // probably a 'for' statement + size_t maxAndOr; // probably an 'if' statement + size_t maxComma; + size_t maxParen; + size_t maxWhiteSpace; + size_t maxSemiPending; + size_t maxAndOrPending; + size_t maxCommaPending; + size_t maxParenPending; + size_t maxWhiteSpacePending; + + size_t previousReadyFormattedLineLength; + FormatStyle formattingStyle; + BracketMode bracketFormatMode; + BracketType previousBracketType; + PointerAlign pointerAlignment; + ReferenceAlign referenceAlignment; + ObjCColonPad objCColonPadMode; + LineEndFormat lineEnd; + bool isVirgin; + bool shouldPadCommas; + bool shouldPadOperators; + bool shouldPadParensOutside; + bool shouldPadFirstParen; + bool shouldPadParensInside; + bool shouldPadHeader; + bool shouldStripCommentPrefix; + bool shouldUnPadParens; + bool shouldConvertTabs; + bool shouldIndentCol1Comments; + bool shouldIndentPreprocBlock; + bool shouldCloseTemplates; + bool shouldAttachExternC; + bool shouldAttachNamespace; + bool shouldAttachClass; + bool shouldAttachInline; + bool isInLineComment; + bool isInComment; + bool isInCommentStartLine; + bool noTrimCommentContinuation; + bool isInPreprocessor; + bool isInPreprocessorBeautify; + bool isInTemplate; + bool doesLineStartComment; + bool lineEndsInCommentOnly; + bool lineIsCommentOnly; + bool lineIsLineCommentOnly; + bool lineIsEmpty; + bool isImmediatelyPostCommentOnly; + bool isImmediatelyPostEmptyLine; + bool isInClassInitializer; + bool isInQuote; + bool isInVerbatimQuote; + bool haveLineContinuationChar; + bool isInQuoteContinuation; + bool isHeaderInMultiStatementLine; + bool isSpecialChar; + bool isNonParenHeader; + bool foundQuestionMark; + bool foundPreDefinitionHeader; + bool foundNamespaceHeader; + bool foundClassHeader; + bool foundStructHeader; + bool foundInterfaceHeader; + bool foundPreCommandHeader; + bool foundPreCommandMacro; + bool foundCastOperator; + bool isInLineBreak; + bool endOfAsmReached; + bool endOfCodeReached; + bool lineCommentNoIndent; + bool isFormattingModeOff; + bool isInEnum; + bool isInExecSQL; + bool isInAsm; + bool isInAsmOneLine; + bool isInAsmBlock; + bool isLineReady; + bool elseHeaderFollowsComments; + bool caseHeaderFollowsComments; + bool isPreviousBracketBlockRelated; + bool isInPotentialCalculation; + bool isCharImmediatelyPostComment; + bool isPreviousCharPostComment; + bool isCharImmediatelyPostLineComment; + bool isCharImmediatelyPostOpenBlock; + bool isCharImmediatelyPostCloseBlock; + bool isCharImmediatelyPostTemplate; + bool isCharImmediatelyPostReturn; + bool isCharImmediatelyPostThrow; + bool isCharImmediatelyPostOperator; + bool isCharImmediatelyPostPointerOrReference; + bool isInObjCMethodDefinition; + bool isInObjCInterface; + bool isInObjCReturnType; + bool isInObjCSelector; + bool breakCurrentOneLineBlock; + bool shouldRemoveNextClosingBracket; + bool isInHorstmannRunIn; + bool currentLineBeginsWithBracket; + bool attachClosingBracketMode; + bool shouldBreakOneLineBlocks; + bool shouldReparseCurrentChar; + bool shouldBreakOneLineStatements; + bool shouldBreakClosingHeaderBrackets; + bool shouldBreakElseIfs; + bool shouldBreakLineAfterLogical; + bool shouldAddBrackets; + bool shouldAddOneLineBrackets; + bool shouldRemoveBrackets; + bool shouldPadMethodColon; + bool shouldPadMethodPrefix; + bool shouldUnPadMethodPrefix; + bool shouldPadReturnType; + bool shouldUnPadReturnType; + bool shouldDeleteEmptyLines; + bool needHeaderOpeningBracket; + bool shouldBreakLineAtNextChar; + bool shouldKeepLineUnbroken; + bool passedSemicolon; + bool passedColon; + bool isImmediatelyPostNonInStmt; + bool isCharImmediatelyPostNonInStmt; + bool isImmediatelyPostComment; + bool isImmediatelyPostLineComment; + bool isImmediatelyPostEmptyBlock; + bool isImmediatelyPostObjCMethodPrefix; + bool isImmediatelyPostPreprocessor; + bool isImmediatelyPostReturn; + bool isImmediatelyPostThrow; + bool isImmediatelyPostOperator; + bool isImmediatelyPostTemplate; + bool isImmediatelyPostPointerOrReference; + bool shouldBreakBlocks; + bool shouldBreakClosingHeaderBlocks; + bool isPrependPostBlockEmptyLineRequested; + bool isAppendPostBlockEmptyLineRequested; + bool isIndentableProprocessor; + bool isIndentableProprocessorBlock; + bool prependEmptyLine; + bool appendOpeningBracket; + bool foundClosingHeader; + bool isInHeader; + bool isImmediatelyPostHeader; + bool isInCase; + bool isFirstPreprocConditional; + bool processedFirstConditional; + bool isJavaStaticConstructor; + +private: // inline functions + // append the CURRENT character (curentChar) to the current formatted line. + void appendCurrentChar(bool canBreakLine = true) + { + appendChar(currentChar, canBreakLine); + } + + // check if a specific sequence exists in the current placement of the current line + bool isSequenceReached(const char* sequence) const + { + return currentLine.compare(charNum, strlen(sequence), sequence) == 0; + } + + // call ASBase::findHeader for the current character + const string* findHeader(const vector* headers_) + { + return ASBeautifier::findHeader(currentLine, charNum, headers_); + } + + // call ASBase::findOperator for the current character + const string* findOperator(const vector* headers_) + { + return ASBeautifier::findOperator(currentLine, charNum, headers_); + } +}; // Class ASFormatter + +//----------------------------------------------------------------------------- +// astyle namespace global declarations +//----------------------------------------------------------------------------- +// sort comparison functions for ASResource +bool sortOnLength(const string* a, const string* b); +bool sortOnName(const string* a, const string* b); + +} // end of astyle namespace + +// end of astyle namespace -------------------------------------------------- + +#endif // closes ASTYLE_H diff --git a/External/Tools/AStyle/src/astyle_main.cpp b/External/Tools/AStyle/src/astyle_main.cpp new file mode 100644 index 0000000000..1adc3cd18f --- /dev/null +++ b/External/Tools/AStyle/src/astyle_main.cpp @@ -0,0 +1,3792 @@ +// astyle_main.cpp +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. +// License.txt describes the conditions under which this software may be distributed. + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + * AStyle_main source file map. + * This source file contains several classes. + * They are arranged as follows. + * --------------------------------------- + * namespace astyle { + * ASStreamIterator methods + * ASConsole methods + * // Windows specific + * // Linux specific + * ASLibrary methods + * // Windows specific + * // Linux specific + * ASOptions methods + * Utf8_16 methods + * } // end of astyle namespace + * Global Area --------------------------- + * Java Native Interface functions + * AStyleMainUtf16 entry point + * AStyleMain entry point + * AStyleGetVersion entry point + * main entry point + * --------------------------------------- + * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * + */ + +//----------------------------------------------------------------------------- +// headers +//----------------------------------------------------------------------------- + +#include "astyle_main.h" + +#include +#include +#include +#include +#include // needed by some compilers +#include + +// includes for recursive getFileNames() function +#ifdef _WIN32 + #undef UNICODE // use ASCII windows functions + #include +#else + #include + #include + #include + #ifdef __VMS + #include + #include + #include + #include + #include + #include + #endif /* __VMS */ +#endif + +//----------------------------------------------------------------------------- +// declarations +//----------------------------------------------------------------------------- + +// turn off MinGW automatic file globbing +// this CANNOT be in the astyle namespace +#ifndef ASTYLE_LIB + int _CRT_glob = 0; +#endif + +//---------------------------------------------------------------------------- +// astyle namespace +//---------------------------------------------------------------------------- + +namespace astyle { +// +// console build variables +#ifndef ASTYLE_LIB + ASConsole* g_console = NULL; // class to encapsulate console variables + ostream* _err = &cerr; // direct error messages to cerr + #ifdef _WIN32 + char g_fileSeparator = '\\'; // Windows file separator + bool g_isCaseSensitive = false; // Windows IS case sensitive + #else + char g_fileSeparator = '/'; // Linux file separator + bool g_isCaseSensitive = true; // Linux IS NOT case sensitive + #endif // _WIN32 +#endif // ASTYLE_LIB + +// java library build variables +#ifdef ASTYLE_JNI + JNIEnv* g_env; + jobject g_obj; + jmethodID g_mid; +#endif + +const char* g_version = "2.06 beta"; + +//----------------------------------------------------------------------------- +// ASStreamIterator class +// typename will be istringstream for GUI and istream otherwise +//----------------------------------------------------------------------------- + +template +ASStreamIterator::ASStreamIterator(T* in) +{ + inStream = in; + buffer.reserve(200); + eolWindows = 0; + eolLinux = 0; + eolMacOld = 0; + outputEOL[0] = '\0'; + peekStart = 0; + prevLineDeleted = false; + checkForEmptyLine = false; + // get length of stream + inStream->seekg(0, inStream->end); + streamLength = inStream->tellg(); + inStream->seekg(0, inStream->beg); +} + +template +ASStreamIterator::~ASStreamIterator() +{ +} + +/** +* get the length of the input stream. +* streamLength variable is set by the constructor. +* +* @return length of the input file stream, converted to an int. +*/ +template +int ASStreamIterator::getStreamLength() const +{ + return static_cast(streamLength); +} + +/** + * read the input stream, delete any end of line characters, + * and build a string that contains the input line. + * + * @return string containing the next input line minus any end of line characters + */ +template +string ASStreamIterator::nextLine(bool emptyLineWasDeleted) +{ + // verify that the current position is correct + assert(peekStart == 0); + + // a deleted line may be replaced if break-blocks is requested + // this sets up the compare to check for a replaced empty line + if (prevLineDeleted) + { + prevLineDeleted = false; + checkForEmptyLine = true; + } + if (!emptyLineWasDeleted) + prevBuffer = buffer; + else + prevLineDeleted = true; + + // read the next record + buffer.clear(); + char ch; + inStream->get(ch); + + while (!inStream->eof() && ch != '\n' && ch != '\r') + { + buffer.append(1, ch); + inStream->get(ch); + } + + if (inStream->eof()) + { + return buffer; + } + + int peekCh = inStream->peek(); + + // find input end-of-line characters + if (!inStream->eof()) + { + if (ch == '\r') // CR+LF is windows otherwise Mac OS 9 + { + if (peekCh == '\n') + { + inStream->get(); + eolWindows++; + } + else + eolMacOld++; + } + else // LF is Linux, allow for improbable LF/CR + { + if (peekCh == '\r') + { + inStream->get(); + eolWindows++; + } + else + eolLinux++; + } + } + else + { + inStream->clear(); + } + + // set output end of line characters + if (eolWindows >= eolLinux) + { + if (eolWindows >= eolMacOld) + strcpy(outputEOL, "\r\n"); // Windows (CR+LF) + else + strcpy(outputEOL, "\r"); // MacOld (CR) + } + else if (eolLinux >= eolMacOld) + strcpy(outputEOL, "\n"); // Linux (LF) + else + strcpy(outputEOL, "\r"); // MacOld (CR) + + return buffer; +} + +// save the current position and get the next line +// this can be called for multiple reads +// when finished peeking you MUST call peekReset() +// call this function from ASFormatter ONLY +template +string ASStreamIterator::peekNextLine() +{ + assert(hasMoreLines()); + string nextLine_; + char ch; + + if (peekStart == 0) + peekStart = inStream->tellg(); + + // read the next record + inStream->get(ch); + while (!inStream->eof() && ch != '\n' && ch != '\r') + { + nextLine_.append(1, ch); + inStream->get(ch); + } + + if (inStream->eof()) + { + return nextLine_; + } + + int peekCh = inStream->peek(); + + // remove end-of-line characters + if (!inStream->eof()) + { + if ((peekCh == '\n' || peekCh == '\r') && peekCh != ch) + inStream->get(); + } + + return nextLine_; +} + +// reset current position and EOF for peekNextLine() +template +void ASStreamIterator::peekReset() +{ + assert(peekStart != 0); + inStream->clear(); + inStream->seekg(peekStart); + peekStart = 0; +} + +// save the last input line after input has reached EOF +template +void ASStreamIterator::saveLastInputLine() +{ + assert(inStream->eof()); + prevBuffer = buffer; +} + +// return position of the get pointer +template +streamoff ASStreamIterator::tellg() +{ + return inStream->tellg(); +} + +// check for a change in line ends +template +bool ASStreamIterator::getLineEndChange(int lineEndFormat) const +{ + assert(lineEndFormat == LINEEND_DEFAULT + || lineEndFormat == LINEEND_WINDOWS + || lineEndFormat == LINEEND_LINUX + || lineEndFormat == LINEEND_MACOLD); + + bool lineEndChange = false; + if (lineEndFormat == LINEEND_WINDOWS) + lineEndChange = (eolLinux + eolMacOld != 0); + else if (lineEndFormat == LINEEND_LINUX) + lineEndChange = (eolWindows + eolMacOld != 0); + else if (lineEndFormat == LINEEND_MACOLD) + lineEndChange = (eolWindows + eolLinux != 0); + else + { + if (eolWindows > 0) + lineEndChange = (eolLinux + eolMacOld != 0); + else if (eolLinux > 0) + lineEndChange = (eolWindows + eolMacOld != 0); + else if (eolMacOld > 0) + lineEndChange = (eolWindows + eolLinux != 0); + } + return lineEndChange; +} + +//----------------------------------------------------------------------------- +// ASConsole class +// main function will be included only in the console build +//----------------------------------------------------------------------------- + +#ifndef ASTYLE_LIB + +// rewrite a stringstream converting the line ends +void ASConsole::convertLineEnds(ostringstream& out, int lineEnd) +{ + assert(lineEnd == LINEEND_WINDOWS || lineEnd == LINEEND_LINUX || lineEnd == LINEEND_MACOLD); + const string& inStr = out.str(); // avoids strange looking syntax + string outStr; // the converted output + int inLength = inStr.length(); + for (int pos = 0; pos < inLength; pos++) + { + if (inStr[pos] == '\r') + { + if (inStr[pos + 1] == '\n') + { + // CRLF + if (lineEnd == LINEEND_CR) + { + outStr += inStr[pos]; // Delete the LF + pos++; + continue; + } + else if (lineEnd == LINEEND_LF) + { + outStr += inStr[pos + 1]; // Delete the CR + pos++; + continue; + } + else + { + outStr += inStr[pos]; // Do not change + outStr += inStr[pos + 1]; + pos++; + continue; + } + } + else + { + // CR + if (lineEnd == LINEEND_CRLF) + { + outStr += inStr[pos]; // Insert the CR + outStr += '\n'; // Insert the LF + continue; + } + else if (lineEnd == LINEEND_LF) + { + outStr += '\n'; // Insert the LF + continue; + } + else + { + outStr += inStr[pos]; // Do not change + continue; + } + } + } + else if (inStr[pos] == '\n') + { + // LF + if (lineEnd == LINEEND_CRLF) + { + outStr += '\r'; // Insert the CR + outStr += inStr[pos]; // Insert the LF + continue; + } + else if (lineEnd == LINEEND_CR) + { + outStr += '\r'; // Insert the CR + continue; + } + else + { + outStr += inStr[pos]; // Do not change + continue; + } + } + else + { + outStr += inStr[pos]; // Write the current char + } + } + // replace the stream + out.str(outStr); +} + +void ASConsole::correctMixedLineEnds(ostringstream& out) +{ + LineEndFormat lineEndFormat = LINEEND_DEFAULT; + if (strcmp(outputEOL, "\r\n") == 0) + lineEndFormat = LINEEND_WINDOWS; + if (strcmp(outputEOL, "\n") == 0) + lineEndFormat = LINEEND_LINUX; + if (strcmp(outputEOL, "\r") == 0) + lineEndFormat = LINEEND_MACOLD; + convertLineEnds(out, lineEndFormat); +} + +// check files for 16 or 32 bit encoding +// the file must have a Byte Order Mark (BOM) +// NOTE: some string functions don't work with NULLs (e.g. length()) +FileEncoding ASConsole::detectEncoding(const char* data, size_t dataSize) const +{ + FileEncoding encoding = ENCODING_8BIT; + + if (dataSize >= 4 && memcmp(data, "\x00\x00\xFE\xFF", 4) == 0) + encoding = UTF_32BE; + else if (dataSize >= 4 && memcmp(data, "\xFF\xFE\x00\x00", 4) == 0) + encoding = UTF_32LE; + else if (dataSize >= 2 && memcmp(data, "\xFE\xFF", 2) == 0) + encoding = UTF_16BE; + else if (dataSize >= 2 && memcmp(data, "\xFF\xFE", 2) == 0) + encoding = UTF_16LE; + + return encoding; +} + +// error exit without a message +void ASConsole::error() const +{ + (*_err) << _("\nArtistic Style has terminated") << endl; + exit(EXIT_FAILURE); +} + +// error exit with a message +void ASConsole::error(const char* why, const char* what) const +{ + (*_err) << why << ' ' << what << endl; + error(); +} + +/** + * If no files have been given, use cin for input and cout for output. + * + * This is used to format text for text editors like TextWrangler (Mac). + * Do NOT display any console messages when this function is used. + */ +void ASConsole::formatCinToCout() +{ + // Using cin.tellg() causes problems with both Windows and Linux. + // The Windows problem occurs when the input is not Windows line-ends. + // The tellg() will be out of sequence with the get() statements. + // The Linux cin.tellg() will return -1 (invalid). + // Copying the input sequentially to a stringstream before + // formatting solves the problem for both. + istream* inStream = &cin; + stringstream outStream; + char ch; + inStream->get(ch); + while (!inStream->eof()) + { + outStream.put(ch); + inStream->get(ch); + } + ASStreamIterator streamIterator(&outStream); + // Windows pipe or redirection always outputs Windows line-ends. + // Linux pipe or redirection will output any line end. + LineEndFormat lineEndFormat = formatter.getLineEndFormat(); + initializeOutputEOL(lineEndFormat); + formatter.init(&streamIterator); + + while (formatter.hasMoreLines()) + { + cout << formatter.nextLine(); + if (formatter.hasMoreLines()) + { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + cout << outputEOL; + } + else + { + // this can happen if the file if missing a closing bracket and break-blocks is requested + if (formatter.getIsLineReady()) + { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + cout << outputEOL; + cout << formatter.nextLine(); + } + } + } + cout.flush(); +} + +/** + * Open input file, format it, and close the output. + * + * @param fileName_ The path and name of the file to be processed. + */ +void ASConsole::formatFile(const string& fileName_) +{ + stringstream in; + ostringstream out; + FileEncoding encoding = readFile(fileName_, in); + + // Unless a specific language mode has been set, set the language mode + // according to the file's suffix. + if (!formatter.getModeManuallySet()) + { + if (stringEndsWith(fileName_, string(".java"))) + formatter.setJavaStyle(); + else if (stringEndsWith(fileName_, string(".cs"))) + formatter.setSharpStyle(); + else + formatter.setCStyle(); + } + + // set line end format + string nextLine; // next output line + filesAreIdentical = true; // input and output files are identical + LineEndFormat lineEndFormat = formatter.getLineEndFormat(); + initializeOutputEOL(lineEndFormat); + // do this AFTER setting the file mode + ASStreamIterator streamIterator(&in); + formatter.init(&streamIterator); + + // format the file + while (formatter.hasMoreLines()) + { + nextLine = formatter.nextLine(); + out << nextLine; + linesOut++; + if (formatter.hasMoreLines()) + { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + out << outputEOL; + } + else + { + streamIterator.saveLastInputLine(); // to compare the last input line + // this can happen if the file if missing a closing bracket and break-blocks is requested + if (formatter.getIsLineReady()) + { + setOutputEOL(lineEndFormat, streamIterator.getOutputEOL()); + out << outputEOL; + nextLine = formatter.nextLine(); + out << nextLine; + linesOut++; + streamIterator.saveLastInputLine(); + } + } + + if (filesAreIdentical) + { + if (streamIterator.checkForEmptyLine) + { + if (nextLine.find_first_not_of(" \t") != string::npos) + filesAreIdentical = false; + } + else if (!streamIterator.compareToInputBuffer(nextLine)) + filesAreIdentical = false; + streamIterator.checkForEmptyLine = false; + } + } + // correct for mixed line ends + if (lineEndsMixed) + { + correctMixedLineEnds(out); + filesAreIdentical = false; + } + + // remove targetDirectory from filename if required by print + string displayName; + if (hasWildcard) + displayName = fileName_.substr(targetDirectory.length() + 1); + else + displayName = fileName_; + + // if file has changed, write the new file + if (!filesAreIdentical || streamIterator.getLineEndChange(lineEndFormat)) + { + if (!isDryRun) + writeFile(fileName_, encoding, out); + printMsg(_("Formatted %s\n"), displayName); + filesFormatted++; + } + else + { + if (!isFormattedOnly) + printMsg(_("Unchanged %s\n"), displayName); + filesUnchanged++; + } + + assert(formatter.getChecksumDiff() == 0); +} + +// build a vector of argv options +// the program path argv[0] is excluded +vector ASConsole::getArgvOptions(int argc, char** argv) const +{ + vector argvOptions; + for (int i = 1; i < argc; i++) + { + argvOptions.push_back(string(argv[i])); + } + return argvOptions; +} + +// for unit testing +vector ASConsole::getExcludeHitsVector() const +{ return excludeHitsVector; } + +// for unit testing +vector ASConsole::getExcludeVector() const +{ return excludeVector; } + +// for unit testing +vector ASConsole::getFileName() const +{ return fileName; } + +// for unit testing +vector ASConsole::getFileNameVector() const +{ return fileNameVector; } + +// for unit testing +vector ASConsole::getFileOptionsVector() const +{ return fileOptionsVector; } + +// for unit testing +bool ASConsole::getFilesAreIdentical() const +{ return filesAreIdentical; } + +// for unit testing +int ASConsole::getFilesFormatted() const +{ return filesFormatted; } + +// for unit testing +bool ASConsole::getIgnoreExcludeErrors() const +{ return ignoreExcludeErrors; } + +// for unit testing +bool ASConsole::getIgnoreExcludeErrorsDisplay() const +{ return ignoreExcludeErrorsDisplay; } + +// for unit testing +bool ASConsole::getIsDryRun() const +{ return isDryRun; } + +// for unit testing +bool ASConsole::getIsFormattedOnly() const +{ return isFormattedOnly; } + +// for unit testing +string ASConsole::getLanguageID() const +{ return localizer.getLanguageID(); } + +// for unit testing +bool ASConsole::getIsQuiet() const +{ return isQuiet; } + +// for unit testing +bool ASConsole::getIsRecursive() const +{ return isRecursive; } + +// for unit testing +bool ASConsole::getIsVerbose() const +{ return isVerbose; } + +// for unit testing +bool ASConsole::getLineEndsMixed() const +{ return lineEndsMixed; } + +// for unit testing +bool ASConsole::getNoBackup() const +{ return noBackup; } + +// for unit testing +string ASConsole::getOptionsFileName() const +{ return optionsFileName; } + +// for unit testing +vector ASConsole::getOptionsVector() const +{ return optionsVector; } + +// for unit testing +string ASConsole::getOrigSuffix() const +{ return origSuffix; } + +// for unit testing +bool ASConsole::getPreserveDate() const +{ return preserveDate; } + +// for unit testing +void ASConsole::setBypassBrowserOpen(bool state) +{ bypassBrowserOpen = state; } + +string ASConsole::getParam(const string& arg, const char* op) +{ + return arg.substr(strlen(op)); +} + +// initialize output end of line +void ASConsole::initializeOutputEOL(LineEndFormat lineEndFormat) +{ + assert(lineEndFormat == LINEEND_DEFAULT + || lineEndFormat == LINEEND_WINDOWS + || lineEndFormat == LINEEND_LINUX + || lineEndFormat == LINEEND_MACOLD); + + outputEOL[0] = '\0'; // current line end + prevEOL[0] = '\0'; // previous line end + lineEndsMixed = false; // output has mixed line ends, LINEEND_DEFAULT only + + if (lineEndFormat == LINEEND_WINDOWS) + strcpy(outputEOL, "\r\n"); + else if (lineEndFormat == LINEEND_LINUX) + strcpy(outputEOL, "\n"); + else if (lineEndFormat == LINEEND_MACOLD) + strcpy(outputEOL, "\r"); + else + outputEOL[0] = '\0'; +} + +FileEncoding ASConsole::readFile(const string& fileName_, stringstream& in) const +{ + const int blockSize = 65536; // 64 KB + ifstream fin(fileName_.c_str(), ios::binary); + if (!fin) + error("Cannot open input file", fileName_.c_str()); + char* data = new(nothrow) char[blockSize]; + if (!data) + error("Cannot allocate memory for input file", fileName_.c_str()); + fin.read(data, blockSize); + if (fin.bad()) + error("Cannot read input file", fileName_.c_str()); + size_t dataSize = static_cast(fin.gcount()); + FileEncoding encoding = detectEncoding(data, dataSize); + if (encoding == UTF_32BE || encoding == UTF_32LE) + error(_("Cannot process UTF-32 encoding"), fileName_.c_str()); + bool firstBlock = true; + bool isBigEndian = (encoding == UTF_16BE); + while (dataSize) + { + if (encoding == UTF_16LE || encoding == UTF_16BE) + { + // convert utf-16 to utf-8 + size_t utf8Size = utf8_16.Utf8LengthFromUtf16(data, dataSize, isBigEndian); + char* utf8Out = new(nothrow) char[utf8Size]; + if (!utf8Out) + error("Cannot allocate memory for utf-8 conversion", fileName_.c_str()); + size_t utf8Len = utf8_16.Utf16ToUtf8(data, dataSize, isBigEndian, firstBlock, utf8Out); + assert(utf8Len == utf8Size); + in << string(utf8Out, utf8Len); + delete [] utf8Out; + } + else + in << string(data, dataSize); + fin.read(data, blockSize); + if (fin.bad()) + error("Cannot read input file", fileName_.c_str()); + dataSize = static_cast(fin.gcount()); + firstBlock = false; + } + fin.close(); + delete [] data; + return encoding; +} + +void ASConsole::setIgnoreExcludeErrors(bool state) +{ ignoreExcludeErrors = state; } + +void ASConsole::setIgnoreExcludeErrorsAndDisplay(bool state) +{ ignoreExcludeErrors = state; ignoreExcludeErrorsDisplay = state; } + +void ASConsole::setIsFormattedOnly(bool state) +{ isFormattedOnly = state; } + +void ASConsole::setIsQuiet(bool state) +{ isQuiet = state; } + +void ASConsole::setIsRecursive(bool state) +{ isRecursive = state; } + +void ASConsole::setIsDryRun(bool state) +{ isDryRun = state; } + +void ASConsole::setIsVerbose(bool state) +{ isVerbose = state; } + +void ASConsole::setNoBackup(bool state) +{ noBackup = state; } + +void ASConsole::setOptionsFileName(string name) +{ optionsFileName = name; } + +void ASConsole::setOrigSuffix(string suffix) +{ origSuffix = suffix; } + +void ASConsole::setPreserveDate(bool state) +{ preserveDate = state; } + +// set outputEOL variable +void ASConsole::setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL) +{ + if (lineEndFormat == LINEEND_DEFAULT) + { + strcpy(outputEOL, currentEOL); + if (strlen(prevEOL) == 0) + strcpy(prevEOL, outputEOL); + if (strcmp(prevEOL, outputEOL) != 0) + { + lineEndsMixed = true; + filesAreIdentical = false; + strcpy(prevEOL, outputEOL); + } + } + else + { + strcpy(prevEOL, currentEOL); + if (strcmp(prevEOL, outputEOL) != 0) + filesAreIdentical = false; + } +} + +#ifdef _WIN32 // Windows specific + +/** + * WINDOWS function to display the last system error. + */ +void ASConsole::displayLastError() +{ + LPSTR msgBuf; + DWORD lastError = GetLastError(); + FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + lastError, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language + (LPSTR) &msgBuf, + 0, + NULL + ); + // Display the string. + (*_err) << "Error (" << lastError << ") " << msgBuf << endl; + // Free the buffer. + LocalFree(msgBuf); +} + +/** + * WINDOWS function to get the current directory. + * NOTE: getenv("CD") does not work for Windows Vista. + * The Windows function GetCurrentDirectory is used instead. + * + * @return The path of the current directory + */ +string ASConsole::getCurrentDirectory(const string& fileName_) const +{ + char currdir[MAX_PATH]; + currdir[0] = '\0'; + if (!GetCurrentDirectory(sizeof(currdir), currdir)) + error("Cannot find file", fileName_.c_str()); + return string(currdir); +} + +/** + * WINDOWS function to resolve wildcards and recurse into sub directories. + * The fileName vector is filled with the path and names of files to process. + * + * @param directory The path of the directory to be processed. + * @param wildcard The wildcard to be processed (e.g. *.cpp). + */ +void ASConsole::getFileNames(const string& directory, const string& wildcard) +{ + vector subDirectory; // sub directories of directory + WIN32_FIND_DATA findFileData; // for FindFirstFile and FindNextFile + + // Find the first file in the directory + // Find will get at least "." and "..". + string firstFile = directory + "\\*"; + HANDLE hFind = FindFirstFile(firstFile.c_str(), &findFileData); + + if (hFind == INVALID_HANDLE_VALUE) + { + // Error (3) The system cannot find the path specified. + // Error (123) The filename, directory name, or volume label syntax is incorrect. + // ::FindClose(hFind); before exiting + displayLastError(); + error(_("Cannot open directory"), directory.c_str()); + } + + // save files and sub directories + do + { + // skip hidden or read only + if (findFileData.cFileName[0] == '.' + || (findFileData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) + || (findFileData.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) + continue; + + // is this a sub directory + if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + { + if (!isRecursive) + continue; + // if a sub directory and recursive, save sub directory + string subDirectoryPath = directory + g_fileSeparator + findFileData.cFileName; + if (isPathExclued(subDirectoryPath)) + printMsg(_("Exclude %s\n"), subDirectoryPath.substr(mainDirectoryLength)); + else + subDirectory.push_back(subDirectoryPath); + continue; + } + + // save the file name + string filePathName = directory + g_fileSeparator + findFileData.cFileName; + // check exclude before wildcmp to avoid "unmatched exclude" error + bool isExcluded = isPathExclued(filePathName); + // save file name if wildcard match + if (wildcmp(wildcard.c_str(), findFileData.cFileName)) + { + if (isExcluded) + printMsg(_("Exclude %s\n"), filePathName.substr(mainDirectoryLength)); + else + fileName.push_back(filePathName); + } + } + while (FindNextFile(hFind, &findFileData) != 0); + + // check for processing error + ::FindClose(hFind); + DWORD dwError = GetLastError(); + if (dwError != ERROR_NO_MORE_FILES) + error("Error processing directory", directory.c_str()); + + // recurse into sub directories + // if not doing recursive subDirectory is empty + for (unsigned i = 0; i < subDirectory.size(); i++) + getFileNames(subDirectory[i], wildcard); + + return; +} + +/** + * WINDOWS function to format a number according to the current locale. + * This formats positive integers only, no float. + * + * @param num The number to be formatted. + * @param lcid The LCID of the locale to be used for testing. + * @return The formatted number. + */ +string ASConsole::getNumberFormat(int num, size_t lcid) const +{ +#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__BORLANDC__) || defined(__GNUC__) + // Compilers that don't support C++ locales should still support this assert. + // The C locale should be set but not the C++. + // This function is not necessary if the C++ locale is set. + // The locale().name() return value is not portable to all compilers. + assert(locale().name() == "C"); +#endif + // convert num to a string + stringstream alphaNum; + alphaNum << num; + string number = alphaNum.str(); + if (useAscii) + return number; + + // format the number using the Windows API + if (lcid == 0) + lcid = LOCALE_USER_DEFAULT; + int outSize = ::GetNumberFormat(lcid, 0, number.c_str(), NULL, NULL, 0); + char* outBuf = new(nothrow) char[outSize]; + if (outBuf == NULL) + return number; + ::GetNumberFormat(lcid, 0, number.c_str(), NULL, outBuf, outSize); + string formattedNum(outBuf); + delete [] outBuf; + // remove the decimal + int decSize = ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, NULL, 0); + char* decBuf = new(nothrow) char[decSize]; + if (decBuf == NULL) + return number; + ::GetLocaleInfo(lcid, LOCALE_SDECIMAL, decBuf, decSize); + size_t i = formattedNum.rfind(decBuf); + delete [] decBuf; + if (i != string::npos) + formattedNum.erase(i); + if (!formattedNum.length()) + formattedNum = "0"; + return formattedNum; +} + +/** + * WINDOWS function to open a HTML file in the default browser. + */ +void ASConsole::launchDefaultBrowser(const char* filePathIn /*NULL*/) const +{ + struct stat statbuf; + const char* envPaths[] = { "PROGRAMFILES(X86)", "PROGRAMFILES" }; + size_t pathsLen = sizeof(envPaths) / sizeof(envPaths[0]); + string htmlDefaultPath; + for (size_t i = 0; i < pathsLen; i++) + { + const char* envPath = getenv(envPaths[i]); + if (envPath == NULL) + continue; + htmlDefaultPath = envPath; + if (htmlDefaultPath.length() > 0 + && htmlDefaultPath[htmlDefaultPath.length() - 1] == g_fileSeparator) + htmlDefaultPath.erase(htmlDefaultPath.length() - 1); + htmlDefaultPath.append("\\AStyle\\doc"); + if (stat(htmlDefaultPath.c_str(), &statbuf) == 0 && statbuf.st_mode & S_IFDIR) + break; + } + htmlDefaultPath.append("\\"); + + // build file path + string htmlFilePath; + if (filePathIn == NULL) + htmlFilePath = htmlDefaultPath + "astyle.html"; + else + { + if (strpbrk(filePathIn, "\\/") == NULL) + htmlFilePath = htmlDefaultPath + filePathIn; + else + htmlFilePath = filePathIn; + } + standardizePath(htmlFilePath); + if (stat(htmlFilePath.c_str(), &statbuf) != 0 || !(statbuf.st_mode & S_IFREG)) + { + printf(_("Cannot open HTML file %s\n"), htmlFilePath.c_str()); + return; + } + + SHELLEXECUTEINFO sei = { sizeof(sei), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + sei.fMask = SEE_MASK_FLAG_NO_UI; + sei.lpVerb = "open"; + sei.lpFile = htmlFilePath.c_str(); + sei.nShow = SW_SHOWNORMAL; + + // browser open will be bypassed in test programs + printf(_("Opening HTML documentation %s\n"), htmlFilePath.c_str()); + if (!bypassBrowserOpen) + { + int ret = ShellExecuteEx(&sei); + if (!ret) + error(_("Command execute failure"), htmlFilePath.c_str()); + } +} + +#else // Linux specific + +/** + * LINUX function to get the current directory. + * This is done if the fileName does not contain a path. + * It is probably from an editor sending a single file. + * + * @param fileName_ The filename is used only for the error message. + * @return The path of the current directory + */ +string ASConsole::getCurrentDirectory(const string& fileName_) const +{ + char* currdir = getenv("PWD"); + if (currdir == NULL) + error("Cannot find file", fileName_.c_str()); + return string(currdir); +} + +/** + * LINUX function to resolve wildcards and recurse into sub directories. + * The fileName vector is filled with the path and names of files to process. + * + * @param directory The path of the directory to be processed. + * @param wildcard The wildcard to be processed (e.g. *.cpp). + */ +void ASConsole::getFileNames(const string& directory, const string& wildcard) +{ + struct dirent* entry; // entry from readdir() + struct stat statbuf; // entry from stat() + vector subDirectory; // sub directories of this directory + + // errno is defined in and is set for errors in opendir, readdir, or stat + errno = 0; + + DIR* dp = opendir(directory.c_str()); + if (dp == NULL) + error(_("Cannot open directory"), directory.c_str()); + + // save the first fileName entry for this recursion + const unsigned firstEntry = fileName.size(); + + // save files and sub directories + while ((entry = readdir(dp)) != NULL) + { + // get file status + string entryFilepath = directory + g_fileSeparator + entry->d_name; + if (stat(entryFilepath.c_str(), &statbuf) != 0) + { + if (errno == EOVERFLOW) // file over 2 GB is OK + { + errno = 0; + continue; + } + perror("errno message"); + error("Error getting file status in directory", directory.c_str()); + } + // skip hidden or read only + if (entry->d_name[0] == '.' || !(statbuf.st_mode & S_IWUSR)) + continue; + // if a sub directory and recursive, save sub directory + if (S_ISDIR(statbuf.st_mode) && isRecursive) + { + if (isPathExclued(entryFilepath)) + printMsg(_("Exclude %s\n"), entryFilepath.substr(mainDirectoryLength)); + else + subDirectory.push_back(entryFilepath); + continue; + } + + // if a file, save file name + if (S_ISREG(statbuf.st_mode)) + { + // check exclude before wildcmp to avoid "unmatched exclude" error + bool isExcluded = isPathExclued(entryFilepath); + // save file name if wildcard match + if (wildcmp(wildcard.c_str(), entry->d_name)) + { + if (isExcluded) + printMsg(_("Exclude %s\n"), entryFilepath.substr(mainDirectoryLength)); + else + fileName.push_back(entryFilepath); + } + } + } + + if (closedir(dp) != 0) + { + perror("errno message"); + error("Error reading directory", directory.c_str()); + } + + // sort the current entries for fileName + if (firstEntry < fileName.size()) + sort(&fileName[firstEntry], &fileName[fileName.size()]); + + // recurse into sub directories + // if not doing recursive, subDirectory is empty + if (subDirectory.size() > 1) + sort(subDirectory.begin(), subDirectory.end()); + for (unsigned i = 0; i < subDirectory.size(); i++) + { + getFileNames(subDirectory[i], wildcard); + } + + return; +} + +/** + * LINUX function to get locale information and call getNumberFormat. + * This formats positive integers only, no float. + * + * @param num The number to be formatted. + * size_t is for compatibility with the Windows function. + * @return The formatted number. + */ +string ASConsole::getNumberFormat(int num, size_t) const +{ +#if defined(_MSC_VER) || defined(__MINGW32__) || defined(__BORLANDC__) || defined(__GNUC__) + // Compilers that don't support C++ locales should still support this assert. + // The C locale should be set but not the C++. + // This function is not necessary if the C++ locale is set. + // The locale().name() return value is not portable to all compilers. + assert(locale().name() == "C"); +#endif + + // get the locale info + struct lconv* lc; + lc = localeconv(); + + // format the number + return getNumberFormat(num, lc->grouping, lc->thousands_sep); +} + +/** + * LINUX function to format a number according to the current locale. + * This formats positive integers only, no float. + * + * @param num The number to be formatted. + * @param groupingArg The grouping string from the locale. + * @param separator The thousands group separator from the locale. + * @return The formatted number. + */ +string ASConsole::getNumberFormat(int num, const char* groupingArg, const char* separator) const +{ + // convert num to a string + stringstream alphaNum; + alphaNum << num; + string number = alphaNum.str(); + // format the number from right to left + string formattedNum; + size_t ig = 0; // grouping index + int grouping = groupingArg[ig]; + int i = number.length(); + // check for no grouping + if (grouping == 0) + grouping = number.length(); + while (i > 0) + { + // extract a group of numbers + string group; + if (i < grouping) + group = number; + else + group = number.substr(i - grouping); + // update formatted number + formattedNum.insert(0, group); + i -= grouping; + if (i < 0) + i = 0; + if (i > 0) + formattedNum.insert(0, separator); + number.erase(i); + // update grouping + if (groupingArg[ig] != '\0' + && groupingArg[ig + 1] != '\0') + grouping = groupingArg[++ig]; + } + return formattedNum; +} + +/** + * LINUX function to open a HTML file in the default browser. + * Use xdg-open from freedesktop.org cross-desktop compatibility suite xdg-utils. + * see http://portland.freedesktop.org/wiki/ + * This is installed on most modern distributions. + */ +void ASConsole::launchDefaultBrowser(const char* filePathIn /*NULL*/) const +{ + struct stat statbuf; + string htmlDefaultPath = "/usr/share/doc/astyle/html/"; + string htmlDefaultFile = "astyle.html"; + + // build file path + string htmlFilePath; + if (filePathIn == NULL) + htmlFilePath = htmlDefaultPath + htmlDefaultFile; + else + { + if (strpbrk(filePathIn, "\\/") == NULL) + htmlFilePath = htmlDefaultPath + filePathIn; + else + htmlFilePath = filePathIn; + } + standardizePath(htmlFilePath); + if (stat(htmlFilePath.c_str(), &statbuf) != 0 || !(statbuf.st_mode & S_IFREG)) + { + printf(_("Cannot open HTML file %s\n"), htmlFilePath.c_str()); + return; + } + + // get search paths + const char* envPaths = getenv("PATH"); + if (envPaths == NULL) + envPaths = "?"; + size_t envlen = strlen(envPaths); + char* paths = new char[envlen + 1]; + strcpy(paths, envPaths); + // find xdg-open (usually in /usr/bin) + // Mac uses open instead +#ifdef __APPLE__ + const char* FILE_OPEN = "open"; +#else + const char* FILE_OPEN = "xdg-open"; +#endif + string searchPath; + char* searchDir = strtok(paths, ":"); + while (searchDir != NULL) + { + searchPath = searchDir; + if (searchPath.length() > 0 + && searchPath[searchPath.length() - 1] != g_fileSeparator) + searchPath.append(string(1, g_fileSeparator)); + searchPath.append(FILE_OPEN); + if (stat(searchPath.c_str(), &statbuf) == 0 && (statbuf.st_mode & S_IFREG)) + break; + searchDir = strtok(NULL, ":"); + } + delete[] paths; + if (searchDir == NULL) + error(_("Command is not installed"), FILE_OPEN); + + // browser open will be bypassed in test programs + printf(_("Opening HTML documentation %s\n"), htmlFilePath.c_str()); + if (!bypassBrowserOpen) + { + execlp(FILE_OPEN, FILE_OPEN, htmlFilePath.c_str(), NULL); + // execlp will NOT return if successful + error(_("Command execute failure"), FILE_OPEN); + } +} + +#endif // _WIN32 + +// get individual file names from the command-line file path +void ASConsole::getFilePaths(string& filePath) +{ + fileName.clear(); + targetDirectory = string(); + targetFilename = string(); + + // separate directory and file name + size_t separator = filePath.find_last_of(g_fileSeparator); + if (separator == string::npos) + { + // if no directory is present, use the currently active directory + targetDirectory = getCurrentDirectory(filePath); + targetFilename = filePath; + mainDirectoryLength = targetDirectory.length() + 1; // +1 includes trailing separator + } + else + { + targetDirectory = filePath.substr(0, separator); + targetFilename = filePath.substr(separator + 1); + mainDirectoryLength = targetDirectory.length() + 1; // +1 includes trailing separator + } + + if (targetFilename.length() == 0) + { + fprintf(stderr, _("Missing filename in %s\n"), filePath.c_str()); + error(); + } + + // check filename for wildcards + hasWildcard = false; + if (targetFilename.find_first_of("*?") != string::npos) + hasWildcard = true; + + // clear exclude hits vector + for (size_t ix = 0; ix < excludeHitsVector.size(); ix++) + excludeHitsVector[ix] = false; + + // If the filename is not quoted on Linux, bash will replace the + // wildcard instead of passing it to the program. + if (isRecursive && !hasWildcard) + { + fprintf(stderr, "%s\n", _("Recursive option with no wildcard")); +#ifndef _WIN32 + fprintf(stderr, "%s\n", _("Did you intend quote the filename")); +#endif + error(); + } + + // display directory name for wildcard processing + if (hasWildcard) + { + printSeparatingLine(); + printMsg(_("Directory %s\n"), targetDirectory + g_fileSeparator + targetFilename); + } + + // create a vector of paths and file names to process + if (hasWildcard || isRecursive) + getFileNames(targetDirectory, targetFilename); + else + { + // verify a single file is not a directory (needed on Linux) + string entryFilepath = targetDirectory + g_fileSeparator + targetFilename; + struct stat statbuf; + if (stat(entryFilepath.c_str(), &statbuf) == 0 && (statbuf.st_mode & S_IFREG)) + fileName.push_back(entryFilepath); + } + + // check for unprocessed excludes + bool excludeErr = false; + for (size_t ix = 0; ix < excludeHitsVector.size(); ix++) + { + if (excludeHitsVector[ix] == false) + { + excludeErr = true; + if (!ignoreExcludeErrorsDisplay) + { + if (ignoreExcludeErrors) + printMsg(_("Exclude (unmatched) %s\n"), excludeVector[ix]); + else + fprintf(stderr, _("Exclude (unmatched) %s\n"), excludeVector[ix].c_str()); + } + else + { + if (!ignoreExcludeErrors) + fprintf(stderr, _("Exclude (unmatched) %s\n"), excludeVector[ix].c_str()); + } + } + } + + if (excludeErr && !ignoreExcludeErrors) + { + if (hasWildcard && !isRecursive) + fprintf(stderr, "%s\n", _("Did you intend to use --recursive")); + error(); + } + + // check if files were found (probably an input error if not) + if (fileName.empty()) + { + fprintf(stderr, _("No file to process %s\n"), filePath.c_str()); + if (hasWildcard && !isRecursive) + fprintf(stderr, "%s\n", _("Did you intend to use --recursive")); + error(); + } + + if (hasWildcard) + printSeparatingLine(); +} + +bool ASConsole::fileNameVectorIsEmpty() const +{ + return fileNameVector.empty(); +} + +bool ASConsole::isOption(const string& arg, const char* op) +{ + return arg.compare(op) == 0; +} + +bool ASConsole::isOption(const string& arg, const char* a, const char* b) +{ + return (isOption(arg, a) || isOption(arg, b)); +} + +bool ASConsole::isParamOption(const string& arg, const char* option) +{ + bool retVal = arg.compare(0, strlen(option), option) == 0; + // if comparing for short option, 2nd char of arg must be numeric + if (retVal && strlen(option) == 1 && arg.length() > 1) + if (!isdigit((unsigned char)arg[1])) + retVal = false; + return retVal; +} + +// compare a path to the exclude vector +// used for both directories and filenames +// updates the g_excludeHitsVector +// return true if a match +bool ASConsole::isPathExclued(const string& subPath) +{ + bool retVal = false; + + // read the exclude vector checking for a match + for (size_t i = 0; i < excludeVector.size(); i++) + { + string exclude = excludeVector[i]; + + if (subPath.length() < exclude.length()) + continue; + + size_t compareStart = subPath.length() - exclude.length(); + // subPath compare must start with a directory name + if (compareStart > 0) + { + char lastPathChar = subPath[compareStart - 1]; + if (lastPathChar != g_fileSeparator) + continue; + } + + string compare = subPath.substr(compareStart); + if (!g_isCaseSensitive) + { + // make it case insensitive for Windows + for (size_t j = 0; j < compare.length(); j++) + compare[j] = (char)tolower(compare[j]); + for (size_t j = 0; j < exclude.length(); j++) + exclude[j] = (char)tolower(exclude[j]); + } + // compare sub directory to exclude data - must check them all + if (compare == exclude) + { + excludeHitsVector[i] = true; + retVal = true; + break; + } + } + return retVal; +} + +void ASConsole::printHelp() const +{ + cout << endl; + cout << " Artistic Style " << g_version << endl; + cout << " Maintained by: Jim Pattee\n"; + cout << " Original Author: Tal Davidson\n"; + cout << endl; + cout << "Usage:\n"; + cout << "------\n"; + cout << " astyle [OPTIONS] File1 File2 File3 [...]\n"; + cout << endl; + cout << " astyle [OPTIONS] < Original > Beautified\n"; + cout << endl; + cout << " When indenting a specific file, the resulting indented file RETAINS\n"; + cout << " the original file-name. The original pre-indented file is renamed,\n"; + cout << " with a suffix of \'.orig\' added to the original filename.\n"; + cout << endl; + cout << " Wildcards (* and ?) may be used in the filename.\n"; + cout << " A \'recursive\' option can process directories recursively.\n"; + cout << endl; + cout << " By default, astyle is set up to indent with four spaces per indent,\n"; + cout << " a maximal indentation of 40 spaces inside continuous statements,\n"; + cout << " a minimum indentation of eight spaces inside conditional statements,\n"; + cout << " and NO formatting options.\n"; + cout << endl; + cout << "Options:\n"; + cout << "--------\n"; + cout << " This program follows the usual GNU command line syntax.\n"; + cout << " Long options (starting with '--') must be written one at a time.\n"; + cout << " Short options (starting with '-') may be appended together.\n"; + cout << " Thus, -bps4 is the same as -b -p -s4.\n"; + cout << endl; + cout << "Options File:\n"; + cout << "-------------\n"; + cout << " Artistic Style looks for a default options file in the\n"; + cout << " following order:\n"; + cout << " 1. The contents of the ARTISTIC_STYLE_OPTIONS environment\n"; + cout << " variable if it exists.\n"; + cout << " 2. The file called .astylerc in the directory pointed to by the\n"; + cout << " HOME environment variable ( i.e. $HOME/.astylerc ).\n"; + cout << " 3. The file called astylerc in the directory pointed to by the\n"; + cout << " USERPROFILE environment variable (i.e. %USERPROFILE%\\astylerc).\n"; + cout << " If a default options file is found, the options in this file will\n"; + cout << " be parsed BEFORE the command-line options.\n"; + cout << " Long options within the default option file may be written without\n"; + cout << " the preliminary '--'.\n"; + cout << endl; + cout << "Disable Formatting:\n"; + cout << "----------------------\n"; + cout << " Disable Block\n"; + cout << " Blocks of code can be disabled with the comment tags *INDENT-OFF*\n"; + cout << " and *INDENT-ON*. It must be contained in a one-line comment.\n"; + cout << endl; + cout << " Disable Line\n"; + cout << " Padding of operators can be disabled on a single line using the\n"; + cout << " comment tag *NOPAD*. It must be contained in a line-end comment.\n"; + cout << endl; + cout << "Bracket Style Options:\n"; + cout << "----------------------\n"; + cout << " default bracket style\n"; + cout << " If no bracket style is requested, the opening brackets will not be\n"; + cout << " changed and closing brackets will be broken from the preceding line.\n"; + cout << endl; + cout << " --style=allman OR --style=bsd OR --style=break OR -A1\n"; + cout << " Allman style formatting/indenting.\n"; + cout << " Broken brackets.\n"; + cout << endl; + cout << " --style=java OR --style=attach OR -A2\n"; + cout << " Java style formatting/indenting.\n"; + cout << " Attached brackets.\n"; + cout << endl; + cout << " --style=kr OR --style=k&r OR --style=k/r OR -A3\n"; + cout << " Kernighan & Ritchie style formatting/indenting.\n"; + cout << " Linux brackets.\n"; + cout << endl; + cout << " --style=stroustrup OR -A4\n"; + cout << " Stroustrup style formatting/indenting.\n"; + cout << " Stroustrup brackets.\n"; + cout << endl; + cout << " --style=whitesmith OR -A5\n"; + cout << " Whitesmith style formatting/indenting.\n"; + cout << " Broken, indented brackets.\n"; + cout << " Indented class blocks and switch blocks.\n"; + cout << endl; + cout << " --style=vtk OR -A15\n"; + cout << " VTK style formatting/indenting.\n"; + cout << " Broken, indented brackets, except for opening brackets.\n"; + cout << endl; + cout << " --style=banner OR -A6\n"; + cout << " Banner style formatting/indenting.\n"; + cout << " Attached, indented brackets.\n"; + cout << endl; + cout << " --style=gnu OR -A7\n"; + cout << " GNU style formatting/indenting.\n"; + cout << " Broken brackets, indented blocks.\n"; + cout << endl; + cout << " --style=linux OR --style=knf OR -A8\n"; + cout << " Linux style formatting/indenting.\n"; + cout << " Linux brackets, minimum conditional indent is one-half indent.\n"; + cout << endl; + cout << " --style=horstmann OR -A9\n"; + cout << " Horstmann style formatting/indenting.\n"; + cout << " Run-in brackets, indented switches.\n"; + cout << endl; + cout << " --style=1tbs OR --style=otbs OR -A10\n"; + cout << " One True Brace Style formatting/indenting.\n"; + cout << " Linux brackets, add brackets to all conditionals.\n"; + cout << endl; + cout << " --style=google OR -A14\n"; + cout << " Google style formatting/indenting.\n"; + cout << " Attached brackets, indented class modifiers.\n"; + cout << endl; + cout << " --style=pico OR -A11\n"; + cout << " Pico style formatting/indenting.\n"; + cout << " Run-in opening brackets and attached closing brackets.\n"; + cout << " Uses keep one line blocks and keep one line statements.\n"; + cout << endl; + cout << " --style=lisp OR -A12\n"; + cout << " Lisp style formatting/indenting.\n"; + cout << " Attached opening brackets and attached closing brackets.\n"; + cout << " Uses keep one line statements.\n"; + cout << endl; + cout << "Tab Options:\n"; + cout << "------------\n"; + cout << " default indent option\n"; + cout << " If no indentation option is set, the default\n"; + cout << " option of 4 spaces per indent will be used.\n"; + cout << endl; + cout << " --indent=spaces=# OR -s#\n"; + cout << " Indent using # spaces per indent. Not specifying #\n"; + cout << " will result in a default of 4 spaces per indent.\n"; + cout << endl; + cout << " --indent=tab OR --indent=tab=# OR -t OR -t#\n"; + cout << " Indent using tab characters, assuming that each\n"; + cout << " indent is # spaces long. Not specifying # will result\n"; + cout << " in a default assumption of 4 spaces per indent.\n"; + cout << endl; + cout << " --indent=force-tab=# OR -T#\n"; + cout << " Indent using tab characters, assuming that each\n"; + cout << " indent is # spaces long. Force tabs to be used in areas\n"; + cout << " AStyle would prefer to use spaces.\n"; + cout << endl; + cout << " --indent=force-tab-x=# OR -xT#\n"; + cout << " Allows the tab length to be set to a length that is different\n"; + cout << " from the indent length. This may cause the indentation to be\n"; + cout << " a mix of both spaces and tabs. This option sets the tab length.\n"; + cout << endl; + cout << "Bracket Modify Options:\n"; + cout << "-----------------------\n"; + cout << " --attach-namespaces OR -xn\n"; + cout << " Attach brackets to a namespace statement.\n"; + cout << endl; + cout << " --attach-classes OR -xc\n"; + cout << " Attach brackets to a class statement.\n"; + cout << endl; + cout << " --attach-inlines OR -xl\n"; + cout << " Attach brackets to class inline function definitions.\n"; + cout << endl; + cout << " --attach-extern-c OR -xk\n"; + cout << " Attach brackets to an extern \"C\" statement.\n"; + cout << endl; + cout << "Indentation Options:\n"; + cout << "--------------------\n"; + cout << " --indent-classes OR -C\n"; + cout << " Indent 'class' blocks so that the entire block is indented.\n"; + cout << endl; + cout << " --indent-modifiers OR -xG\n"; + cout << " Indent 'class' access modifiers, 'public:', 'protected:' or\n"; + cout << " 'private:', one half indent. The rest of the class is not\n"; + cout << " indented. \n"; + cout << endl; + cout << " --indent-switches OR -S\n"; + cout << " Indent 'switch' blocks, so that the inner 'case XXX:'\n"; + cout << " headers are indented in relation to the switch block.\n"; + cout << endl; + cout << " --indent-cases OR -K\n"; + cout << " Indent case blocks from the 'case XXX:' headers.\n"; + cout << " Case statements not enclosed in blocks are NOT indented.\n"; + cout << endl; + cout << " --indent-namespaces OR -N\n"; + cout << " Indent the contents of namespace blocks.\n"; + cout << endl; + cout << " --indent-labels OR -L\n"; + cout << " Indent labels so that they appear one indent less than\n"; + cout << " the current indentation level, rather than being\n"; + cout << " flushed completely to the left (which is the default).\n"; + cout << endl; + cout << " --indent-preproc-block OR -xW\n"; + cout << " Indent preprocessor blocks at bracket level 0.\n"; + cout << " Without this option the preprocessor block is not indented.\n"; + cout << endl; + cout << " --indent-preproc-cond OR -xw\n"; + cout << " Indent preprocessor conditional statements #if/#else/#endif\n"; + cout << " to the same level as the source code.\n"; + cout << endl; + cout << " --indent-preproc-define OR -w\n"; + cout << " Indent multi-line preprocessor #define statements.\n"; + cout << endl; + cout << " --indent-col1-comments OR -Y\n"; + cout << " Indent line comments that start in column one.\n"; + cout << endl; + cout << " --min-conditional-indent=# OR -m#\n"; + cout << " Indent a minimal # spaces in a continuous conditional\n"; + cout << " belonging to a conditional header.\n"; + cout << " The valid values are:\n"; + cout << " 0 - no minimal indent.\n"; + cout << " 1 - indent at least one additional indent.\n"; + cout << " 2 - indent at least two additional indents.\n"; + cout << " 3 - indent at least one-half an additional indent.\n"; + cout << " The default value is 2, two additional indents.\n"; + cout << endl; + cout << " --max-instatement-indent=# OR -M#\n"; + cout << " Indent a maximal # spaces in a continuous statement,\n"; + cout << " relative to the previous line.\n"; + cout << " The valid values are 40 thru 120.\n"; + cout << " The default value is 40.\n"; + cout << endl; + cout << "Padding Options:\n"; + cout << "----------------\n"; + cout << " --break-blocks OR -f\n"; + cout << " Insert empty lines around unrelated blocks, labels, classes, ...\n"; + cout << endl; + cout << " --break-blocks=all OR -F\n"; + cout << " Like --break-blocks, except also insert empty lines \n"; + cout << " around closing headers (e.g. 'else', 'catch', ...).\n"; + cout << endl; + cout << " --pad-oper OR -p\n"; + cout << " Insert space padding around operators.\n"; + cout << endl; + cout << " --pad-comma OR -xg\n"; + cout << " Insert space padding around commas and semicolons.\n"; + cout << endl; + cout << " --pad-paren OR -P\n"; + cout << " Insert space padding around parenthesis on both the outside\n"; + cout << " and the inside.\n"; + cout << endl; + cout << " --pad-paren-out OR -d\n"; + cout << " Insert space padding around parenthesis on the outside only.\n"; + cout << endl; + cout << " --pad-first-paren-out OR -xd\n"; + cout << " Insert space padding around first parenthesis in a series on\n"; + cout << " the outside only.\n"; + cout << endl; + cout << " --pad-paren-in OR -D\n"; + cout << " Insert space padding around parenthesis on the inside only.\n"; + cout << endl; + cout << " --pad-header OR -H\n"; + cout << " Insert space padding after paren headers (e.g. 'if', 'for'...).\n"; + cout << endl; + cout << " --unpad-paren OR -U\n"; + cout << " Remove unnecessary space padding around parenthesis. This\n"; + cout << " can be used in combination with the 'pad' options above.\n"; + cout << endl; + cout << " --delete-empty-lines OR -xd\n"; + cout << " Delete empty lines within a function or method.\n"; + cout << " It will NOT delete lines added by the break-blocks options.\n"; + cout << endl; + cout << " --fill-empty-lines OR -E\n"; + cout << " Fill empty lines with the white space of their\n"; + cout << " previous lines.\n"; + cout << endl; + cout << " --align-pointer=type OR -k1\n"; + cout << " --align-pointer=middle OR -k2\n"; + cout << " --align-pointer=name OR -k3\n"; + cout << " Attach a pointer or reference operator (*, &, or ^) to either\n"; + cout << " the operator type (left), middle, or operator name (right).\n"; + cout << " To align the reference separately use --align-reference.\n"; + cout << endl; + cout << " --align-reference=none OR -W0\n"; + cout << " --align-reference=type OR -W1\n"; + cout << " --align-reference=middle OR -W2\n"; + cout << " --align-reference=name OR -W3\n"; + cout << " Attach a reference operator (&) to either\n"; + cout << " the operator type (left), middle, or operator name (right).\n"; + cout << " If not set, follow pointer alignment.\n"; + cout << endl; + cout << "Formatting Options:\n"; + cout << "-------------------\n"; + cout << " --break-closing-brackets OR -y\n"; + cout << " Break brackets before closing headers (e.g. 'else', 'catch', ...).\n"; + cout << " Use with --style=java, --style=kr, --style=stroustrup,\n"; + cout << " --style=linux, or --style=1tbs.\n"; + cout << endl; + cout << " --break-elseifs OR -e\n"; + cout << " Break 'else if()' statements into two different lines.\n"; + cout << endl; + cout << " --add-brackets OR -j\n"; + cout << " Add brackets to unbracketed one line conditional statements.\n"; + cout << endl; + cout << " --add-one-line-brackets OR -J\n"; + cout << " Add one line brackets to unbracketed one line conditional\n"; + cout << " statements.\n"; + cout << endl; + cout << " --remove-brackets OR -xj\n"; + cout << " Remove brackets from a bracketed one line conditional statements.\n"; + cout << endl; + cout << " --keep-one-line-blocks OR -O\n"; + cout << " Don't break blocks residing completely on one line.\n"; + cout << endl; + cout << " --keep-one-line-statements OR -o\n"; + cout << " Don't break lines containing multiple statements into\n"; + cout << " multiple single-statement lines.\n"; + cout << endl; + cout << " --convert-tabs OR -c\n"; + cout << " Convert tabs to the appropriate number of spaces.\n"; + cout << endl; + cout << " --close-templates OR -xy\n"; + cout << " Close ending angle brackets on template definitions.\n"; + cout << endl; + cout << " --remove-comment-prefix OR -xp\n"; + cout << " Remove the leading '*' prefix on multi-line comments and\n"; + cout << " indent the comment text one indent.\n"; + cout << endl; + cout << " --max-code-length=# OR -xC#\n"; + cout << " --break-after-logical OR -xL\n"; + cout << " max-code-length=# will break the line if it exceeds more than\n"; + cout << " # characters. The valid values are 50 thru 200.\n"; + cout << " If the line contains logical conditionals they will be placed\n"; + cout << " first on the new line. The option break-after-logical will\n"; + cout << " cause the logical conditional to be placed last on the\n"; + cout << " previous line.\n"; + cout << endl; + cout << " --mode=c\n"; + cout << " Indent a C or C++ source file (this is the default).\n"; + cout << endl; + cout << " --mode=java\n"; + cout << " Indent a Java source file.\n"; + cout << endl; + cout << " --mode=cs\n"; + cout << " Indent a C# source file.\n"; + cout << endl; + cout << "Objective-C Options:\n"; + cout << "--------------------\n"; + cout << " --pad-method-prefix OR -xQ\n"; + cout << " Insert space padding after the '-' or '+' Objective-C\n"; + cout << " method prefix.\n"; + cout << endl; + cout << " --unpad-method-prefix OR -xR\n"; + cout << " Remove all space padding after the '-' or '+' Objective-C\n"; + cout << " method prefix.\n"; + cout << endl; + cout << " --pad-return-type OR -xq\n"; + cout << " Insert space padding after the Objective-C return type.\n"; + cout << endl; + cout << " --unpad-return-type OR -xr\n"; + cout << " Remove all space padding after the Objective-C return type.\n"; + cout << endl; + cout << " --align-method-colon OR -xM\n"; + cout << " Align the colons in an Objective-C method definition.\n"; + cout << endl; + cout << " --pad-method-colon=none OR -xP\n"; + cout << " --pad-method-colon=all OR -xP1\n"; + cout << " --pad-method-colon=after OR -xP2\n"; + cout << " --pad-method-colon=before OR -xP3\n"; + cout << " Add or remove space padding before or after the colons in an\n"; + cout << " Objective-C method call.\n"; + cout << endl; + cout << "Other Options:\n"; + cout << "--------------\n"; + cout << " --suffix=####\n"; + cout << " Append the suffix #### instead of '.orig' to original filename.\n"; + cout << endl; + cout << " --suffix=none OR -n\n"; + cout << " Do not retain a backup of the original file.\n"; + cout << endl; + cout << " --recursive OR -r OR -R\n"; + cout << " Process subdirectories recursively.\n"; + cout << endl; + cout << " --dry-run\n"; + cout << " Perform a trial run with no changes made to check for formatting.\n"; + cout << endl; + cout << " --exclude=####\n"; + cout << " Specify a file or directory #### to be excluded from processing.\n"; + cout << endl; + cout << " --ignore-exclude-errors OR -i\n"; + cout << " Allow processing to continue if there are errors in the exclude=####\n"; + cout << " options. It will display the unmatched excludes.\n"; + cout << endl; + cout << " --ignore-exclude-errors-x OR -xi\n"; + cout << " Allow processing to continue if there are errors in the exclude=####\n"; + cout << " options. It will NOT display the unmatched excludes.\n"; + cout << endl; + cout << " --errors-to-stdout OR -X\n"; + cout << " Print errors and help information to standard-output rather than\n"; + cout << " to standard-error.\n"; + cout << endl; + cout << " --preserve-date OR -Z\n"; + cout << " Preserve the original file's date and time modified. The time\n"; + cout << " modified will be changed a few micro seconds to force a compile.\n"; + cout << endl; + cout << " --verbose OR -v\n"; + cout << " Verbose mode. Extra informational messages will be displayed.\n"; + cout << endl; + cout << " --formatted OR -Q\n"; + cout << " Formatted display mode. Display only the files that have been\n"; + cout << " formatted.\n"; + cout << endl; + cout << " --quiet OR -q\n"; + cout << " Quiet mode. Suppress all output except error messages.\n"; + cout << endl; + cout << " --lineend=windows OR -z1\n"; + cout << " --lineend=linux OR -z2\n"; + cout << " --lineend=macold OR -z3\n"; + cout << " Force use of the specified line end style. Valid options\n"; + cout << " are windows (CRLF), linux (LF), and macold (CR).\n"; + cout << endl; + cout << "Command Line Only:\n"; + cout << "------------------\n"; + cout << " --options=####\n"; + cout << " Specify an options file #### to read and use.\n"; + cout << endl; + cout << " --options=none\n"; + cout << " Disable the default options file.\n"; + cout << " Only the command-line parameters will be used.\n"; + cout << endl; + cout << " --ascii OR -I\n"; + cout << " The displayed output will be ascii characters only.\n"; + cout << endl; + cout << " --version OR -V\n"; + cout << " Print version number.\n"; + cout << endl; + cout << " --help OR -h OR -?\n"; + cout << " Print this help message.\n"; + cout << endl; + cout << " --html OR -!\n"; + cout << " Open the HTML help file \"astyle.html\" in the default browser.\n"; + cout << " The documentation must be installed in the standard install path.\n"; + cout << endl; + cout << " --html=####\n"; + cout << " Open a HTML help file in the default browser using the file path\n"; + cout << " ####. The path may include a directory path and a file name, or a\n"; + cout << " file name only. Paths containing spaces must be enclosed in quotes.\n"; + cout << endl; + cout << endl; +} + +/** + * Process files in the fileNameVector. + */ +void ASConsole::processFiles() +{ + if (isVerbose) + printVerboseHeader(); + + clock_t startTime = clock(); // start time of file formatting + + // loop thru input fileNameVector and process the files + for (size_t i = 0; i < fileNameVector.size(); i++) + { + getFilePaths(fileNameVector[i]); + + // loop thru fileName vector formatting the files + for (size_t j = 0; j < fileName.size(); j++) + formatFile(fileName[j]); + } + + // files are processed, display stats + if (isVerbose) + printVerboseStats(startTime); +} + +// process options from the command line and options file +// build the vectors fileNameVector, excludeVector, optionsVector, and fileOptionsVector +void ASConsole::processOptions(vector& argvOptions) +{ + string arg; + bool ok = true; + bool shouldParseOptionsFile = true; + + // get command line options + for (size_t i = 0; i < argvOptions.size(); i++) + { + arg = argvOptions[i]; + + if ( isOption(arg, "-I" ) + || isOption(arg, "--ascii") ) + { + useAscii = true; + setlocale(LC_ALL, "C"); // use English decimal indicator + localizer.setLanguageFromName("en"); + } + else if ( isOption(arg, "--options=none") ) + { + shouldParseOptionsFile = false; + } + else if ( isParamOption(arg, "--options=") ) + { + optionsFileName = getParam(arg, "--options="); + optionsFileRequired = true; + if (optionsFileName.compare("") == 0) + setOptionsFileName(" "); + } + else if ( isOption(arg, "-h") + || isOption(arg, "--help") + || isOption(arg, "-?") ) + { + printHelp(); + exit(EXIT_SUCCESS); + } + else if ( isOption(arg, "-!") + || isOption(arg, "--html") ) + { + launchDefaultBrowser(); + exit(EXIT_SUCCESS); + } + else if ( isParamOption(arg, "--html=") ) + { + string htmlFilePath = getParam(arg, "--html="); + launchDefaultBrowser(htmlFilePath.c_str()); + exit(EXIT_SUCCESS); + } + else if ( isOption(arg, "-V" ) + || isOption(arg, "--version") ) + { + printf("Artistic Style Version %s\n", g_version); + exit(EXIT_SUCCESS); + } + else if (arg[0] == '-') + { + optionsVector.push_back(arg); + } + else // file-name + { + standardizePath(arg); + fileNameVector.push_back(arg); + } + } + + // get options file path and name + if (shouldParseOptionsFile) + { + if (optionsFileName.compare("") == 0) + { + char* env = getenv("ARTISTIC_STYLE_OPTIONS"); + if (env != NULL) + setOptionsFileName(env); + } + if (optionsFileName.compare("") == 0) + { + char* env = getenv("HOME"); + if (env != NULL) + setOptionsFileName(string(env) + "/.astylerc"); + } + if (optionsFileName.compare("") == 0) + { + char* env = getenv("USERPROFILE"); + if (env != NULL) + setOptionsFileName(string(env) + "/astylerc"); + } + if (optionsFileName.compare("") != 0) + standardizePath(optionsFileName); + } + + // create the options file vector and parse the options for errors + ASOptions options(formatter); + if (optionsFileName.compare("") != 0) + { + ifstream optionsIn(optionsFileName.c_str()); + if (optionsIn) + { + options.importOptions(optionsIn, fileOptionsVector); + ok = options.parseOptions(fileOptionsVector, + string(_("Invalid option file options:"))); + } + else + { + if (optionsFileRequired) + error(_("Cannot open options file"), optionsFileName.c_str()); + optionsFileName.clear(); + } + optionsIn.close(); + } + if (!ok) + { + (*_err) << options.getOptionErrors() << endl; + (*_err) << _("For help on options type 'astyle -h'") << endl; + error(); + } + + // parse the command line options vector for errors + ok = options.parseOptions(optionsVector, + string(_("Invalid command line options:"))); + if (!ok) + { + (*_err) << options.getOptionErrors() << endl; + (*_err) << _("For help on options type 'astyle -h'") << endl; + error(); + } +} + +// remove a file and check for an error +void ASConsole::removeFile(const char* fileName_, const char* errMsg) const +{ + if (remove(fileName_)) + { + if (errno == ENOENT) // no file is OK + errno = 0; + if (errno) + { + perror("errno message"); + error(errMsg, fileName_); + } + } +} + +// rename a file and check for an error +void ASConsole::renameFile(const char* oldFileName, const char* newFileName, const char* errMsg) const +{ + int result = rename(oldFileName, newFileName); + if (result != 0) + { + // if file still exists the remove needs more time - retry + if (errno == EEXIST) + { + errno = 0; + waitForRemove(newFileName); + result = rename(oldFileName, newFileName); + } + if (result != 0) + { + perror("errno message"); + error(errMsg, oldFileName); + } + } +} + +// make sure file separators are correct type (Windows or Linux) +// remove ending file separator +// remove beginning file separator if requested and NOT a complete file path +void ASConsole::standardizePath(string& path, bool removeBeginningSeparator /*false*/) const +{ +#ifdef __VMS + struct FAB fab; + struct NAML naml; + char less[NAML$C_MAXRSS]; + char sess[NAM$C_MAXRSS]; + int r0_status; + + // If we are on a VMS system, translate VMS style filenames to unix + // style. + fab = cc$rms_fab; + fab.fab$l_fna = (char*) - 1; + fab.fab$b_fns = 0; + fab.fab$l_naml = &naml; + naml = cc$rms_naml; + strcpy(sess, path.c_str()); + naml.naml$l_long_filename = (char*)sess; + naml.naml$l_long_filename_size = path.length(); + naml.naml$l_long_expand = less; + naml.naml$l_long_expand_alloc = sizeof(less); + naml.naml$l_esa = sess; + naml.naml$b_ess = sizeof(sess); + naml.naml$v_no_short_upcase = 1; + r0_status = sys$parse(&fab); + if (r0_status == RMS$_SYN) + { + error("File syntax error", path.c_str()); + } + else + { + if (!$VMS_STATUS_SUCCESS(r0_status)) + { + (void)lib$signal (r0_status); + } + } + less[naml.naml$l_long_expand_size - naml.naml$b_ver] = '\0'; + sess[naml.naml$b_esl - naml.naml$b_ver] = '\0'; + if (naml.naml$l_long_expand_size > naml.naml$b_esl) + { + path = decc$translate_vms (less); + } + else + { + path = decc$translate_vms(sess); + } +#endif /* __VMS */ + + // make sure separators are correct type (Windows or Linux) + for (size_t i = 0; i < path.length(); i++) + { + i = path.find_first_of("/\\", i); + if (i == string::npos) + break; + path[i] = g_fileSeparator; + } + // remove beginning separator if requested + if (removeBeginningSeparator && (path[0] == g_fileSeparator)) + path.erase(0, 1); +} + +void ASConsole::printMsg(const char* msg, const string& data) const +{ + if (isQuiet) + return; + printf(msg, data.c_str()); +} + +void ASConsole::printSeparatingLine() const +{ + string line; + for (size_t i = 0; i < 60; i++) + line.append("-"); + printMsg("%s\n", line); +} + +void ASConsole::printVerboseHeader() const +{ + assert(isVerbose); + if (isQuiet) + return; + // get the date + struct tm* ptr; + time_t lt; + char str[20]; + lt = time(NULL); + ptr = localtime(<); + strftime(str, 20, "%x", ptr); + // print the header + printf("Artistic Style %s %s\n", g_version, str); + // print options file + if (!optionsFileName.empty()) + printf(_("Using default options file %s\n"), optionsFileName.c_str()); +} + +void ASConsole::printVerboseStats(clock_t startTime) const +{ + assert(isVerbose); + if (isQuiet) + return; + if (hasWildcard) + printSeparatingLine(); + string formatted = getNumberFormat(filesFormatted); + string unchanged = getNumberFormat(filesUnchanged); + printf(_(" %s formatted %s unchanged "), formatted.c_str(), unchanged.c_str()); + + // show processing time + clock_t stopTime = clock(); + float secs = (stopTime - startTime) / float (CLOCKS_PER_SEC); + if (secs < 60) + { + if (secs < 2.0) + printf("%.2f", secs); + else if (secs < 20.0) + printf("%.1f", secs); + else + printf("%.0f", secs); + printf("%s", _(" seconds ")); + } + else + { + // show minutes and seconds if time is greater than one minute + int min = (int) secs / 60; + secs -= min * 60; + int minsec = int (secs + .5); + printf(_("%d min %d sec "), min, minsec); + } + + string lines = getNumberFormat(linesOut); + printf(_("%s lines\n"), lines.c_str()); +} + +void ASConsole::sleep(int seconds) const +{ + clock_t endwait; + endwait = clock_t (clock () + seconds * CLOCKS_PER_SEC); + while (clock() < endwait) {} +} + +bool ASConsole::stringEndsWith(const string& str, const string& suffix) const +{ + int strIndex = (int) str.length() - 1; + int suffixIndex = (int) suffix.length() - 1; + + while (strIndex >= 0 && suffixIndex >= 0) + { + if (tolower(str[strIndex]) != tolower(suffix[suffixIndex])) + return false; + + --strIndex; + --suffixIndex; + } + // suffix longer than string + if (strIndex < 0 && suffixIndex >= 0) + return false; + return true; +} + +void ASConsole::updateExcludeVector(string suffixParam) +{ + excludeVector.push_back(suffixParam); + standardizePath(excludeVector.back(), true); + excludeHitsVector.push_back(false); +} + +int ASConsole::waitForRemove(const char* newFileName) const +{ + struct stat stBuf; + int seconds; + // sleep a max of 20 seconds for the remove + for (seconds = 1; seconds <= 20; seconds++) + { + sleep(1); + if (stat(newFileName, &stBuf) != 0) + break; + } + errno = 0; + return seconds; +} + +// From The Code Project http://www.codeproject.com/string/wildcmp.asp +// Written by Jack Handy - jakkhandy@hotmail.com +// Modified to compare case insensitive for Windows +int ASConsole::wildcmp(const char* wild, const char* data) const +{ + const char* cp = NULL, *mp = NULL; + bool cmpval; + + while ((*data) && (*wild != '*')) + { + if (!g_isCaseSensitive) + cmpval = (tolower(*wild) != tolower(*data)) && (*wild != '?'); + else + cmpval = (*wild != *data) && (*wild != '?'); + + if (cmpval) + { + return 0; + } + wild++; + data++; + } + + while (*data) + { + if (*wild == '*') + { + if (!*++wild) + { + return 1; + } + mp = wild; + cp = data + 1; + } + else + { + if (!g_isCaseSensitive) + cmpval = (tolower(*wild) == tolower(*data) || (*wild == '?')); + else + cmpval = (*wild == *data) || (*wild == '?'); + + if (cmpval) + { + wild++; + data++; + } + else + { + wild = mp; + data = cp++; + } + } + } + + while (*wild == '*') + { + wild++; + } + return !*wild; +} + +void ASConsole::writeFile(const string& fileName_, FileEncoding encoding, ostringstream& out) const +{ + // save date accessed and date modified of original file + struct stat stBuf; + bool statErr = false; + if (stat(fileName_.c_str(), &stBuf) == -1) + statErr = true; + + // create a backup + if (!noBackup) + { + string origFileName = fileName_ + origSuffix; + removeFile(origFileName.c_str(), "Cannot remove pre-existing backup file"); + renameFile(fileName_.c_str(), origFileName.c_str(), "Cannot create backup file"); + } + + // write the output file + ofstream fout(fileName_.c_str(), ios::binary | ios::trunc); + if (!fout) + error("Cannot open output file", fileName_.c_str()); + if (encoding == UTF_16LE || encoding == UTF_16BE) + { + // convert utf-8 to utf-16 + bool isBigEndian = (encoding == UTF_16BE); + size_t utf16Size = utf8_16.Utf16LengthFromUtf8(out.str().c_str(), out.str().length()); + char* utf16Out = new char[utf16Size]; + size_t utf16Len = utf8_16.Utf8ToUtf16(const_cast(out.str().c_str()), + out.str().length(), isBigEndian, utf16Out); + assert(utf16Len == utf16Size); + fout << string(utf16Out, utf16Len); + delete [] utf16Out; + } + else + fout << out.str(); + + fout.close(); + + // change date modified to original file date + // Embarcadero must be linked with cw32mt not cw32 + if (preserveDate) + { + if (!statErr) + { + struct utimbuf outBuf; + outBuf.actime = stBuf.st_atime; + // add ticks so 'make' will recognize a change + // Visual Studio 2008 needs more than 1 + outBuf.modtime = stBuf.st_mtime + 10; + if (utime(fileName_.c_str(), &outBuf) == -1) + statErr = true; + } + if (statErr) + { + perror("errno message"); + (*_err) << "********* Cannot preserve file date" << endl; + } + } +} + +//----------------------------------------------------------------------------- +// ASLibrary class +// used by shared object (DLL) calls +//----------------------------------------------------------------------------- + +#else // ASTYLE_LIB + +utf16_t* ASLibrary::formatUtf16(const utf16_t* pSourceIn, // the source to be formatted + const utf16_t* pOptions, // AStyle options + fpError fpErrorHandler, // error handler function + fpAlloc fpMemoryAlloc) const // memory allocation function) +{ + const char* utf8In = convertUtf16ToUtf8(pSourceIn); + if (utf8In == NULL) + { + fpErrorHandler(121, "Cannot convert input utf-16 to utf-8."); + return NULL; + } + const char* utf8Options = convertUtf16ToUtf8(pOptions); + if (utf8Options == NULL) + { + delete [] utf8In; + fpErrorHandler(122, "Cannot convert options utf-16 to utf-8."); + return NULL; + } + // call the Artistic Style formatting function + // cannot use the callers memory allocation here + char* utf8Out = AStyleMain(utf8In, + utf8Options, + fpErrorHandler, + ASLibrary::tempMemoryAllocation); + // finished with these + delete [] utf8In; + delete [] utf8Options; + utf8In = NULL; + utf8Options = NULL; + // AStyle error has already been sent + if (utf8Out == NULL) + return NULL; + // convert text to wide char and return it + utf16_t* utf16Out = convertUtf8ToUtf16(utf8Out, fpMemoryAlloc); + delete [] utf8Out; + utf8Out = NULL; + if (utf16Out == NULL) + { + fpErrorHandler(123, "Cannot convert output utf-8 to utf-16."); + return NULL; + } + return utf16Out; +} + +// STATIC method to allocate temporary memory for AStyle formatting. +// The data will be converted before being returned to the calling program. +char* STDCALL ASLibrary::tempMemoryAllocation(unsigned long memoryNeeded) +{ + char* buffer = new(nothrow) char[memoryNeeded]; + return buffer; +} + +/** + * Convert utf-8 strings to utf16 strings. + * Memory is allocated by the calling program memory allocation function. + * The calling function must check for errors. + */ +utf16_t* ASLibrary::convertUtf8ToUtf16(const char* utf8In, fpAlloc fpMemoryAlloc) const +{ + if (utf8In == NULL) + return NULL; + char* data = const_cast(utf8In); + size_t dataSize = strlen(utf8In); + bool isBigEndian = utf8_16.getBigEndian(); + // return size is in number of CHARs, not utf16_t + size_t utf16Size = (utf8_16.Utf16LengthFromUtf8(data, dataSize) + sizeof(utf16_t)); + char* utf16Out = fpMemoryAlloc(utf16Size); + if (utf16Out == NULL) + return NULL; +#ifdef NDEBUG + utf8_16.Utf8ToUtf16(data, dataSize + 1, isBigEndian, utf16Out); +#else + size_t utf16Len = utf8_16.Utf8ToUtf16(data, dataSize + 1, isBigEndian, utf16Out); + assert(utf16Len == utf16Size); +#endif + assert(utf16Size == (utf8_16.utf16len(reinterpret_cast(utf16Out)) + 1) * sizeof(utf16_t)); + return reinterpret_cast(utf16Out); +} + +/** + * Convert utf16 strings to utf-8. + * The calling function must check for errors and delete the + * allocated memory. + */ +char* ASLibrary::convertUtf16ToUtf8(const utf16_t* utf16In) const +{ + if (utf16In == NULL) + return NULL; + char* data = reinterpret_cast(const_cast(utf16In)); + // size must be in chars + size_t dataSize = utf8_16.utf16len(utf16In) * sizeof(utf16_t); + bool isBigEndian = utf8_16.getBigEndian(); + size_t utf8Size = utf8_16.Utf8LengthFromUtf16(data, dataSize, isBigEndian) + 1; + char* utf8Out = new(nothrow) char[utf8Size]; + if (utf8Out == NULL) + return NULL; +#ifdef NDEBUG + utf8_16.Utf16ToUtf8(data, dataSize + 1, isBigEndian, true, utf8Out); +#else + size_t utf8Len = utf8_16.Utf16ToUtf8(data, dataSize + 1, isBigEndian, true, utf8Out); + assert(utf8Len == utf8Size); +#endif + assert(utf8Size == strlen(utf8Out) + 1); + return utf8Out; +} + +#endif // ASTYLE_LIB + +//----------------------------------------------------------------------------- +// ASOptions class +// used by both console and library builds +//----------------------------------------------------------------------------- + +/** + * parse the options vector + * optionsVector can be either a fileOptionsVector (options file) or an optionsVector (command line) + * + * @return true if no errors, false if errors + */ +bool ASOptions::parseOptions(vector& optionsVector, const string& errorInfo) +{ + vector::iterator option; + string arg, subArg; + optionErrors.clear(); + + for (option = optionsVector.begin(); option != optionsVector.end(); ++option) + { + arg = *option; + + if (arg.compare(0, 2, "--") == 0) + parseOption(arg.substr(2), errorInfo); + else if (arg[0] == '-') + { + size_t i; + + for (i = 1; i < arg.length(); ++i) + { + if (i > 1 + && isalpha((unsigned char)arg[i]) + && arg[i - 1] != 'x') + { + // parse the previous option in subArg + parseOption(subArg, errorInfo); + subArg = ""; + } + // append the current option to subArg + subArg.append(1, arg[i]); + } + // parse the last option + parseOption(subArg, errorInfo); + subArg = ""; + } + else + { + parseOption(arg, errorInfo); + subArg = ""; + } + } + if (optionErrors.str().length() > 0) + return false; + return true; +} + +void ASOptions::parseOption(const string& arg, const string& errorInfo) +{ + if ( isOption(arg, "style=allman") || isOption(arg, "style=bsd") || isOption(arg, "style=break") ) + { + formatter.setFormattingStyle(STYLE_ALLMAN); + } + else if ( isOption(arg, "style=java") || isOption(arg, "style=attach") ) + { + formatter.setFormattingStyle(STYLE_JAVA); + } + else if ( isOption(arg, "style=k&r") || isOption(arg, "style=kr") || isOption(arg, "style=k/r") ) + { + formatter.setFormattingStyle(STYLE_KR); + } + else if ( isOption(arg, "style=stroustrup") ) + { + formatter.setFormattingStyle(STYLE_STROUSTRUP); + } + else if ( isOption(arg, "style=whitesmith") ) + { + formatter.setFormattingStyle(STYLE_WHITESMITH); + } + else if ( isOption(arg, "style=vtk") ) + { + formatter.setFormattingStyle(STYLE_VTK); + } + else if ( isOption(arg, "style=banner") ) + { + formatter.setFormattingStyle(STYLE_BANNER); + } + else if ( isOption(arg, "style=gnu") ) + { + formatter.setFormattingStyle(STYLE_GNU); + } + else if ( isOption(arg, "style=linux") || isOption(arg, "style=knf") ) + { + formatter.setFormattingStyle(STYLE_LINUX); + } + else if ( isOption(arg, "style=horstmann") ) + { + formatter.setFormattingStyle(STYLE_HORSTMANN); + } + else if ( isOption(arg, "style=1tbs") || isOption(arg, "style=otbs") ) + { + formatter.setFormattingStyle(STYLE_1TBS); + } + else if ( isOption(arg, "style=google") ) + { + formatter.setFormattingStyle(STYLE_GOOGLE); + } + else if ( isOption(arg, "style=pico") ) + { + formatter.setFormattingStyle(STYLE_PICO); + } + else if ( isOption(arg, "style=lisp") || isOption(arg, "style=python") ) + { + formatter.setFormattingStyle(STYLE_LISP); + } + else if ( isParamOption(arg, "A") ) + { + int style = 0; + string styleParam = getParam(arg, "A"); + if (styleParam.length() > 0) + style = atoi(styleParam.c_str()); + if (style == 1) + formatter.setFormattingStyle(STYLE_ALLMAN); + else if (style == 2) + formatter.setFormattingStyle(STYLE_JAVA); + else if (style == 3) + formatter.setFormattingStyle(STYLE_KR); + else if (style == 4) + formatter.setFormattingStyle(STYLE_STROUSTRUP); + else if (style == 5) + formatter.setFormattingStyle(STYLE_WHITESMITH); + else if (style == 6) + formatter.setFormattingStyle(STYLE_BANNER); + else if (style == 7) + formatter.setFormattingStyle(STYLE_GNU); + else if (style == 8) + formatter.setFormattingStyle(STYLE_LINUX); + else if (style == 9) + formatter.setFormattingStyle(STYLE_HORSTMANN); + else if (style == 10) + formatter.setFormattingStyle(STYLE_1TBS); + else if (style == 11) + formatter.setFormattingStyle(STYLE_PICO); + else if (style == 12) + formatter.setFormattingStyle(STYLE_LISP); + else if (style == 14) + formatter.setFormattingStyle(STYLE_GOOGLE); + else if (style == 15) + formatter.setFormattingStyle(STYLE_VTK); + else + isOptionError(arg, errorInfo); + } + // must check for mode=cs before mode=c !!! + else if ( isOption(arg, "mode=cs") ) + { + formatter.setSharpStyle(); + formatter.setModeManuallySet(true); + } + else if ( isOption(arg, "mode=c") ) + { + formatter.setCStyle(); + formatter.setModeManuallySet(true); + } + else if ( isOption(arg, "mode=java") ) + { + formatter.setJavaStyle(); + formatter.setModeManuallySet(true); + } + else if ( isParamOption(arg, "t", "indent=tab=") ) + { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "t", "indent=tab="); + if (spaceNumParam.length() > 0) + spaceNum = atoi(spaceNumParam.c_str()); + if (spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); + else + { + formatter.setTabIndentation(spaceNum, false); + } + } + else if ( isOption(arg, "indent=tab") ) + { + formatter.setTabIndentation(4); + } + else if ( isParamOption(arg, "T", "indent=force-tab=") ) + { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "T", "indent=force-tab="); + if (spaceNumParam.length() > 0) + spaceNum = atoi(spaceNumParam.c_str()); + if (spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); + else + { + formatter.setTabIndentation(spaceNum, true); + } + } + else if ( isOption(arg, "indent=force-tab") ) + { + formatter.setTabIndentation(4, true); + } + else if ( isParamOption(arg, "xT", "indent=force-tab-x=") ) + { + int tabNum = 8; + string tabNumParam = getParam(arg, "xT", "indent=force-tab-x="); + if (tabNumParam.length() > 0) + tabNum = atoi(tabNumParam.c_str()); + if (tabNum < 2 || tabNum > 20) + isOptionError(arg, errorInfo); + else + { + formatter.setForceTabXIndentation(tabNum); + } + } + else if ( isOption(arg, "indent=force-tab-x") ) + { + formatter.setForceTabXIndentation(8); + } + else if ( isParamOption(arg, "s", "indent=spaces=") ) + { + int spaceNum = 4; + string spaceNumParam = getParam(arg, "s", "indent=spaces="); + if (spaceNumParam.length() > 0) + spaceNum = atoi(spaceNumParam.c_str()); + if (spaceNum < 2 || spaceNum > 20) + isOptionError(arg, errorInfo); + else + { + formatter.setSpaceIndentation(spaceNum); + } + } + else if ( isOption(arg, "indent=spaces") ) + { + formatter.setSpaceIndentation(4); + } + else if ( isParamOption(arg, "m", "min-conditional-indent=") ) + { + int minIndent = MINCOND_TWO; + string minIndentParam = getParam(arg, "m", "min-conditional-indent="); + if (minIndentParam.length() > 0) + minIndent = atoi(minIndentParam.c_str()); + if (minIndent >= MINCOND_END) + isOptionError(arg, errorInfo); + else + formatter.setMinConditionalIndentOption(minIndent); + } + else if ( isParamOption(arg, "M", "max-instatement-indent=") ) + { + int maxIndent = 40; + string maxIndentParam = getParam(arg, "M", "max-instatement-indent="); + if (maxIndentParam.length() > 0) + maxIndent = atoi(maxIndentParam.c_str()); + if (maxIndent < 40) + isOptionError(arg, errorInfo); + else if (maxIndent > 120) + isOptionError(arg, errorInfo); + else + formatter.setMaxInStatementIndentLength(maxIndent); + } + else if ( isOption(arg, "N", "indent-namespaces") ) + { + formatter.setNamespaceIndent(true); + } + else if ( isOption(arg, "C", "indent-classes") ) + { + formatter.setClassIndent(true); + } + else if ( isOption(arg, "xG", "indent-modifiers") ) + { + formatter.setModifierIndent(true); + } + else if ( isOption(arg, "S", "indent-switches") ) + { + formatter.setSwitchIndent(true); + } + else if ( isOption(arg, "K", "indent-cases") ) + { + formatter.setCaseIndent(true); + } + else if ( isOption(arg, "L", "indent-labels") ) + { + formatter.setLabelIndent(true); + } + else if (isOption(arg, "xW", "indent-preproc-block")) + { + formatter.setPreprocBlockIndent(true); + } + else if ( isOption(arg, "w", "indent-preproc-define") ) + { + formatter.setPreprocDefineIndent(true); + } + else if ( isOption(arg, "xw", "indent-preproc-cond") ) + { + formatter.setPreprocConditionalIndent(true); + } + else if ( isOption(arg, "y", "break-closing-brackets") ) + { + formatter.setBreakClosingHeaderBracketsMode(true); + } + else if ( isOption(arg, "O", "keep-one-line-blocks") ) + { + formatter.setBreakOneLineBlocksMode(false); + } + else if ( isOption(arg, "o", "keep-one-line-statements") ) + { + formatter.setSingleStatementsMode(false); + } + else if ( isOption(arg, "P", "pad-paren") ) + { + formatter.setParensOutsidePaddingMode(true); + formatter.setParensInsidePaddingMode(true); + } + else if ( isOption(arg, "d", "pad-paren-out") ) + { + formatter.setParensOutsidePaddingMode(true); + } + else if ( isOption(arg, "xd", "pad-first-paren-out") ) + { + formatter.setParensFirstPaddingMode(true); + } + else if ( isOption(arg, "D", "pad-paren-in") ) + { + formatter.setParensInsidePaddingMode(true); + } + else if ( isOption(arg, "H", "pad-header") ) + { + formatter.setParensHeaderPaddingMode(true); + } + else if ( isOption(arg, "U", "unpad-paren") ) + { + formatter.setParensUnPaddingMode(true); + } + else if ( isOption(arg, "p", "pad-oper") ) + { + formatter.setOperatorPaddingMode(true); + } + else if (isOption(arg, "xg", "pad-comma")) + { + formatter.setCommaPaddingMode(true); + } + else if ( isOption(arg, "xe", "delete-empty-lines") ) + { + formatter.setDeleteEmptyLinesMode(true); + } + else if ( isOption(arg, "E", "fill-empty-lines") ) + { + formatter.setEmptyLineFill(true); + } + else if ( isOption(arg, "c", "convert-tabs") ) + { + formatter.setTabSpaceConversionMode(true); + } + else if ( isOption(arg, "xy", "close-templates") ) + { + formatter.setCloseTemplatesMode(true); + } + else if ( isOption(arg, "F", "break-blocks=all") ) + { + formatter.setBreakBlocksMode(true); + formatter.setBreakClosingHeaderBlocksMode(true); + } + else if ( isOption(arg, "f", "break-blocks") ) + { + formatter.setBreakBlocksMode(true); + } + else if ( isOption(arg, "e", "break-elseifs") ) + { + formatter.setBreakElseIfsMode(true); + } + else if ( isOption(arg, "j", "add-brackets") ) + { + formatter.setAddBracketsMode(true); + } + else if ( isOption(arg, "J", "add-one-line-brackets") ) + { + formatter.setAddOneLineBracketsMode(true); + } + else if ( isOption(arg, "xj", "remove-brackets") ) + { + formatter.setRemoveBracketsMode(true); + } + else if ( isOption(arg, "Y", "indent-col1-comments") ) + { + formatter.setIndentCol1CommentsMode(true); + } + else if ( isOption(arg, "align-pointer=type") ) + { + formatter.setPointerAlignment(PTR_ALIGN_TYPE); + } + else if ( isOption(arg, "align-pointer=middle") ) + { + formatter.setPointerAlignment(PTR_ALIGN_MIDDLE); + } + else if ( isOption(arg, "align-pointer=name") ) + { + formatter.setPointerAlignment(PTR_ALIGN_NAME); + } + else if ( isParamOption(arg, "k") ) + { + int align = 0; + string styleParam = getParam(arg, "k"); + if (styleParam.length() > 0) + align = atoi(styleParam.c_str()); + if (align < 1 || align > 3) + isOptionError(arg, errorInfo); + else if (align == 1) + formatter.setPointerAlignment(PTR_ALIGN_TYPE); + else if (align == 2) + formatter.setPointerAlignment(PTR_ALIGN_MIDDLE); + else if (align == 3) + formatter.setPointerAlignment(PTR_ALIGN_NAME); + } + else if ( isOption(arg, "align-reference=none") ) + { + formatter.setReferenceAlignment(REF_ALIGN_NONE); + } + else if ( isOption(arg, "align-reference=type") ) + { + formatter.setReferenceAlignment(REF_ALIGN_TYPE); + } + else if ( isOption(arg, "align-reference=middle") ) + { + formatter.setReferenceAlignment(REF_ALIGN_MIDDLE); + } + else if ( isOption(arg, "align-reference=name") ) + { + formatter.setReferenceAlignment(REF_ALIGN_NAME); + } + else if ( isParamOption(arg, "W") ) + { + int align = 0; + string styleParam = getParam(arg, "W"); + if (styleParam.length() > 0) + align = atoi(styleParam.c_str()); + if (align < 0 || align > 3) + isOptionError(arg, errorInfo); + else if (align == 0) + formatter.setReferenceAlignment(REF_ALIGN_NONE); + else if (align == 1) + formatter.setReferenceAlignment(REF_ALIGN_TYPE); + else if (align == 2) + formatter.setReferenceAlignment(REF_ALIGN_MIDDLE); + else if (align == 3) + formatter.setReferenceAlignment(REF_ALIGN_NAME); + } + else if ( isParamOption(arg, "max-code-length=") ) + { + int maxLength = 50; + string maxLengthParam = getParam(arg, "max-code-length="); + if (maxLengthParam.length() > 0) + maxLength = atoi(maxLengthParam.c_str()); + if (maxLength < 50) + isOptionError(arg, errorInfo); + else if (maxLength > 200) + isOptionError(arg, errorInfo); + else + formatter.setMaxCodeLength(maxLength); + } + else if ( isParamOption(arg, "xC") ) + { + int maxLength = 50; + string maxLengthParam = getParam(arg, "xC"); + if (maxLengthParam.length() > 0) + maxLength = atoi(maxLengthParam.c_str()); + if (maxLength > 200) + isOptionError(arg, errorInfo); + else + formatter.setMaxCodeLength(maxLength); + } + else if ( isOption(arg, "xL", "break-after-logical") ) + { + formatter.setBreakAfterMode(true); + } + else if ( isOption(arg, "xc", "attach-classes") ) + { + formatter.setAttachClass(true); + } + else if ( isOption(arg, "xk", "attach-extern-c") ) + { + formatter.setAttachExternC(true); + } + else if ( isOption(arg, "xn", "attach-namespaces") ) + { + formatter.setAttachNamespace(true); + } + else if ( isOption(arg, "xl", "attach-inlines") ) + { + formatter.setAttachInline(true); + } + else if ( isOption(arg, "xp", "remove-comment-prefix") ) + { + formatter.setStripCommentPrefix(true); + } + // Objective-C options + else if ( isOption(arg, "xQ", "pad-method-prefix") ) + { + formatter.setMethodPrefixPaddingMode(true); + } + else if ( isOption(arg, "xR", "unpad-method-prefix") ) + { + formatter.setMethodPrefixUnPaddingMode(true); + } + else if (isOption(arg, "xq", "pad-return-type")) + { + formatter.setReturnTypePaddingMode(true); + } + else if (isOption(arg, "xr", "unpad-return-type")) + { + formatter.setReturnTypeUnPaddingMode(true); + } + else if (isOption(arg, "xM", "align-method-colon")) + { + formatter.setAlignMethodColon(true); + } + else if ( isOption(arg, "xP0", "pad-method-colon=none") ) + { + formatter.setObjCColonPaddingMode(COLON_PAD_NONE); + } + else if ( isOption(arg, "xP1", "pad-method-colon=all") ) + { + formatter.setObjCColonPaddingMode(COLON_PAD_ALL); + } + else if ( isOption(arg, "xP2", "pad-method-colon=after") ) + { + formatter.setObjCColonPaddingMode(COLON_PAD_AFTER); + } + else if ( isOption(arg, "xP3", "pad-method-colon=before") ) + { + formatter.setObjCColonPaddingMode(COLON_PAD_BEFORE); + } + // depreciated options //////////////////////////////////////////////////////////////////////////////////////////// + else if ( isOption(arg, "indent-preprocessor") ) // depreciated release 2.04 + { + formatter.setPreprocDefineIndent(true); + } + else if ( isOption(arg, "style=ansi") ) // depreciated release 2.05 + { + formatter.setFormattingStyle(STYLE_ALLMAN); + } +// NOTE: Removed in release 2.04. +// else if ( isOption(arg, "b", "brackets=break") ) +// { +// formatter.setBracketFormatMode(BREAK_MODE); +// } +// else if ( isOption(arg, "a", "brackets=attach") ) +// { +// formatter.setBracketFormatMode(ATTACH_MODE); +// } +// else if ( isOption(arg, "l", "brackets=linux") ) +// { +// formatter.setBracketFormatMode(LINUX_MODE); +// } +// else if ( isOption(arg, "u", "brackets=stroustrup") ) +// { +// formatter.setBracketFormatMode(STROUSTRUP_MODE); +// } +// else if ( isOption(arg, "g", "brackets=run-in") ) +// { +// formatter.setBracketFormatMode(RUN_IN_MODE); +// } + // end depreciated options //////////////////////////////////////////////////////////////////////////////////////// +#ifdef ASTYLE_LIB + // End of options used by GUI ///////////////////////////////////////////////////////////////////////////////////// + else + isOptionError(arg, errorInfo); +#else + // Options used by only console /////////////////////////////////////////////////////////////////////////////////// + else if ( isOption(arg, "n", "suffix=none") ) + { + g_console->setNoBackup(true); + } + else if ( isParamOption(arg, "suffix=") ) + { + string suffixParam = getParam(arg, "suffix="); + if (suffixParam.length() > 0) + { + g_console->setOrigSuffix(suffixParam); + } + } + else if ( isParamOption(arg, "exclude=") ) + { + string suffixParam = getParam(arg, "exclude="); + if (suffixParam.length() > 0) + g_console->updateExcludeVector(suffixParam); + } + else if ( isOption(arg, "r", "R") || isOption(arg, "recursive") ) + { + g_console->setIsRecursive(true); + } + else if (isOption(arg, "dry-run")) + { + g_console->setIsDryRun(true); + } + else if ( isOption(arg, "Z", "preserve-date") ) + { + g_console->setPreserveDate(true); + } + else if ( isOption(arg, "v", "verbose") ) + { + g_console->setIsVerbose(true); + } + else if ( isOption(arg, "Q", "formatted") ) + { + g_console->setIsFormattedOnly(true); + } + else if ( isOption(arg, "q", "quiet") ) + { + g_console->setIsQuiet(true); + } + else if ( isOption(arg, "i", "ignore-exclude-errors") ) + { + g_console->setIgnoreExcludeErrors(true); + } + else if ( isOption(arg, "xi", "ignore-exclude-errors-x") ) + { + g_console->setIgnoreExcludeErrorsAndDisplay(true); + } + else if ( isOption(arg, "X", "errors-to-stdout") ) + { + _err = &cout; + } + else if ( isOption(arg, "lineend=windows") ) + { + formatter.setLineEndFormat(LINEEND_WINDOWS); + } + else if ( isOption(arg, "lineend=linux") ) + { + formatter.setLineEndFormat(LINEEND_LINUX); + } + else if ( isOption(arg, "lineend=macold") ) + { + formatter.setLineEndFormat(LINEEND_MACOLD); + } + else if ( isParamOption(arg, "z") ) + { + int lineendType = 0; + string lineendParam = getParam(arg, "z"); + if (lineendParam.length() > 0) + lineendType = atoi(lineendParam.c_str()); + if (lineendType < 1 || lineendType > 3) + isOptionError(arg, errorInfo); + else if (lineendType == 1) + formatter.setLineEndFormat(LINEEND_WINDOWS); + else if (lineendType == 2) + formatter.setLineEndFormat(LINEEND_LINUX); + else if (lineendType == 3) + formatter.setLineEndFormat(LINEEND_MACOLD); + } + else + isOptionError(arg, errorInfo); +#endif +} // End of parseOption function + +// Parse options from the options file. +void ASOptions::importOptions(istream& in, vector& optionsVector) +{ + char ch; + bool isInQuote = false; + char quoteChar = ' '; + string currentToken; + + while (in) + { + currentToken = ""; + do + { + in.get(ch); + if (in.eof()) + break; + // treat '#' as line comments + if (ch == '#') + while (in) + { + in.get(ch); + if (ch == '\n' || ch == '\r') + break; + } + + // break options on new-lines, tabs, commas, or spaces + // remove quotes from output + if (in.eof() || ch == '\n' || ch == '\r' || ch == '\t' || ch == ',') + break; + if (ch == ' ' && !isInQuote) + break; + if (ch == quoteChar && isInQuote) + break; + if (ch == '"' || ch == '\'') + { + isInQuote = true; + quoteChar = ch; + continue; + } + currentToken.append(1, ch); + } + while (in); + + if (currentToken.length() != 0) + optionsVector.push_back(currentToken); + isInQuote = false; + } +} + +string ASOptions::getOptionErrors() const +{ + return optionErrors.str(); +} + +string ASOptions::getParam(const string& arg, const char* op) +{ + return arg.substr(strlen(op)); +} + +string ASOptions::getParam(const string& arg, const char* op1, const char* op2) +{ + return isParamOption(arg, op1) ? getParam(arg, op1) : getParam(arg, op2); +} + +bool ASOptions::isOption(const string& arg, const char* op) +{ + return arg.compare(op) == 0; +} + +bool ASOptions::isOption(const string& arg, const char* op1, const char* op2) +{ + return (isOption(arg, op1) || isOption(arg, op2)); +} + +void ASOptions::isOptionError(const string& arg, const string& errorInfo) +{ + if (optionErrors.str().length() == 0) + optionErrors << errorInfo << endl; // need main error message + optionErrors << arg << endl; +} + +bool ASOptions::isParamOption(const string& arg, const char* option) +{ + bool retVal = arg.compare(0, strlen(option), option) == 0; + // if comparing for short option, 2nd char of arg must be numeric + if (retVal && strlen(option) == 1 && arg.length() > 1) + if (!isdigit((unsigned char)arg[1])) + retVal = false; + return retVal; +} + +bool ASOptions::isParamOption(const string& arg, const char* option1, const char* option2) +{ + return isParamOption(arg, option1) || isParamOption(arg, option2); +} + +//---------------------------------------------------------------------------- +// Utf8_16 class +//---------------------------------------------------------------------------- + +// Return true if an int is big endian. +bool Utf8_16::getBigEndian() const +{ + short int word = 0x0001; + char* byte = (char*) &word; + return (byte[0] ? false : true); +} + +// Swap the two low order bytes of a 16 bit integer value. +int Utf8_16::swap16bit(int value) const +{ + return ( ((value & 0xff) << 8) | ((value & 0xff00) >> 8) ); +} + +// Return the length of a utf-16 C string. +// The length is in number of utf16_t. +size_t Utf8_16::utf16len(const utf16* utf16In) const +{ + size_t length = 0; + while (*utf16In++ != '\0') + length++; + return length; +} + +// Adapted from SciTE UniConversion.cxx. +// Copyright 1998-2001 by Neil Hodgson +// Modified for Artistic Style by Jim Pattee. +// Compute the length of an output utf-8 file given a utf-16 file. +// Input inLen is the size in BYTES (not wchar_t). +size_t Utf8_16::Utf8LengthFromUtf16(const char* utf16In, size_t inLen, bool isBigEndian) const +{ + size_t len = 0; + size_t wcharLen = inLen / 2; + const short* uptr = reinterpret_cast(utf16In); + for (size_t i = 0; i < wcharLen && uptr[i];) + { + size_t uch = isBigEndian ? swap16bit(uptr[i]) : uptr[i]; + if (uch < 0x80) + len++; + else if (uch < 0x800) + len += 2; + else if ((uch >= SURROGATE_LEAD_FIRST) && (uch <= SURROGATE_TRAIL_LAST)) + { + len += 4; + i++; + } + else + len += 3; + i++; + } + return len; +} + +// Adapted from SciTE Utf8_16.cxx. +// Copyright (C) 2002 Scott Kirkwood. +// Modified for Artistic Style by Jim Pattee. +// Convert a utf-8 file to utf-16. +size_t Utf8_16::Utf8ToUtf16(char* utf8In, size_t inLen, bool isBigEndian, char* utf16Out) const +{ + int nCur = 0; + ubyte* pRead = reinterpret_cast(utf8In); + utf16* pCur = reinterpret_cast(utf16Out); + const ubyte* pEnd = pRead + inLen; + const utf16* pCurStart = pCur; + eState state = eStart; + + // the BOM will automatically be converted to utf-16 + while (pRead < pEnd) + { + switch (state) + { + case eStart: + if ((0xF0 & *pRead) == 0xF0) + { + nCur = (0x7 & *pRead) << 18; + state = eSecondOf4Bytes; + } + else if ((0xE0 & *pRead) == 0xE0) + { + nCur = (~0xE0 & *pRead) << 12; + state = ePenultimate; + } + else if ((0xC0 & *pRead) == 0xC0) + { + nCur = (~0xC0 & *pRead) << 6; + state = eFinal; + } + else + { + nCur = *pRead; + state = eStart; + } + break; + case eSecondOf4Bytes: + nCur |= (0x3F & *pRead) << 12; + state = ePenultimate; + break; + case ePenultimate: + nCur |= (0x3F & *pRead) << 6; + state = eFinal; + break; + case eFinal: + nCur |= (0x3F & *pRead); + state = eStart; + break; + // no default case is needed + } + ++pRead; + + if (state == eStart) + { + int codePoint = nCur; + if (codePoint >= SURROGATE_FIRST_VALUE) + { + codePoint -= SURROGATE_FIRST_VALUE; + int lead = (codePoint >> 10) + SURROGATE_LEAD_FIRST; + *pCur++ = static_cast(isBigEndian ? swap16bit(lead) : lead); + int trail = (codePoint & 0x3ff) + SURROGATE_TRAIL_FIRST; + *pCur++ = static_cast(isBigEndian ? swap16bit(trail) : trail); + } + else + *pCur++ = static_cast(isBigEndian ? swap16bit(codePoint) : codePoint); + } + } + // return value is the output length in BYTES (not wchar_t) + return (pCur - pCurStart) * 2; +} + +// Adapted from SciTE UniConversion.cxx. +// Copyright 1998-2001 by Neil Hodgson +// Modified for Artistic Style by Jim Pattee. +// Compute the length of an output utf-16 file given a utf-8 file. +// Return value is the size in BYTES (not wchar_t). +size_t Utf8_16::Utf16LengthFromUtf8(const char* utf8In, size_t len) const +{ + size_t ulen = 0; + size_t charLen; + for (size_t i = 0; i < len;) + { + unsigned char ch = static_cast(utf8In[i]); + if (ch < 0x80) + charLen = 1; + else if (ch < 0x80 + 0x40 + 0x20) + charLen = 2; + else if (ch < 0x80 + 0x40 + 0x20 + 0x10) + charLen = 3; + else + { + charLen = 4; + ulen++; + } + i += charLen; + ulen++; + } + // return value is the length in bytes (not wchar_t) + return ulen * 2; +} + +// Adapted from SciTE Utf8_16.cxx. +// Copyright (C) 2002 Scott Kirkwood. +// Modified for Artistic Style by Jim Pattee. +// Convert a utf-16 file to utf-8. +size_t Utf8_16::Utf16ToUtf8(char* utf16In, size_t inLen, bool isBigEndian, + bool firstBlock, char* utf8Out) const +{ + int nCur16 = 0; + int nCur = 0; + ubyte* pRead = reinterpret_cast(utf16In); + ubyte* pCur = reinterpret_cast(utf8Out); + const ubyte* pEnd = pRead + inLen; + const ubyte* pCurStart = pCur; + static eState state = eStart; // state is retained for subsequent blocks + if (firstBlock) + state = eStart; + + // the BOM will automatically be converted to utf-8 + while (pRead < pEnd) + { + switch (state) + { + case eStart: + if (pRead >= pEnd) + { + ++pRead; + break; + } + if (isBigEndian) + { + nCur16 = static_cast(*pRead++ << 8); + nCur16 |= static_cast(*pRead); + } + else + { + nCur16 = *pRead++; + nCur16 |= static_cast(*pRead << 8); + } + if (nCur16 >= SURROGATE_LEAD_FIRST && nCur16 <= SURROGATE_LEAD_LAST) + { + ++pRead; + int trail; + if (isBigEndian) + { + trail = static_cast(*pRead++ << 8); + trail |= static_cast(*pRead); + } + else + { + trail = *pRead++; + trail |= static_cast(*pRead << 8); + } + nCur16 = (((nCur16 & 0x3ff) << 10) | (trail & 0x3ff)) + SURROGATE_FIRST_VALUE; + } + ++pRead; + + if (nCur16 < 0x80) + { + nCur = static_cast(nCur16 & 0xFF); + state = eStart; + } + else if (nCur16 < 0x800) + { + nCur = static_cast(0xC0 | (nCur16 >> 6)); + state = eFinal; + } + else if (nCur16 < SURROGATE_FIRST_VALUE) + { + nCur = static_cast(0xE0 | (nCur16 >> 12)); + state = ePenultimate; + } + else + { + nCur = static_cast(0xF0 | (nCur16 >> 18)); + state = eSecondOf4Bytes; + } + break; + case eSecondOf4Bytes: + nCur = static_cast(0x80 | ((nCur16 >> 12) & 0x3F)); + state = ePenultimate; + break; + case ePenultimate: + nCur = static_cast(0x80 | ((nCur16 >> 6) & 0x3F)); + state = eFinal; + break; + case eFinal: + nCur = static_cast(0x80 | (nCur16 & 0x3F)); + state = eStart; + break; + // no default case is needed + } + *pCur++ = static_cast(nCur); + } + return pCur - pCurStart; +} + +//---------------------------------------------------------------------------- + +} // end of astyle namespace + +//---------------------------------------------------------------------------- + +using namespace astyle; + +//---------------------------------------------------------------------------- +// ASTYLE_JNI functions for Java library builds +//---------------------------------------------------------------------------- + +#ifdef ASTYLE_JNI + +// called by a java program to get the version number +// the function name is constructed from method names in the calling java program +extern "C" EXPORT +jstring STDCALL Java_AStyleInterface_AStyleGetVersion(JNIEnv* env, jclass) +{ + return env->NewStringUTF(g_version); +} + +// called by a java program to format the source code +// the function name is constructed from method names in the calling java program +extern "C" EXPORT +jstring STDCALL Java_AStyleInterface_AStyleMain(JNIEnv* env, + jobject obj, + jstring textInJava, + jstring optionsJava) +{ + g_env = env; // make object available globally + g_obj = obj; // make object available globally + + jstring textErr = env->NewStringUTF(""); // zero length text returned if an error occurs + + // get the method ID + jclass cls = env->GetObjectClass(obj); + g_mid = env->GetMethodID(cls, "ErrorHandler", "(ILjava/lang/String;)V"); + if (g_mid == 0) + { + cout << "Cannot find java method ErrorHandler" << endl; + return textErr; + } + + // convert jstring to char* + const char* textIn = env->GetStringUTFChars(textInJava, NULL); + const char* options = env->GetStringUTFChars(optionsJava, NULL); + + // call the C++ formatting function + char* textOut = AStyleMain(textIn, options, javaErrorHandler, javaMemoryAlloc); + // if an error message occurred it was displayed by errorHandler + if (textOut == NULL) + return textErr; + + // release memory + jstring textOutJava = env->NewStringUTF(textOut); + delete [] textOut; + env->ReleaseStringUTFChars(textInJava, textIn); + env->ReleaseStringUTFChars(optionsJava, options); + + return textOutJava; +} + +// Call the Java error handler +void STDCALL javaErrorHandler(int errorNumber, const char* errorMessage) +{ + jstring errorMessageJava = g_env->NewStringUTF(errorMessage); + g_env->CallVoidMethod(g_obj, g_mid, errorNumber, errorMessageJava); +} + +// Allocate memory for the formatted text +char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded) +{ + // error condition is checked after return from AStyleMain + char* buffer = new(nothrow) char[memoryNeeded]; + return buffer; +} +#endif // ASTYLE_JNI + +//---------------------------------------------------------------------------- +// Entry point for AStyleMainUtf16 library builds +//---------------------------------------------------------------------------- + +#ifdef ASTYLE_LIB + +extern "C" EXPORT utf16_t* STDCALL AStyleMainUtf16(const utf16_t* pSourceIn, // the source to be formatted + const utf16_t* pOptions, // AStyle options + fpError fpErrorHandler, // error handler function + fpAlloc fpMemoryAlloc) // memory allocation function +{ + if (fpErrorHandler == NULL) // cannot display a message if no error handler + return NULL; + + if (pSourceIn == NULL) + { + fpErrorHandler(101, "No pointer to source input."); + return NULL; + } + if (pOptions == NULL) + { + fpErrorHandler(102, "No pointer to AStyle options."); + return NULL; + } + if (fpMemoryAlloc == NULL) + { + fpErrorHandler(103, "No pointer to memory allocation function."); + return NULL; + } +#ifndef _WIN32 + // check size of utf16_t on Linux + int sizeCheck = 2; + if (sizeof(utf16_t) != sizeCheck) + { + fpErrorHandler(104, "Unsigned short is not the correct size."); + return NULL; + } +#endif + + ASLibrary library; + utf16_t* utf16Out = library.formatUtf16(pSourceIn, pOptions, fpErrorHandler, fpMemoryAlloc); + return utf16Out; +} + +//---------------------------------------------------------------------------- +// ASTYLE_LIB entry point for library builds +//---------------------------------------------------------------------------- +/* + * IMPORTANT VC DLL linker for WIN32 must have the parameter /EXPORT:AStyleMain=_AStyleMain@16 + * /EXPORT:AStyleGetVersion=_AStyleGetVersion@0 + * No /EXPORT is required for x64 + */ +extern "C" EXPORT char* STDCALL AStyleMain(const char* pSourceIn, // the source to be formatted + const char* pOptions, // AStyle options + fpError fpErrorHandler, // error handler function + fpAlloc fpMemoryAlloc) // memory allocation function +{ + if (fpErrorHandler == NULL) // cannot display a message if no error handler + return NULL; + + if (pSourceIn == NULL) + { + fpErrorHandler(101, "No pointer to source input."); + return NULL; + } + if (pOptions == NULL) + { + fpErrorHandler(102, "No pointer to AStyle options."); + return NULL; + } + if (fpMemoryAlloc == NULL) + { + fpErrorHandler(103, "No pointer to memory allocation function."); + return NULL; + } + + ASFormatter formatter; + ASOptions options(formatter); + + vector optionsVector; + istringstream opt(pOptions); + + options.importOptions(opt, optionsVector); + + bool ok = options.parseOptions(optionsVector, "Invalid Artistic Style options:"); + if (!ok) + fpErrorHandler(130, options.getOptionErrors().c_str()); + + istringstream in(pSourceIn); + ASStreamIterator streamIterator(&in); + ostringstream out; + formatter.init(&streamIterator); + + while (formatter.hasMoreLines()) + { + out << formatter.nextLine(); + if (formatter.hasMoreLines()) + out << streamIterator.getOutputEOL(); + else + { + // this can happen if the file if missing a closing bracket and break-blocks is requested + if (formatter.getIsLineReady()) + { + out << streamIterator.getOutputEOL(); + out << formatter.nextLine(); + } + } + } + + unsigned long textSizeOut = out.str().length(); + char* pTextOut = fpMemoryAlloc(textSizeOut + 1); // call memory allocation function + if (pTextOut == NULL) + { + fpErrorHandler(120, "Allocation failure on output."); + return NULL; + } + + strcpy(pTextOut, out.str().c_str()); +#ifndef NDEBUG + // The checksum is an assert in the console build and ASFormatter. + // This error returns the incorrectly formatted file to the editor. + // This is done to allow the file to be saved for debugging purposes. + if (formatter.getChecksumDiff() != 0) + fpErrorHandler(220, + "Checksum error.\n" + "The incorrectly formatted file will be returned for debugging."); +#endif + return pTextOut; +} + +extern "C" EXPORT const char* STDCALL AStyleGetVersion(void) +{ + return g_version; +} + +// ASTYLECON_LIB is defined to exclude "main" from the test programs +#elif !defined(ASTYLECON_LIB) + +//---------------------------------------------------------------------------- +// main function for ASConsole build +//---------------------------------------------------------------------------- + +int main(int argc, char** argv) +{ + // create objects + ASFormatter formatter; + g_console = new ASConsole(formatter); + + // process command line and options file + // build the vectors fileNameVector, optionsVector, and fileOptionsVector + vector argvOptions; + argvOptions = g_console->getArgvOptions(argc, argv); + g_console->processOptions(argvOptions); + + // if no files have been given, use cin for input and cout for output + if (g_console->fileNameVectorIsEmpty()) + { + g_console->formatCinToCout(); + return EXIT_SUCCESS; + } + + // process entries in the fileNameVector + g_console->processFiles(); + + delete g_console; + return EXIT_SUCCESS; +} + +#endif // ASTYLE_LIB diff --git a/External/Tools/AStyle/src/astyle_main.h b/External/Tools/AStyle/src/astyle_main.h new file mode 100644 index 0000000000..2da42c0280 --- /dev/null +++ b/External/Tools/AStyle/src/astyle_main.h @@ -0,0 +1,440 @@ +// astyle_main.h +// Copyright (c) 2016 by Jim Pattee . +// Licensed under the MIT license. +// License.txt describes the conditions under which this software may be distributed. + +#ifndef ASTYLE_MAIN_H +#define ASTYLE_MAIN_H + +//---------------------------------------------------------------------------- +// headers +//---------------------------------------------------------------------------- + +#include "astyle.h" + +#include +#include + +#if defined(__BORLANDC__) && __BORLANDC__ < 0x0650 + // Embarcadero needs this for the following utime.h + // otherwise "struct utimbuf" gets an error on time_t + // 0x0650 for C++Builder XE3 + using std::time_t; +#endif + +#if defined(_MSC_VER) || defined(__DMC__) + #include + #include +#else + #include + #include +#endif // end compiler checks + +#ifdef ASTYLE_JNI + #include + #ifndef ASTYLE_LIB // ASTYLE_LIB must be defined for ASTYLE_JNI + #define ASTYLE_LIB + #endif +#endif // ASTYLE_JNI + +#ifndef ASTYLE_LIB + // for console build only + #include "ASLocalizer.h" + #define _(a) localizer.settext(a) +#endif // ASTYLE_LIB + +//----------------------------------------------------------------------------- +// declarations +//----------------------------------------------------------------------------- + +// for G++ implementation of string.compare: +#if defined(__GNUC__) && __GNUC__ < 3 + #error - Use GNU C compiler release 3 or higher +#endif + +// for namespace problem in version 5.0 +#if defined(_MSC_VER) && _MSC_VER < 1200 // check for V6.0 + #error - Use Microsoft compiler version 6 or higher +#endif + +// for mingw BOM, UTF-16, and Unicode functions +#if defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR) + #if (__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION < 16)) + #error - Use MinGW compiler version 4 or higher + #endif +#endif + +#ifdef ASTYLE_LIB + + // define STDCALL and EXPORT for Windows + // MINGW defines STDCALL in Windows.h (actually windef.h) + // EXPORT has no value if ASTYLE_NO_EXPORT is defined + #ifdef _WIN32 + #ifndef STDCALL + #define STDCALL __stdcall + #endif + // define this to prevent compiler warning and error messages + #ifdef ASTYLE_NO_EXPORT + #define EXPORT + #else + #define EXPORT __declspec(dllexport) + #endif + // define STDCALL and EXPORT for non-Windows + // visibility attribute allows "-fvisibility=hidden" compiler option + #else + #define STDCALL + #if __GNUC__ >= 4 + #define EXPORT __attribute__ ((visibility ("default"))) + #else + #define EXPORT + #endif + #endif // #ifdef _WIN32 + + // define utf-16 bit text for the platform + typedef unsigned short utf16_t; + // define pointers to callback error handler and memory allocation + typedef void (STDCALL* fpError)(int errorNumber, const char* errorMessage); + typedef char* (STDCALL* fpAlloc)(unsigned long memoryNeeded); + +#endif // #ifdef ASTYLE_LIB + +//---------------------------------------------------------------------------- +// astyle namespace +//---------------------------------------------------------------------------- + +namespace astyle { +// +//---------------------------------------------------------------------------- +// ASStreamIterator class +// typename will be istringstream for GUI and istream otherwise +// ASSourceIterator is an abstract class defined in astyle.h +//---------------------------------------------------------------------------- + +template +class ASStreamIterator : public ASSourceIterator +{ +public: + bool checkForEmptyLine; + + // function declarations + explicit ASStreamIterator(T* in); + virtual ~ASStreamIterator(); + bool getLineEndChange(int lineEndFormat) const; + int getStreamLength() const; + string nextLine(bool emptyLineWasDeleted); + string peekNextLine(); + void peekReset(); + void saveLastInputLine(); + streamoff tellg(); + +private: + ASStreamIterator(const ASStreamIterator& copy); // copy constructor not to be implemented + ASStreamIterator& operator=(ASStreamIterator&); // assignment operator not to be implemented + T* inStream; // pointer to the input stream + string buffer; // current input line + string prevBuffer; // previous input line + int eolWindows; // number of Windows line endings, CRLF + int eolLinux; // number of Linux line endings, LF + int eolMacOld; // number of old Mac line endings. CR + char outputEOL[4]; // next output end of line char + streamoff streamLength; // length of the input file stream + streamoff peekStart; // starting position for peekNextLine + bool prevLineDeleted; // the previous input line was deleted + +public: // inline functions + bool compareToInputBuffer(const string& nextLine_) const + { return (nextLine_ == prevBuffer); } + const char* getOutputEOL() const { return outputEOL; } + bool hasMoreLines() const { return !inStream->eof(); } +}; + +//---------------------------------------------------------------------------- +// Utf8_16 class for utf8/16 conversions +//---------------------------------------------------------------------------- + +class Utf8_16 +{ +private: + typedef unsigned short utf16; // 16 bits + typedef unsigned char utf8; // 8 bits + typedef unsigned char ubyte; // 8 bits + enum { SURROGATE_LEAD_FIRST = 0xD800 }; + enum { SURROGATE_LEAD_LAST = 0xDBFF }; + enum { SURROGATE_TRAIL_FIRST = 0xDC00 }; + enum { SURROGATE_TRAIL_LAST = 0xDFFF }; + enum { SURROGATE_FIRST_VALUE = 0x10000 }; + enum eState { eStart, eSecondOf4Bytes, ePenultimate, eFinal }; + +public: + bool getBigEndian() const; + int swap16bit(int value) const; + size_t utf16len(const utf16* utf16In) const; + size_t Utf8LengthFromUtf16(const char* utf16In, size_t inLen, bool isBigEndian) const; + size_t Utf8ToUtf16(char* utf8In, size_t inLen, bool isBigEndian, char* utf16Out) const; + size_t Utf16LengthFromUtf8(const char* utf8In, size_t inLen) const; + size_t Utf16ToUtf8(char* utf16In, size_t inLen, bool isBigEndian, + bool firstBlock, char* utf8Out) const; +}; + +//---------------------------------------------------------------------------- +// ASOptions class for options processing +// used by both console and library builds +//---------------------------------------------------------------------------- + +class ASOptions +{ +public: + ASOptions(ASFormatter& formatterArg) : formatter(formatterArg) {} + string getOptionErrors() const; + void importOptions(istream& in, vector& optionsVector); + bool parseOptions(vector& optionsVector, const string& errorInfo); + +private: + // variables + ASFormatter& formatter; // reference to the ASFormatter object + stringstream optionErrors; // option error messages + + // functions + ASOptions(const ASOptions&); // copy constructor not to be implemented + ASOptions& operator=(ASOptions&); // assignment operator not to be implemented + string getParam(const string& arg, const char* op); + string getParam(const string& arg, const char* op1, const char* op2); + bool isOption(const string& arg, const char* op); + bool isOption(const string& arg, const char* op1, const char* op2); + void isOptionError(const string& arg, const string& errorInfo); + bool isParamOption(const string& arg, const char* option); + bool isParamOption(const string& arg, const char* option1, const char* option2); + void parseOption(const string& arg, const string& errorInfo); +}; + +#ifndef ASTYLE_LIB + +//---------------------------------------------------------------------------- +// ASConsole class for console build +//---------------------------------------------------------------------------- + +class ASConsole +{ +private: // variables + ASFormatter& formatter; // reference to the ASFormatter object + ASLocalizer localizer; // ASLocalizer object + // command line options + bool isRecursive; // recursive option + bool isDryRun; // dry-run option + bool noBackup; // suffix=none option + bool preserveDate; // preserve-date option + bool isVerbose; // verbose option + bool isQuiet; // quiet option + bool isFormattedOnly; // formatted lines only option + bool ignoreExcludeErrors; // don't abort on unmatched excludes + bool ignoreExcludeErrorsDisplay; // don't display unmatched excludes + bool optionsFileRequired; // options= option + bool useAscii; // ascii option + // other variables + bool bypassBrowserOpen; // don't open the browser on html options + bool hasWildcard; // file name includes a wildcard + size_t mainDirectoryLength; // directory length to be excluded in displays + bool filesAreIdentical; // input and output files are identical + int filesFormatted; // number of files formatted + int filesUnchanged; // number of files unchanged + bool lineEndsMixed; // output has mixed line ends + int linesOut; // number of output lines + char outputEOL[4]; // current line end + char prevEOL[4]; // previous line end + + Utf8_16 utf8_16; // utf8/16 conversion methods + + string optionsFileName; // file path and name of the options file to use + string origSuffix; // suffix= option + string targetDirectory; // path to the directory being processed + string targetFilename; // file name being processed + + vector excludeVector; // exclude from wildcard hits + vector excludeHitsVector; // exclude flags for error reporting + vector fileNameVector; // file paths and names from the command line + vector optionsVector; // options from the command line + vector fileOptionsVector; // options from the options file + vector fileName; // files to be processed including path + +public: // variables + ASConsole(ASFormatter& formatterArg) : formatter(formatterArg) + { + // command line options + isRecursive = false; + isDryRun = false; + noBackup = false; + preserveDate = false; + isVerbose = false; + isQuiet = false; + isFormattedOnly = false; + ignoreExcludeErrors = false; + ignoreExcludeErrorsDisplay = false; + optionsFileRequired = false; + useAscii = false; + // other variables + bypassBrowserOpen = false; + hasWildcard = false; + filesAreIdentical = true; + lineEndsMixed = false; + outputEOL[0] = '\0'; + prevEOL[0] = '\0'; + origSuffix = ".orig"; + mainDirectoryLength = 0; + filesFormatted = 0; + filesUnchanged = 0; + linesOut = 0; + } + +public: // functions + void convertLineEnds(ostringstream& out, int lineEnd); + FileEncoding detectEncoding(const char* data, size_t dataSize) const; + void error() const; + void error(const char* why, const char* what) const; + void formatCinToCout(); + vector getArgvOptions(int argc, char** argv) const; + bool fileNameVectorIsEmpty() const; + bool getFilesAreIdentical() const; + int getFilesFormatted() const; + bool getIgnoreExcludeErrors() const; + bool getIgnoreExcludeErrorsDisplay() const; + bool getIsDryRun() const; + bool getIsFormattedOnly() const; + bool getIsQuiet() const; + bool getIsRecursive() const; + bool getIsVerbose() const; + bool getLineEndsMixed() const; + bool getNoBackup() const; + bool getPreserveDate() const; + string getLanguageID() const; + string getNumberFormat(int num, size_t = 0) const; + string getNumberFormat(int num, const char* groupingArg, const char* separator) const; + string getOptionsFileName() const; + string getOrigSuffix() const; + void processFiles(); + void processOptions(vector& argvOptions); + void setBypassBrowserOpen(bool state); + void setIgnoreExcludeErrors(bool state); + void setIgnoreExcludeErrorsAndDisplay(bool state); + void setIsDryRun(bool state); + void setIsFormattedOnly(bool state); + void setIsQuiet(bool state); + void setIsRecursive(bool state); + void setIsVerbose(bool state); + void setNoBackup(bool state); + void setOptionsFileName(string name); + void setOrigSuffix(string suffix); + void setPreserveDate(bool state); + void standardizePath(string& path, bool removeBeginningSeparator = false) const; + bool stringEndsWith(const string& str, const string& suffix) const; + void updateExcludeVector(string suffixParam); + vector getExcludeVector() const; + vector getExcludeHitsVector() const; + vector getFileNameVector() const; + vector getOptionsVector() const; + vector getFileOptionsVector() const; + vector getFileName() const; + +private: // functions + ASConsole& operator=(ASConsole&); // not to be implemented + void correctMixedLineEnds(ostringstream& out); + void formatFile(const string& fileName_); + string getCurrentDirectory(const string& fileName_) const; + void getFileNames(const string& directory, const string& wildcard); + void getFilePaths(string& filePath); + string getParam(const string& arg, const char* op); + void initializeOutputEOL(LineEndFormat lineEndFormat); + bool isOption(const string& arg, const char* op); + bool isOption(const string& arg, const char* op1, const char* op2); + bool isParamOption(const string& arg, const char* option); + bool isPathExclued(const string& subPath); + void launchDefaultBrowser(const char* filePathIn = NULL) const; + void printHelp() const; + void printMsg(const char* msg, const string& data) const; + void printSeparatingLine() const; + void printVerboseHeader() const; + void printVerboseStats(clock_t startTime) const; + FileEncoding readFile(const string& fileName_, stringstream& in) const; + void removeFile(const char* fileName_, const char* errMsg) const; + void renameFile(const char* oldFileName, const char* newFileName, const char* errMsg) const; + void setOutputEOL(LineEndFormat lineEndFormat, const char* currentEOL); + void sleep(int seconds) const; + int waitForRemove(const char* oldFileName) const; + int wildcmp(const char* wild, const char* data) const; + void writeFile(const string& fileName_, FileEncoding encoding, ostringstream& out) const; +#ifdef _WIN32 + void displayLastError(); +#endif +}; +#else // ASTYLE_LIB + +//---------------------------------------------------------------------------- +// ASLibrary class for library build +//---------------------------------------------------------------------------- + +class ASLibrary +{ +public: + ASLibrary() {} + virtual ~ASLibrary() {} + // virtual functions are mocked in testing + utf16_t* formatUtf16(const utf16_t*, const utf16_t*, fpError, fpAlloc) const; + virtual utf16_t* convertUtf8ToUtf16(const char* utf8In, fpAlloc fpMemoryAlloc) const; + virtual char* convertUtf16ToUtf8(const utf16_t* pSourceIn) const; + +private: + static char* STDCALL tempMemoryAllocation(unsigned long memoryNeeded); + +private: + Utf8_16 utf8_16; // utf8/16 conversion methods +}; + +#endif // ASTYLE_LIB + +//---------------------------------------------------------------------------- + +} // end of namespace astyle + +//---------------------------------------------------------------------------- +// declarations for java native interface (JNI) build +// they are called externally and are NOT part of the namespace +//---------------------------------------------------------------------------- +#ifdef ASTYLE_JNI +void STDCALL javaErrorHandler(int errorNumber, const char* errorMessage); +char* STDCALL javaMemoryAlloc(unsigned long memoryNeeded); +// the following function names are constructed from method names in the calling java program +extern "C" EXPORT +jstring STDCALL Java_AStyleInterface_AStyleGetVersion(JNIEnv* env, jclass); +extern "C" EXPORT +jstring STDCALL Java_AStyleInterface_AStyleMain(JNIEnv* env, + jobject obj, + jstring textInJava, + jstring optionsJava); +#endif // ASTYLE_JNI + +//---------------------------------------------------------------------------- +// declarations for UTF-16 interface +// they are called externally and are NOT part of the namespace +//---------------------------------------------------------------------------- +#ifdef ASTYLE_LIB +extern "C" EXPORT +utf16_t* STDCALL AStyleMainUtf16(const utf16_t* pSourceIn, + const utf16_t* pOptions, + fpError fpErrorHandler, + fpAlloc fpMemoryAlloc); +#endif // ASTYLE_LIB + +//----------------------------------------------------------------------------- +// declarations for standard DLL interface +// they are called externally and are NOT part of the namespace +//----------------------------------------------------------------------------- +#ifdef ASTYLE_LIB +extern "C" EXPORT char* STDCALL AStyleMain(const char* sourceIn, + const char* optionsIn, + fpError errorHandler, + fpAlloc memoryAlloc); +extern "C" EXPORT const char* STDCALL AStyleGetVersion(void); +#endif // ASTYLE_LIB + +//----------------------------------------------------------------------------- + +#endif // closes ASTYLE_MAIN_H diff --git a/External/Tools/AppMan/AppMan.csproj b/External/Tools/AppMan/AppMan.csproj index a38691be76..55cfe1e2c2 100644 --- a/External/Tools/AppMan/AppMan.csproj +++ b/External/Tools/AppMan/AppMan.csproj @@ -1,34 +1,26 @@  - + Debug x86 - 8.0.30703 - 2.0 {82D3DF9E-370C-47C3-B9F6-21756AAF0B0B} WinExe Properties AppMan AppMan - v2.0 - - - 512 + net48 + true + false + false + false + publish\ true Disk - false - Foreground - 7 - Days - false - false true - 0 - 1.0.0.%2a - false false - true + false + false x86 @@ -45,17 +37,18 @@ none true ..\..\..\FlashDevelop\Bin\Debug\Tools\appman\ - FLASHDEVELOP WIN32 + FLASHDEVELOP prompt 4 Resources\AppMan.ico + + Properties\Program.manifest + - - @@ -71,6 +64,8 @@ + + @@ -136,35 +131,10 @@ - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - + - - + \ No newline at end of file diff --git a/External/Tools/AppMan/AppManSA.csproj b/External/Tools/AppMan/AppManSA.csproj index 2d65178b49..0c1cfe1dbe 100644 --- a/External/Tools/AppMan/AppManSA.csproj +++ b/External/Tools/AppMan/AppManSA.csproj @@ -1,34 +1,27 @@  - + Debug x86 - 8.0.30703 - 2.0 {82D3DF9E-370C-47C3-B9F6-21756AAF0B0B} WinExe Properties AppMan AppMan - v2.0 - - + net48 + true + false + false + false + Client 512 false publish\ true Disk - false - Foreground - 7 - Days - false - false true - 0 - 1.0.0.%2a false - true + false x86 @@ -44,14 +37,17 @@ x86 none true - Bin\Debug\ - FLASHDEVELOP WIN32 + Bin\Release\ + FLASHDEVELOP prompt 4 Resources\AppMan.ico + + Properties\Program.manifest + @@ -71,6 +67,8 @@ + + @@ -136,35 +134,14 @@ - - - False - .NET Framework 3.5 SP1 Client Profile - false - - - False - .NET Framework 3.5 SP1 - true - - - False - Windows Installer 3.1 - true - - - - + + + + \ No newline at end of file diff --git a/External/Tools/AppMan/BUILD.NET2.cmd b/External/Tools/AppMan/BUILD.NET2.cmd new file mode 100644 index 0000000000..b3d2972e6c --- /dev/null +++ b/External/Tools/AppMan/BUILD.NET2.cmd @@ -0,0 +1,11 @@ +:: Builds .NET 2.0 binary + +:: Set paths +set PATH=%PATH%;C:\Windows\Microsoft.NET\Framework\v4.0.30319\ + +:: Build the solution +msbuild AppMan.sln /p:Configuration=Release /p:Platform=x86 /t:Rebuild /toolsversion:2.0 + +:: Done +pause +exit \ No newline at end of file diff --git a/External/Tools/AppMan/Bin/Release/Config.xml b/External/Tools/AppMan/Bin/Release/Config.xml index a09e8c3633..8e3c590b20 100644 --- a/External/Tools/AppMan/Bin/Release/Config.xml +++ b/External/Tools/AppMan/Bin/Release/Config.xml @@ -1,13 +1,19 @@  + + FlashDevelop + + FD5 - $(AppDir)\Apps + $(BaseDir)\Apps http://www.flashdevelop.org/appman.xml http://www.flashdevelop.org/wikidocs/ - $(AppDir) + $(BaseDir) + + $(BaseDir)\Data\AppMan en_US \ No newline at end of file diff --git a/External/Tools/AppMan/Bin/Release/Licence.txt b/External/Tools/AppMan/Bin/Release/Licence.txt index 0a2e2dc1fd..857d5febf4 100644 --- a/External/Tools/AppMan/Bin/Release/Licence.txt +++ b/External/Tools/AppMan/Bin/Release/Licence.txt @@ -1,7 +1,7 @@ The awesome app icon is by Martz90: http://martz90.deviantart.com/art/Hex-Icons-Pack-389706981 -Copyright (c) 2005-2014 Mika Palmu - FlashDevelop.org +Copyright (c) 2005-2015 Mika Palmu - FlashDevelop.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, diff --git a/External/Tools/AppMan/Bin/Release/Locales/en_US.xml b/External/Tools/AppMan/Bin/Release/Locales/en_US.xml index 6a4679c730..ea8e3ace70 100644 --- a/External/Tools/AppMan/Bin/Release/Locales/en_US.xml +++ b/External/Tools/AppMan/Bin/Release/Locales/en_US.xml @@ -25,6 +25,8 @@ Trying to continue with the next item. Error while downloading file: Error while extracting file: + Error while deleting directory: + The checksum did not match the file: Select: Explore... @@ -34,8 +36,9 @@ Toggle Checked Show Info... - Executable - Archive + Executable + Archive + Link AppMan Confirm diff --git a/External/Tools/AppMan/MainForm.Designer.cs b/External/Tools/AppMan/MainForm.Designer.cs index f07ae16b86..f24c0eeeeb 100644 --- a/External/Tools/AppMan/MainForm.Designer.cs +++ b/External/Tools/AppMan/MainForm.Designer.cs @@ -19,6 +19,7 @@ partial class MainForm private System.Windows.Forms.ToolStripStatusLabel statusLabel; private System.Windows.Forms.ColumnHeader versionHeader; private System.Windows.Forms.ColumnHeader statusHeader; + private System.Windows.Forms.ColumnHeader infoHeader; private System.Windows.Forms.ColumnHeader nameHeader; private System.Windows.Forms.ColumnHeader descHeader; private System.Windows.Forms.ColumnHeader typeHeader; @@ -37,6 +38,7 @@ partial class MainForm private void InitializeComponent() { this.listView = new System.Windows.Forms.ListView(); + this.infoHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.nameHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.versionHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.descHeader = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); @@ -69,6 +71,7 @@ private void InitializeComponent() this.listView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.nameHeader, this.versionHeader, + this.infoHeader, this.descHeader, this.statusHeader, this.typeHeader}); @@ -80,27 +83,38 @@ private void InitializeComponent() this.listView.Location = new System.Drawing.Point(13, 48); this.listView.Name = "listView"; this.listView.ShowItemToolTips = true; - this.listView.Size = new System.Drawing.Size(730, 420); + this.listView.Size = new System.Drawing.Size(760, 420); this.listView.TabIndex = 4; this.listView.UseCompatibleStateImageBehavior = false; this.listView.View = System.Windows.Forms.View.Details; this.listView.ItemCheck += new System.Windows.Forms.ItemCheckEventHandler(this.ListViewItemCheck); this.listView.ItemChecked += new System.Windows.Forms.ItemCheckedEventHandler(this.ListViewItemChecked); + this.listView.DrawSubItem += new System.Windows.Forms.DrawListViewSubItemEventHandler(this.ListViewDrawSubItem); + this.listView.DrawColumnHeader += new System.Windows.Forms.DrawListViewColumnHeaderEventHandler(this.ListViewDrawColumnHeader); + this.listView.DrawItem += new System.Windows.Forms.DrawListViewItemEventHandler(this.ListViewDrawItem); + this.listView.MouseMove += new System.Windows.Forms.MouseEventHandler(this.ListViewMouseMove); + this.listView.Click += new System.EventHandler(this.ListViewClick); + this.listView.OwnerDraw = true; // // nameHeader // this.nameHeader.Text = "Name"; this.nameHeader.Width = 160; // + // infoHeader + // + this.infoHeader.Text = " !"; + this.infoHeader.Width = 24; + // // versionHeader // this.versionHeader.Text = "Version"; - this.versionHeader.Width = 100; + this.versionHeader.Width = 90; // // descHeader // this.descHeader.Text = "Description"; - this.descHeader.Width = 303; + this.descHeader.Width = 319; // // statusHeader // @@ -135,7 +149,7 @@ private void InitializeComponent() // this.deleteButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.deleteButton.Enabled = false; - this.deleteButton.Location = new System.Drawing.Point(598, 511); + this.deleteButton.Location = new System.Drawing.Point(628, 511); this.deleteButton.Name = "deleteButton"; this.deleteButton.Size = new System.Drawing.Size(146, 27); this.deleteButton.TabIndex = 11; @@ -147,7 +161,7 @@ private void InitializeComponent() // this.installButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.installButton.Enabled = false; - this.installButton.Location = new System.Drawing.Point(598, 477); + this.installButton.Location = new System.Drawing.Point(628, 477); this.installButton.Name = "installButton"; this.installButton.Size = new System.Drawing.Size(146, 27); this.installButton.TabIndex = 10; @@ -172,7 +186,7 @@ private void InitializeComponent() this.pathTextBox.Location = new System.Drawing.Point(86, 15); this.pathTextBox.Name = "pathTextBox"; this.pathTextBox.ReadOnly = true; - this.pathTextBox.Size = new System.Drawing.Size(555, 23); + this.pathTextBox.Size = new System.Drawing.Size(585, 23); this.pathTextBox.TabIndex = 2; // // progressBar @@ -181,7 +195,7 @@ private void InitializeComponent() | System.Windows.Forms.AnchorStyles.Right))); this.progressBar.Location = new System.Drawing.Point(13, 513); this.progressBar.Name = "progressBar"; - this.progressBar.Size = new System.Drawing.Size(578, 23); + this.progressBar.Size = new System.Drawing.Size(608, 23); this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Continuous; this.progressBar.TabIndex = 12; // @@ -189,7 +203,7 @@ private void InitializeComponent() // this.allLinkLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.allLinkLabel.AutoSize = true; - this.allLinkLabel.Location = new System.Drawing.Point(56, 491); + this.allLinkLabel.Location = new System.Drawing.Point(61, 491); this.allLinkLabel.Name = "allLinkLabel"; this.allLinkLabel.Size = new System.Drawing.Size(21, 15); this.allLinkLabel.TabIndex = 6; @@ -201,7 +215,7 @@ private void InitializeComponent() // this.newLinkLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.newLinkLabel.AutoSize = true; - this.newLinkLabel.Location = new System.Drawing.Point(122, 491); + this.newLinkLabel.Location = new System.Drawing.Point(127, 491); this.newLinkLabel.Name = "newLinkLabel"; this.newLinkLabel.Size = new System.Drawing.Size(31, 15); this.newLinkLabel.TabIndex = 8; @@ -213,7 +227,7 @@ private void InitializeComponent() // this.instLinkLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.instLinkLabel.AutoSize = true; - this.instLinkLabel.Location = new System.Drawing.Point(159, 491); + this.instLinkLabel.Location = new System.Drawing.Point(164, 491); this.instLinkLabel.Name = "instLinkLabel"; this.instLinkLabel.Size = new System.Drawing.Size(51, 15); this.instLinkLabel.TabIndex = 9; @@ -235,7 +249,7 @@ private void InitializeComponent() // this.noneLinkLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.noneLinkLabel.AutoSize = true; - this.noneLinkLabel.Location = new System.Drawing.Point(80, 491); + this.noneLinkLabel.Location = new System.Drawing.Point(85, 491); this.noneLinkLabel.Name = "noneLinkLabel"; this.noneLinkLabel.Size = new System.Drawing.Size(36, 15); this.noneLinkLabel.TabIndex = 7; @@ -246,7 +260,7 @@ private void InitializeComponent() // exploreButton // this.exploreButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.exploreButton.Location = new System.Drawing.Point(649, 13); + this.exploreButton.Location = new System.Drawing.Point(679, 13); this.exploreButton.Name = "exploreButton"; this.exploreButton.Size = new System.Drawing.Size(95, 27); this.exploreButton.TabIndex = 3; @@ -258,7 +272,7 @@ private void InitializeComponent() // this.updateLinkLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.updateLinkLabel.AutoSize = true; - this.updateLinkLabel.Location = new System.Drawing.Point(216, 491); + this.updateLinkLabel.Location = new System.Drawing.Point(221, 491); this.updateLinkLabel.Name = "updateLinkLabel"; this.updateLinkLabel.Size = new System.Drawing.Size(50, 15); this.updateLinkLabel.TabIndex = 13; @@ -270,7 +284,7 @@ private void InitializeComponent() // this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cancelButton.Enabled = false; - this.cancelButton.Location = new System.Drawing.Point(557, 477); + this.cancelButton.Location = new System.Drawing.Point(587, 477); this.cancelButton.Name = "taskButton"; this.cancelButton.Size = new System.Drawing.Size(34, 32); this.cancelButton.TabIndex = 15; @@ -286,7 +300,7 @@ private void InitializeComponent() this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; - this.ClientSize = new System.Drawing.Size(757, 572); + this.ClientSize = new System.Drawing.Size(787, 572); this.Controls.Add(this.cancelButton); this.Controls.Add(this.updateLinkLabel); this.Controls.Add(this.exploreButton); @@ -302,12 +316,11 @@ private void InitializeComponent() this.Controls.Add(this.deleteButton); this.Controls.Add(this.listView); this.Controls.Add(this.statusStrip); - this.MinimumSize = new System.Drawing.Size(410, 340); + this.MinimumSize = new System.Drawing.Size(485, 340); this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Load += new EventHandler(this.MainFormLoad); this.HelpRequested += new HelpEventHandler(this.MainFormHelpRequested); this.HelpButtonClicked += new CancelEventHandler(this.MainFormHelpButtonClicked); - this.FormClosed += new FormClosedEventHandler(this.MainFormClosed); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); this.ResumeLayout(false); diff --git a/External/Tools/AppMan/MainForm.cs b/External/Tools/AppMan/MainForm.cs index eb1b9d6cea..de89bafa0a 100644 --- a/External/Tools/AppMan/MainForm.cs +++ b/External/Tools/AppMan/MainForm.cs @@ -1,15 +1,14 @@ using System; using System.IO; using System.Net; -using System.Data; -using System.Text; using System.Drawing; using System.Threading; using System.Reflection; using System.Diagnostics; using System.Windows.Forms; +using System.Drawing.Drawing2D; +using System.Security.Cryptography; using System.Collections.Generic; -using System.Runtime.InteropServices; using System.Xml.Serialization; using System.ComponentModel; using AppMan.Utilities; @@ -18,52 +17,93 @@ namespace AppMan { public partial class MainForm : Form, IMessageFilter { - private String curFile; - private String tempFile; - private String localeId; - private Boolean isLoading; - private DepEntry curEntry; - private String entriesFile; - private WebClient webClient; - private DepEntries depEntries; - private DepEntries instEntries; - private BackgroundWorker bgWorker; - private Dictionary entryStates; - private Dictionary appGroups; - private Queue downloadQueue; - private Queue fileQueue; - private LocaleData localeData; - private Boolean localeOverride; - private String[] notifyPaths; - private Boolean shouldNotify; - private Boolean haveUpdates; - private Boolean checkOnly; - - public MainForm(String[] args) - { - this.CheckArgs(args); - this.isLoading = false; - this.haveUpdates = false; - this.shouldNotify = false; - this.InitializeSettings(); - this.InitializeLocalization(); - this.InitializeComponent(); - this.InitializeGraphics(); - this.InitializeContextMenu(); - this.ApplyLocalizationStrings(); - this.Font = SystemFonts.MenuFont; - Application.AddMessageFilter(this); - } - - #region WIN32 Stuff - - #if WIN32 - [DllImport("user32.dll")] - public static extern IntPtr WindowFromPoint(Point pt); - - [DllImport("user32.dll")] - public static extern IntPtr SendMessage(IntPtr hWnd, Int32 msg, IntPtr wp, IntPtr lp); - #endif + string curFile; + string tempFile; + string localeId; + bool isLoading; + DepEntry curEntry; + string entriesFile; + WebClient webClient; + DepEntries depEntries; + DepEntries instEntries; + BackgroundWorker bgWorker; + Dictionary entryStates; + Dictionary appGroups; + Queue downloadQueue; + Queue fileQueue; + LocaleData localeData; + bool localeOverride; + bool configOverride; + string[] notifyPaths; + bool haveUpdates; + bool checkOnly; + string argsConfig; + + /** + * Static link label margin constant + */ + public static int LINK_MARGIN = 4; + + /** + * Static constant for current distribution + */ + public static string DISTRO_NAME = "FlashDevelop"; + + /** + * Static constant for exposed config groups (separated with ,) + */ + public static string EXPOSED_GROUPS = "FD5"; + + /** + * Static type and state constants + */ + public static string TYPE_LINK = "Link"; + public static string TYPE_EXECUTABLE = "Executable"; + public static string TYPE_ARCHIVE = "Archive"; + public static string STATE_INSTALLED = "Installed"; + public static string STATE_UPDATE = "Updated"; + public static string STATE_NEW = "New"; + + public MainForm(string[] args) + { + CheckArgs(args); + isLoading = false; + haveUpdates = false; + InitializeSettings(); + InitializeLocalization(); + InitializeComponent(); + InitializeGraphics(); + InitializeContextMenu(); + InitializeFormScaling(); + ApplyLocalizationStrings(); + Font = SystemFonts.MenuFont; + if (!Win32.IsRunningOnMono) Application.AddMessageFilter(this); + } + + #region Instancing + + /// + /// Handle the instance message + /// + protected override void WndProc(ref Message m) + { + if (m.Msg == Win32.WM_SHOWME) RestoreWindow(); + base.WndProc(ref m); + } + + /// + /// Restore the window of the first instance + /// + void RestoreWindow() + { + if (WindowState == FormWindowState.Minimized) + { + WindowState = FormWindowState.Normal; + } + bool top = TopMost; + TopMost = true; + TopMost = top; + } #endregion @@ -72,130 +112,142 @@ public MainForm(String[] args) /// /// Processes command line args. /// - private void CheckArgs(String[] args) + void CheckArgs(string[] args) { - this.checkOnly = false; - this.localeId = "en_US"; - this.localeOverride = false; - foreach (String arg in args) + checkOnly = false; + localeId = "en_US"; + localeOverride = false; + foreach (string arg in args) { // Handle minimized mode if (arg.Trim() == "-minimized") { - this.WindowState = FormWindowState.Minimized; - this.checkOnly = true; + WindowState = FormWindowState.Minimized; + checkOnly = true; } // Handle locale id values if (arg.Trim().Contains("-locale=")) { - this.localeId = arg.Trim().Substring("-locale=".Length); - this.localeOverride = true; + localeId = arg.Trim().Substring("-locale=".Length); + localeOverride = true; } + // Handle config values + if (arg.Trim().Contains("-config=")) + { + argsConfig = arg.Trim().Substring("-config=".Length); + configOverride = true; + } + } + } + + /// + /// Initialize the scaling of the form. + /// + void InitializeFormScaling() + { + if (GetScale() > 1) + { + descHeader.Width = ScaleValue(319); + nameHeader.Width = ScaleValue(160); + versionHeader.Width = ScaleValue(90); + statusHeader.Width = ScaleValue(70); + typeHeader.Width = ScaleValue(75); + infoHeader.Width = ScaleValue(30); + int width = Convert.ToInt32(Width * 1.06); + Size = new Size(width, Height); } } /// /// Initializes the graphics of the app. /// - private void InitializeGraphics() + void InitializeGraphics() { - Assembly assembly = Assembly.GetExecutingAssembly(); - this.cancelButton.Image = Image.FromStream(assembly.GetManifestResourceStream("AppMan.Resources.Cancel.png")); - this.Icon = new Icon(assembly.GetManifestResourceStream("AppMan.Resources.AppMan.ico")); + var imageList = new ImageList(); + var assembly = Assembly.GetExecutingAssembly(); + imageList.ColorDepth = ColorDepth.Depth32Bit; + imageList.ImageSize = new Size(ScaleValue(24), ScaleValue(24)); + imageList.Images.Add(Image.FromStream(assembly.GetManifestResourceStream("AppMan.Resources.Cancel.png"))); + Icon = new Icon(assembly.GetManifestResourceStream("AppMan.Resources.AppMan.ico")); + cancelButton.ImageList = imageList; + cancelButton.ImageIndex = 0; } /// /// Initializes the web client used for item downloads. /// - private void InitializeWebClient() + void InitializeWebClient() { - this.webClient = new WebClient(); - this.webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressChanged); - this.webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.DownloadFileCompleted); + ServicePointManager.SecurityProtocol = (SecurityProtocolType)(0xC0 | 0x300 | 0xC00); // SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12 + webClient = new WebClient(); + webClient.DownloadProgressChanged += DownloadProgressChanged; + webClient.DownloadFileCompleted += DownloadFileCompleted; } /// /// Initializes the localization of the app. /// - private void InitializeLocalization() + void InitializeLocalization() { - this.localeData = new LocaleData(); - String localeDir = Path.Combine(PathHelper.GetExeDirectory(), "Locales"); - String localeFile = Path.Combine(PathHelper.GetExeDirectory(), this.localeId + ".xml"); - if (File.Exists(localeFile)) - { - this.localeData = ObjectSerializer.Deserialize(localeFile, this.localeData) as LocaleData; - } + localeData = new LocaleData(); + var localeDir = Path.Combine(PathHelper.GetExeDirectory(), "Locales"); + var localeFile = Path.Combine(localeDir, localeId + ".xml"); + if (File.Exists(localeFile)) localeData = ObjectSerializer.Deserialize(localeFile, localeData) as LocaleData; } /// /// Applies the localization string to controls. /// - private void ApplyLocalizationStrings() + void ApplyLocalizationStrings() { - this.Text = this.localeData.MainFormTitle; - this.exploreButton.Text = this.localeData.ExploreLabel; - this.nameHeader.Text = this.localeData.NameHeader; - this.descHeader.Text = this.localeData.DescHeader; - this.statusHeader.Text = this.localeData.StatusHeader; - this.versionHeader.Text = this.localeData.VersionHeader; - this.typeHeader.Text = this.localeData.TypeHeader; - this.allLinkLabel.Text = this.localeData.LinkAll; - this.newLinkLabel.Text = this.localeData.LinkNew; - this.noneLinkLabel.Text = this.localeData.LinkNone; - this.instLinkLabel.Text = this.localeData.LinkInstalled; - this.updateLinkLabel.Text = this.localeData.LinkUpdates; - this.statusLabel.Text = this.localeData.NoItemsSelected; - this.pathLabel.Text = this.localeData.InstallPathLabel; - this.selectLabel.Text = this.localeData.SelectLabel; - this.installButton.Text = String.Format(this.localeData.InstallSelectedLabel, "0"); - this.deleteButton.Text = String.Format(this.localeData.DeleteSelectedLabel, "0"); + Text = localeData.MainFormTitle; + exploreButton.Text = localeData.ExploreLabel; + nameHeader.Text = localeData.NameHeader; + descHeader.Text = localeData.DescHeader; + statusHeader.Text = localeData.StatusHeader; + versionHeader.Text = localeData.VersionHeader; + typeHeader.Text = localeData.TypeHeader; + allLinkLabel.Text = localeData.LinkAll; + newLinkLabel.Text = localeData.LinkNew; + noneLinkLabel.Text = localeData.LinkNone; + instLinkLabel.Text = localeData.LinkInstalled; + updateLinkLabel.Text = localeData.LinkUpdates; + statusLabel.Text = localeData.NoItemsSelected; + pathLabel.Text = localeData.InstallPathLabel; + selectLabel.Text = localeData.SelectLabel; + installButton.Text = string.Format(localeData.InstallSelectedLabel, "0"); + deleteButton.Text = string.Format(localeData.DeleteSelectedLabel, "0"); } /// /// Initializes the settings of the app. /// - private void InitializeSettings() + void InitializeSettings() { try { Settings settings = new Settings(); - String file = Path.Combine(PathHelper.GetExeDirectory(), "Config.xml"); + string file = Path.Combine(PathHelper.GetExeDirectory(), "Config.xml"); + #if FLASHDEVELOP + // Use the customized config file if present next to normal config file... + if (File.Exists(file.Replace(".xml", ".local.xml"))) file = file.Replace(".xml", ".local.xml"); + #endif if (File.Exists(file)) { settings = ObjectSerializer.Deserialize(file, settings) as Settings; + if (!string.IsNullOrEmpty(settings.Name)) DISTRO_NAME = settings.Name; + if (!string.IsNullOrEmpty(settings.Groups)) EXPOSED_GROUPS = settings.Groups; PathHelper.APPS_DIR = ArgProcessor.ProcessArguments(settings.Archive); PathHelper.CONFIG_ADR = ArgProcessor.ProcessArguments(settings.Config); PathHelper.HELP_ADR = ArgProcessor.ProcessArguments(settings.Help); - if (!this.localeOverride) this.localeId = settings.Locale; - this.notifyPaths = settings.Paths; + PathHelper.LOG_DIR = ArgProcessor.ProcessArguments(settings.Logs); + if (!localeOverride) localeId = settings.Locale; + notifyPaths = settings.Paths; } - #if FLASHDEVELOP - else /* Defaults for FlashDevelop */ + if (configOverride) { - PathHelper.HELP_ADR = "http://www.flashdevelop.org/wikidocs/"; - PathHelper.CONFIG_ADR = "http://www.flashdevelop.org/appman.xml"; - String local = Path.Combine(PathHelper.GetExeDirectory(), @"..\..\.local"); - local = Path.GetFullPath(local); /* Fix weird path */ - if (!File.Exists(local)) - { - String userAppDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - String fdUserPath = Path.Combine(userAppDir, "FlashDevelop"); - String appManDataDir = Path.Combine(fdUserPath, @"Data\AppMan"); - this.notifyPaths = new String[1] { fdUserPath }; - PathHelper.APPS_DIR = Path.Combine(fdUserPath, "Apps"); - PathHelper.LOG_DIR = appManDataDir; - } - else - { - String fdPath = Path.Combine(PathHelper.GetExeDirectory(), @"..\..\"); - fdPath = Path.GetFullPath(fdPath); /* Fix weird path */ - PathHelper.APPS_DIR = Path.Combine(fdPath, "Apps"); - PathHelper.LOG_DIR = Path.Combine(fdPath, @"Data\AppMan"); - this.notifyPaths = new String[1] { fdPath }; - } + PathHelper.CONFIG_ADR = argsConfig; } - #endif if (!Directory.Exists(PathHelper.LOG_DIR)) { Directory.CreateDirectory(PathHelper.LOG_DIR); @@ -214,12 +266,12 @@ private void InitializeSettings() /// /// Initializes the list view context menu. /// - private void InitializeContextMenu() + void InitializeContextMenu() { ContextMenuStrip cms = new ContextMenuStrip(); - cms.Items.Add(this.localeData.ShowInfoLabel, null, new EventHandler(this.OnViewInfoClick)); - cms.Items.Add(this.localeData.ToggleCheckedLabel, null, new EventHandler(this.OnCheckToggleClick)); - this.listView.ContextMenuStrip = cms; + cms.Items.Add(localeData.ShowInfoLabel, null, OnViewInfoClick); + cms.Items.Add(localeData.ToggleCheckedLabel, null, OnCheckToggleClick); + listView.ContextMenuStrip = cms; } #endregion @@ -229,11 +281,11 @@ private void InitializeContextMenu() /// /// Closes the application when pressing Escape. /// - protected override Boolean ProcessCmdKey(ref Message msg, Keys k) + protected override bool ProcessCmdKey(ref Message msg, Keys k) { if (k == Keys.Escape) { - this.Close(); + Close(); return true; } return base.ProcessCmdKey(ref msg, k); @@ -243,26 +295,52 @@ protected override Boolean ProcessCmdKey(ref Message msg, Keys k) #region Event Handlers + /// + /// Handles the mouse wheel on hover + /// + public bool PreFilterMessage(ref Message m) + { + if (!Win32.IsRunningOnMono && m.Msg == 0x20a) // WM_MOUSEWHEEL + { + Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16); + IntPtr hWnd = Win32.WindowFromPoint(pos); + if (hWnd != IntPtr.Zero) + { + if (FromHandle(hWnd) != null) + { + Win32.SendMessage(hWnd, m.Msg, m.WParam, m.LParam); + return true; + } + else if (listView != null && hWnd == listView.Handle) + { + Win32.SendMessage(hWnd, m.Msg, m.WParam, m.LParam); + return true; + } + } + } + return false; + } + /// /// On MainForm show, initializes the UI and the props. /// - private void MainFormLoad(Object sender, EventArgs e) + void MainFormLoad(object sender, EventArgs e) { - this.InitializeWebClient(); - this.depEntries = new DepEntries(); - this.entryStates = new Dictionary(); - this.appGroups = new Dictionary(); - this.downloadQueue = new Queue(); - this.TryDeleteOldTempFiles(); - this.listView.Items.Clear(); - this.LoadInstalledEntries(); - this.LoadEntriesFile(); + InitializeWebClient(); + depEntries = new DepEntries(); + entryStates = new Dictionary(); + appGroups = new Dictionary(); + downloadQueue = new Queue(); + TryDeleteOldTempFiles(); + listView.Items.Clear(); + LoadInstalledEntries(); + LoadEntriesFile(); } /// /// Opens the help when pressing help button or F1. /// - private void MainFormHelpRequested(Object sender, HelpEventArgs e) + void MainFormHelpRequested(object sender, HelpEventArgs e) { try { @@ -273,29 +351,34 @@ private void MainFormHelpRequested(Object sender, HelpEventArgs e) DialogHelper.ShowError(ex.ToString()); } } - private void MainFormHelpButtonClicked(Object sender, CancelEventArgs e) + + /// + /// Opens the help when pressing help button or F1. + /// + void MainFormHelpButtonClicked(object sender, CancelEventArgs e) { e.Cancel = true; - this.MainFormHelpRequested(null, null); + MainFormHelpRequested(null, null); } /// - /// Save notification files to the notify paths + /// Save notification files to the notify paths. /// - private void MainFormClosed(Object sender, FormClosedEventArgs e) + void NotifyPaths(bool restart) { try { - if (!this.shouldNotify || this.notifyPaths == null) return; - foreach (String nPath in this.notifyPaths) + if (notifyPaths == null) return; + foreach (string nPath in notifyPaths) { try { - String path = Path.GetFullPath(ArgProcessor.ProcessArguments(nPath)); + string path = Path.GetFullPath(ArgProcessor.ProcessArguments(nPath)); if (Directory.Exists(path)) { - String amFile = Path.Combine(path, ".appman"); - File.WriteAllText(amFile, ""); + string amFile = Path.Combine(path, ".appman"); + if (restart) File.WriteAllText(amFile, "restart"); + else File.WriteAllText(amFile, ""); } } catch { /* NO ERRORS */ } @@ -310,18 +393,15 @@ private void MainFormClosed(Object sender, FormClosedEventArgs e) /// /// Open info file or url when clicked. /// - private void OnViewInfoClick(Object sender, EventArgs e) + void OnViewInfoClick(object sender, EventArgs e) { - if (this.listView.SelectedItems.Count > 0) + if (listView.SelectedItems.Count > 0) { - ListViewItem item = this.listView.SelectedItems[0]; - if (item != null) + var item = listView.SelectedItems[0]; + var entry = item?.Tag as DepEntry; + if (entry != null && !string.IsNullOrEmpty(entry.Info)) { - DepEntry entry = item.Tag as DepEntry; - if (entry != null && !String.IsNullOrEmpty(entry.Info)) - { - this.RunExecutableProcess(entry.Info); - } + RunExecutableProcess(entry.Info); } } } @@ -329,22 +409,23 @@ private void OnViewInfoClick(Object sender, EventArgs e) /// /// Toggles the check state of the item. /// - private void OnCheckToggleClick(Object sender, EventArgs e) + void OnCheckToggleClick(object sender, EventArgs e) { - if (this.listView.SelectedItems.Count > 0) + if (listView.SelectedItems.Count > 0) { - ListViewItem item = this.listView.SelectedItems[0]; + ListViewItem item = listView.SelectedItems[0]; if (item != null) item.Checked = !item.Checked; } } + /// /// Cancels the item download process. /// - private void CancelButtonClick(Object sender, EventArgs e) + void CancelButtonClick(object sender, EventArgs e) { try { - this.webClient.CancelAsync(); + webClient.CancelAsync(); } catch (Exception ex) { @@ -355,50 +436,50 @@ private void CancelButtonClick(Object sender, EventArgs e) /// /// Starts the download queue based on the user selections. /// - private void InstallButtonClick(Object sender, EventArgs e) + void InstallButtonClick(object sender, EventArgs e) { - this.isLoading = true; - this.cancelButton.Enabled = true; - this.installButton.Enabled = false; - this.deleteButton.Enabled = false; - this.AddEntriesToQueue(); - this.DownloadNextFromQueue(); + isLoading = true; + cancelButton.Enabled = true; + installButton.Enabled = false; + deleteButton.Enabled = false; + AddEntriesToQueue(); + DownloadNextFromQueue(); } /// /// Deletes the selected items from the archive. /// - private void DeleteButtonClick(Object sender, EventArgs e) + void DeleteButtonClick(object sender, EventArgs e) { try { - this.shouldNotify = true; - String title = this.localeData.ConfirmTitle; - String message = this.localeData.DeleteSelectedConfirm; + string title = localeData.ConfirmTitle; + string message = localeData.DeleteSelectedConfirm; if (MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { - foreach (ListViewItem item in this.listView.CheckedItems) + foreach (ListViewItem item in listView.CheckedItems) { DepEntry entry = item.Tag as DepEntry; - String state = this.entryStates[entry.Id]; - if (state == this.localeData.StateInstalled || state == this.localeData.StateUpdate) + string state = entryStates[entry.Id]; + if (state == STATE_INSTALLED || state == STATE_UPDATE) { #if FLASHDEVELOP if (entry.Urls[0].ToLower().EndsWith(".fdz")) { - String fileName = Path.GetFileName(entry.Urls[0]); - String delFile = Path.ChangeExtension(fileName, ".delete.fdz"); - String tempFile = this.GetTempFileName(delFile, true); - String entryDir = Path.Combine(PathHelper.APPS_DIR, entry.Id); - String versionDir = Path.Combine(entryDir, entry.Version.ToLower()); - String entryFile = Path.Combine(versionDir, fileName); + string fileName = Path.GetFileName(entry.Urls[0]); + string delFile = Path.ChangeExtension(fileName, ".delete.fdz"); + string tempFile = GetTempFileName(delFile, true); + string entryDir = Path.Combine(PathHelper.APPS_DIR, entry.Id); + string versionDir = Path.Combine(entryDir, entry.Version.ToLower()); + string entryFile = Path.Combine(versionDir, fileName); File.Copy(entryFile, tempFile, true); - this.RunExecutableProcess(tempFile); + RunExecutableProcess(tempFile); } #endif - Directory.Delete(Path.Combine(PathHelper.APPS_DIR, entry.Id), true); + TryDeleteEntryDir(entry); } } + NotifyPaths(false); } } catch (Exception ex) @@ -408,17 +489,17 @@ private void DeleteButtonClick(Object sender, EventArgs e) finally { Thread.Sleep(100); // Wait for files... - this.NoneLinkLabelLinkClicked(null, null); - this.LoadInstalledEntries(); - this.UpdateEntryStates(); - this.UpdateButtonLabels(); + NoneLinkLabelLinkClicked(null, null); + LoadInstalledEntries(); + UpdateEntryStates(); + UpdateButtonLabels(); } } /// /// Browses the archive with windows explorer. /// - private void ExploreButtonClick(Object sender, EventArgs e) + void ExploreButtonClick(object sender, EventArgs e) { try { @@ -433,48 +514,48 @@ private void ExploreButtonClick(Object sender, EventArgs e) /// /// On All link click, selects the all items. /// - private void AllLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) + void AllLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { - if (this.isLoading) return; - this.listView.BeginUpdate(); - foreach (ListViewItem item in this.listView.Items) + if (isLoading) return; + listView.BeginUpdate(); + foreach (ListViewItem item in listView.Items) { item.Checked = true; } - this.listView.EndUpdate(); + listView.EndUpdate(); } /// /// On None link click, deselects all items. /// - private void NoneLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) + void NoneLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { - if (this.isLoading) return; - this.listView.BeginUpdate(); - foreach (ListViewItem item in this.listView.Items) + if (isLoading) return; + listView.BeginUpdate(); + foreach (ListViewItem item in listView.Items) { item.Checked = false; } - this.listView.EndUpdate(); + listView.EndUpdate(); } /// /// On New link click, selects all new items. /// - private void NewLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) + void NewLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { - if (this.isLoading) return; - this.listView.BeginUpdate(); - foreach (ListViewItem item in this.listView.Items) + if (isLoading) return; + listView.BeginUpdate(); + foreach (ListViewItem item in listView.Items) { DepEntry entry = item.Tag as DepEntry; - String state = this.entryStates[entry.Id]; - if (state == this.localeData.StateNew) item.Checked = true; + string state = entryStates[entry.Id]; + if (state == STATE_NEW) item.Checked = true; else item.Checked = false; } - this.listView.EndUpdate(); + listView.EndUpdate(); } catch (Exception ex) { @@ -485,20 +566,20 @@ private void NewLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArg /// /// On Installed link click, selects all installed items. /// - private void InstLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) + void InstLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { - if (this.isLoading) return; - this.listView.BeginUpdate(); - foreach (ListViewItem item in this.listView.Items) + if (isLoading) return; + listView.BeginUpdate(); + foreach (ListViewItem item in listView.Items) { DepEntry entry = item.Tag as DepEntry; - String state = this.entryStates[entry.Id]; - if (state == this.localeData.StateInstalled) item.Checked = true; + string state = entryStates[entry.Id]; + if (state == STATE_INSTALLED) item.Checked = true; else item.Checked = false; } - this.listView.EndUpdate(); + listView.EndUpdate(); } catch (Exception ex) { @@ -509,20 +590,53 @@ private void InstLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventAr /// /// On Updates link click, selects all updatable items. /// - private void UpdatesLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEventArgs e) + void UpdatesLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) + { + try + { + if (isLoading) return; + listView.BeginUpdate(); + foreach (ListViewItem item in listView.Items) + { + DepEntry entry = item.Tag as DepEntry; + string state = entryStates[entry.Id]; + if (state == STATE_UPDATE) item.Checked = true; + else item.Checked = false; + } + listView.EndUpdate(); + } + catch (Exception ex) + { + DialogHelper.ShowError(ex.ToString()); + } + } + + /// + /// On bundle link click, selects all bundled items. + /// + void BundleLinkLabelLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { try { - if (this.isLoading) return; - this.listView.BeginUpdate(); - foreach (ListViewItem item in this.listView.Items) + if (isLoading) return; + listView.BeginUpdate(); + bool is64bit = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE", EnvironmentVariableTarget.Machine) != "x86"; + foreach (ListViewItem item in listView.Items) { DepEntry entry = item.Tag as DepEntry; - String state = this.entryStates[entry.Id]; - if (state == this.localeData.StateUpdate) item.Checked = true; + if (Array.IndexOf(entry.Bundles, e.Link.LinkData.ToString()) != -1) + { + if (!entry.Name.Contains("(x86)") && !entry.Name.Contains("(x64)")) item.Checked = true; + else + { + if (!is64bit && entry.Name.Contains("(x86)")) item.Checked = true; + else if (is64bit && entry.Name.Contains("(x64)")) item.Checked = true; + else item.Checked = false; + } + } else item.Checked = false; } - this.listView.EndUpdate(); + listView.EndUpdate(); } catch (Exception ex) { @@ -533,46 +647,86 @@ private void UpdatesLinkLabelLinkClicked(Object sender, LinkLabelLinkClickedEven /// /// Disables the item checking when downloading. /// - private void ListViewItemCheck(Object sender, ItemCheckEventArgs e) + void ListViewItemCheck(object sender, ItemCheckEventArgs e) { - if (this.isLoading) e.NewValue = e.CurrentValue; + if (isLoading) e.NewValue = e.CurrentValue; } /// /// Updates the button labels when item is checked. /// - private void ListViewItemChecked(Object sender, ItemCheckedEventArgs e) + void ListViewItemChecked(object sender, ItemCheckedEventArgs e) { - if (this.isLoading) return; - this.UpdateButtonLabels(); + if (isLoading) return; + UpdateButtonLabels(); } /// - /// Handles the mouse wheel on hover + /// Handles the clicking of the info item. /// - public Boolean PreFilterMessage(ref Message m) + void ListViewClick(object sender, EventArgs e) { - #if WIN32 - if (m.Msg == 0x20a) // WM_MOUSEWHEEL + Point point = listView.PointToClient(MousePosition); + ListViewHitTestInfo hitTest = listView.HitTest(point); + int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem); + if (columnIndex == 2) { - Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16); - IntPtr hWnd = WindowFromPoint(pos); - if (hWnd != IntPtr.Zero) + DepEntry entry = hitTest.Item.Tag as DepEntry; + RunExecutableProcess(entry.Info); + } + } + + /// + /// Change cursor when hovering info sub item. + /// + void ListViewMouseMove(object sender, MouseEventArgs e) + { + Point point = listView.PointToClient(MousePosition); + ListViewHitTestInfo hitTest = listView.HitTest(point); + if (hitTest.Item != null) + { + int columnIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem); + if (columnIndex == 2) Cursor = Cursors.Hand; + else Cursor = Cursors.Default; + } + } + + /// + /// Handles the drawing of the info image. + /// + readonly Image InfoImage = Image.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("AppMan.Resources.Information.png")); + + void ListViewDrawSubItem(object sender, DrawListViewSubItemEventArgs e) + { + if (e.Header == infoHeader) + { + if (!e.Item.Selected && (e.ItemState & ListViewItemStates.Selected) == 0) { - if (Control.FromHandle(hWnd) != null) - { - SendMessage(hWnd, m.Msg, m.WParam, m.LParam); - return true; - } - else if (this.listView != null && hWnd == this.listView.Handle) - { - SendMessage(hWnd, m.Msg, m.WParam, m.LParam); - return true; - } + e.DrawBackground(); } + else if (e.Item.Selected) + { + e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds); + } + int posOffsetX = (e.Bounds.Width - e.Bounds.Height) / 2; + e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + e.Graphics.DrawImage(InfoImage, new Rectangle(e.Bounds.X + posOffsetX, e.Bounds.Y + 1, e.Bounds.Height - 2, e.Bounds.Height - 2)); } - #endif - return false; + else e.DrawDefault = true; + } + + void ListViewDrawItem(object sender, DrawListViewItemEventArgs e) + { + if ((e.State & ListViewItemStates.Selected) != 0) + { + e.Graphics.FillRectangle(SystemBrushes.Highlight, e.Bounds); + } + else e.DrawDefault = true; + } + + void ListViewDrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e) + { + e.DrawDefault = true; } #endregion @@ -582,14 +736,14 @@ public Boolean PreFilterMessage(ref Message m) /// /// Completes the minimized update process. /// - private void CompleteMinimizedProcess() + void CompleteMinimizedProcess() { - if (this.checkOnly) + if (checkOnly) { - if (this.haveUpdates) + if (haveUpdates) { - this.WindowState = FormWindowState.Normal; - this.Activate(); + WindowState = FormWindowState.Normal; + Activate(); } else Application.Exit(); } @@ -598,27 +752,27 @@ private void CompleteMinimizedProcess() /// /// Updates the buttons labels. /// - private void UpdateButtonLabels() + void UpdateButtonLabels() { try { - Int32 inst = 0; - Int32 dele = 0; - if (this.isLoading) return; - foreach (ListViewItem item in this.listView.CheckedItems) + int inst = 0; + int dele = 0; + if (isLoading) return; + foreach (ListViewItem item in listView.CheckedItems) { DepEntry entry = item.Tag as DepEntry; - if (this.entryStates.ContainsKey(entry.Id)) + if (entryStates.ContainsKey(entry.Id)) { - String state = this.entryStates[entry.Id]; - if (state == this.localeData.StateInstalled || state == this.localeData.StateUpdate) dele++; - if (state == this.localeData.StateNew || state == this.localeData.StateUpdate) inst++; + string state = entryStates[entry.Id]; + if (state == STATE_INSTALLED || state == STATE_UPDATE) dele++; + if (state == STATE_NEW || state == STATE_UPDATE) inst++; } } - this.installButton.Text = String.Format(this.localeData.InstallSelectedLabel, inst); - this.deleteButton.Text = String.Format(this.localeData.DeleteSelectedLabel, dele); - this.deleteButton.Enabled = dele > 0; - this.installButton.Enabled = inst > 0; + installButton.Text = string.Format(localeData.InstallSelectedLabel, inst); + deleteButton.Text = string.Format(localeData.DeleteSelectedLabel, dele); + deleteButton.Enabled = dele > 0; + installButton.Enabled = inst > 0; } catch (Exception ex) { @@ -629,27 +783,30 @@ private void UpdateButtonLabels() /// /// Populates the list view with current entries. /// - private void PopulateListView() + void PopulateListView() { try { - this.listView.BeginUpdate(); - this.pathTextBox.Text = PathHelper.APPS_DIR; - foreach (DepEntry entry in this.depEntries) + listView.BeginUpdate(); + pathTextBox.Text = PathHelper.APPS_DIR; + foreach (DepEntry entry in depEntries) { ListViewItem item = new ListViewItem(entry.Name); item.Tag = entry; /* Store for later */ item.SubItems.Add(entry.Version); + item.SubItems.Add(entry.Info); item.SubItems.Add(entry.Desc); - item.SubItems.Add(this.localeData.StateNew); - item.SubItems.Add(this.IsExecutable(entry) ? this.localeData.ExecutableType : this.localeData.ArchiveType); - this.listView.Items.Add(item); - this.AddToGroup(item); + item.SubItems.Add(GetLocaleState(STATE_NEW)); + item.SubItems.Add(GetLocaleType(entry.Type)); + listView.Items.Add(item); + AddToGroup(item); } - if (this.appGroups.Count > 1) this.listView.ShowGroups = true; - else this.listView.ShowGroups = false; - this.UpdateEntryStates(); - this.listView.EndUpdate(); + if (appGroups.Count > 1) listView.ShowGroups = true; + else listView.ShowGroups = false; + UpdateEntryStates(); + UpdateLinkPositions(); + GenerateBundleLinks(); + listView.EndUpdate(); } catch (Exception ex) { @@ -657,24 +814,65 @@ private void PopulateListView() } } + /// + /// Update the link label positions for example if the font is different size. + /// + void UpdateLinkPositions() + { + allLinkLabel.Location = new Point(selectLabel.Bounds.Right + LINK_MARGIN, allLinkLabel.Location.Y); + noneLinkLabel.Location = new Point(allLinkLabel.Bounds.Right + LINK_MARGIN, allLinkLabel.Location.Y); + newLinkLabel.Location = new Point(noneLinkLabel.Bounds.Right + LINK_MARGIN, allLinkLabel.Location.Y); + instLinkLabel.Location = new Point(newLinkLabel.Bounds.Right + LINK_MARGIN, allLinkLabel.Location.Y); + updateLinkLabel.Location = new Point(instLinkLabel.Bounds.Right + LINK_MARGIN, allLinkLabel.Location.Y); + } + + /// + /// Generates the bundle selection links. + /// + void GenerateBundleLinks() + { + LinkLabel prevLink = updateLinkLabel; + List bundleLinks = new List(); + foreach (DepEntry entry in depEntries) + { + foreach (string bundle in entry.Bundles) + { + if (!bundleLinks.Contains(bundle)) + { + LinkLabel linkLabel = new LinkLabel(); + linkLabel.Anchor = ((AnchorStyles)((AnchorStyles.Bottom | AnchorStyles.Left))); + linkLabel.LinkClicked += BundleLinkLabelLinkClicked; + linkLabel.Location = new Point(prevLink.Bounds.Right + LINK_MARGIN, allLinkLabel.Location.Y); + linkLabel.Links[0].LinkData = bundle; + linkLabel.LinkColor = Color.Green; + linkLabel.AutoSize = true; + linkLabel.Text = bundle; + bundleLinks.Add(bundle); + Controls.Add(linkLabel); + prevLink = linkLabel; + } + } + } + } + /// /// Adds the entry into a new or existing group. /// - private void AddToGroup(ListViewItem item) + void AddToGroup(ListViewItem item) { try { DepEntry entry = item.Tag as DepEntry; - if (this.appGroups.ContainsKey(entry.Group)) + if (appGroups.ContainsKey(entry.Group)) { - ListViewGroup lvg = this.appGroups[entry.Group]; + ListViewGroup lvg = appGroups[entry.Group]; item.Group = lvg; } else { ListViewGroup lvg = new ListViewGroup(entry.Group); - this.appGroups[entry.Group] = lvg; - this.listView.Groups.Add(lvg); + appGroups[entry.Group] = lvg; + listView.Groups.Add(lvg); item.Group = lvg; } } @@ -687,14 +885,14 @@ private void AddToGroup(ListViewItem item) /// /// Creates a temporary file with the given extension. /// - private String GetTempFileName(String file, Boolean unique) + string GetTempFileName(string file, bool unique) { try { - Int32 counter = 0; - String tempDir = Path.GetTempPath(); - String fileName = Path.GetFileName(file); - String tempFile = Path.Combine(tempDir, "appman_" + fileName); + int counter = 0; + string tempDir = Path.GetTempPath(); + string fileName = Path.GetFileName(file); + string tempFile = Path.Combine(tempDir, "appman_" + fileName); if (!unique) return tempFile; while (File.Exists(tempFile)) { @@ -713,33 +911,65 @@ private String GetTempFileName(String file, Boolean unique) /// /// Tries to delete old temp files. /// - private void TryDeleteOldTempFiles() + void TryDeleteOldTempFiles() { - String path = Path.GetTempPath(); - String[] oldFiles = Directory.GetFiles(path, "appman_*.*"); - foreach (String file in oldFiles) + string path = Path.GetTempPath(); + string[] oldFiles = Directory.GetFiles(path, "appman_*.*"); + foreach (string file in oldFiles) { try { File.Delete(file); } catch { /* NO ERRORS */ } } } + /// + /// Try to delete old entry directory + /// + void TryDeleteEntryDir(DepEntry entry) + { + string folder = Path.Combine(PathHelper.APPS_DIR, entry.Id); + // Sometimes we might get "dir not empty" error, try 10 times... + for (int attempts = 0; attempts < 10; attempts++) + { + try + { + if (Directory.Exists(folder)) Directory.Delete(folder, true); + return; + } + catch (IOException) { Thread.Sleep(50); } + } + throw new Exception(localeData.DeleteDirError + folder); + } + /// /// Runs an executable process. /// - private void RunExecutableProcess(String file) + void RunExecutableProcess(string file, bool wait) { try { #if FLASHDEVELOP if (file.ToLower().EndsWith(".fdz")) { - String fd = Path.Combine(PathHelper.GetExeDirectory(), @"..\..\FlashDevelop.exe"); - Process.Start(Path.GetFullPath(fd), file + " -silent -reuse"); - return; + string fd = Path.Combine(PathHelper.GetExeDirectory(), @"..\..\" + DISTRO_NAME + ".exe"); + bool waitfd = Process.GetProcessesByName(DISTRO_NAME).Length == 0; + if (File.Exists(fd)) + { + Process.Start(Path.GetFullPath(fd), "\"" + file + "\" -silent -reuse"); + // If FD was not running, give it a little time to start... + if (waitfd) Thread.Sleep(500); + return; + } } #endif - Process.Start(file); + Process process = new Process(); + process.StartInfo.FileName = file; + process.Start(); + if (wait) + { + process.WaitForExit(); + NotifyPaths(true); + } } catch (Exception ex) { @@ -747,12 +977,45 @@ private void RunExecutableProcess(String file) } } + void RunExecutableProcess(string file) + { + RunExecutableProcess(file, false); + } + + /// + /// Gets the locale string for state + /// + string GetLocaleState(string state) + { + if (state == STATE_INSTALLED) return localeData.StateInstalled; + else if (state == STATE_UPDATE) return localeData.StateUpdate; + else return localeData.StateNew; + } + + /// + /// Gets the locale string for type + /// + string GetLocaleType(string type) + { + if (type == TYPE_LINK) return localeData.TypeLink; + else if (type == TYPE_EXECUTABLE) return localeData.TypeExecutable; + else return localeData.TypeArchive; + } + + /// + /// Checks if entry is an executable. + /// + bool IsExecutable(DepEntry entry) + { + return entry.Type == TYPE_EXECUTABLE; + } + /// /// Checks if entry is an executable. /// - private Boolean IsExecutable(DepEntry entry) + bool IsLink(DepEntry entry) { - return entry.Type == this.localeData.ExecutableType; + return entry.Type == TYPE_LINK; } #endregion @@ -762,26 +1025,26 @@ private Boolean IsExecutable(DepEntry entry) /// /// Downloads the entry config file. /// - private void LoadEntriesFile() + void LoadEntriesFile() { try { if (PathHelper.CONFIG_ADR.StartsWith("http")) { WebClient client = new WebClient(); - this.entriesFile = Path.GetTempFileName(); - client.DownloadFileCompleted += new AsyncCompletedEventHandler(this.EntriesDownloadCompleted); - client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressChanged); - client.DownloadFileAsync(new Uri(PathHelper.CONFIG_ADR), this.entriesFile); - this.statusLabel.Text = this.localeData.DownloadingItemList; + entriesFile = Path.GetTempFileName(); + client.DownloadFileCompleted += EntriesDownloadCompleted; + client.DownloadProgressChanged += DownloadProgressChanged; + client.DownloadFileAsync(new Uri(PathHelper.CONFIG_ADR), entriesFile); + statusLabel.Text = localeData.DownloadingItemList; } else { - this.entriesFile = PathHelper.CONFIG_ADR; - Object data = ObjectSerializer.Deserialize(this.entriesFile, this.depEntries); - this.statusLabel.Text = this.localeData.ItemListOpened; - this.depEntries = data as DepEntries; - this.PopulateListView(); + entriesFile = PathHelper.CONFIG_ADR; + object data = ObjectSerializer.Deserialize(entriesFile, depEntries, EXPOSED_GROUPS); + statusLabel.Text = localeData.ItemListOpened; + depEntries = data as DepEntries; + PopulateListView(); } } catch (Exception ex) @@ -790,28 +1053,29 @@ private void LoadEntriesFile() } finally { - this.CompleteMinimizedProcess(); + CompleteMinimizedProcess(); } } /// /// When entry config is loaded, populates the list view. /// - private void EntriesDownloadCompleted(Object sender, AsyncCompletedEventArgs e) + void EntriesDownloadCompleted(object sender, AsyncCompletedEventArgs e) { try { - Boolean fileExists = File.Exists(this.entriesFile); - Boolean fileIsValid = File.ReadAllText(this.entriesFile).Length > 0; + bool fileExists = File.Exists(entriesFile); + bool fileIsValid = File.ReadAllText(entriesFile).Length > 0; if (e.Error == null && fileExists && fileIsValid) { - this.statusLabel.Text = this.localeData.DownloadedItemList; - Object data = ObjectSerializer.Deserialize(this.entriesFile, this.depEntries); - this.depEntries = data as DepEntries; - this.PopulateListView(); + statusLabel.Text = localeData.DownloadedItemList; + object data = ObjectSerializer.Deserialize(entriesFile, depEntries, EXPOSED_GROUPS); + depEntries = data as DepEntries; + PopulateListView(); } - else this.statusLabel.Text = this.localeData.ItemListDownloadFailed; - this.progressBar.Value = 0; + else statusLabel.Text = localeData.ItemListDownloadFailed; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress); + progressBar.Value = 0; } catch (Exception ex) { @@ -819,8 +1083,8 @@ private void EntriesDownloadCompleted(Object sender, AsyncCompletedEventArgs e) } finally { - this.CompleteMinimizedProcess(); - try { File.Delete(this.entriesFile); } + CompleteMinimizedProcess(); + try { File.Delete(entriesFile); } catch { /* NO ERRORS*/ } } } @@ -828,18 +1092,18 @@ private void EntriesDownloadCompleted(Object sender, AsyncCompletedEventArgs e) /// /// Adds the currently selected entries to download queue. /// - private void AddEntriesToQueue() + void AddEntriesToQueue() { try { - this.downloadQueue.Clear(); - foreach (ListViewItem item in this.listView.CheckedItems) + downloadQueue.Clear(); + foreach (ListViewItem item in listView.CheckedItems) { DepEntry entry = item.Tag as DepEntry; - String state = this.entryStates[entry.Id]; - if (state == this.localeData.StateNew || state == this.localeData.StateUpdate) + string state = entryStates[entry.Id]; + if (state == STATE_NEW || state == STATE_UPDATE) { - this.downloadQueue.Enqueue(entry); + downloadQueue.Enqueue(entry); } } } @@ -852,30 +1116,46 @@ private void AddEntriesToQueue() /// /// Downloads next item from the queue. /// - private void DownloadNextFromQueue() + void DownloadNextFromQueue() { try { - this.fileQueue = new Queue(); - this.curEntry = this.downloadQueue.Dequeue(); - foreach (String file in this.curEntry.Urls) + fileQueue = new Queue(); + curEntry = downloadQueue.Dequeue(); + foreach (string file in curEntry.Urls) + { + if (IsLink(curEntry)) RunExecutableProcess(file); + else fileQueue.Enqueue(file); + } + if (IsLink(curEntry)) { - this.fileQueue.Enqueue(file); + if (downloadQueue.Count > 0) DownloadNextFromQueue(); + else + { + isLoading = false; + progressBar.Value = 0; + cancelButton.Enabled = false; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress); + statusLabel.Text = localeData.AllItemsCompleted; + NoneLinkLabelLinkClicked(null, null); + UpdateButtonLabels(); + } + return; } - this.curFile = this.fileQueue.Dequeue(); - this.tempFile = this.GetTempFileName(this.curFile, false); - this.curEntry.Temps[this.curFile] = this.tempFile; // Save for cmd - if (File.Exists(this.tempFile)) // Use already downloaded temp... + curFile = fileQueue.Dequeue(); + tempFile = GetTempFileName(curFile, false); + curEntry.Temps[curFile] = tempFile; // Save for cmd + if (File.Exists(tempFile)) // Use already downloaded temp... { - String idPath = Path.Combine(PathHelper.APPS_DIR, this.curEntry.Id); - String vnPath = Path.Combine(idPath, this.curEntry.Version.ToLower()); - this.ExtractFile(this.tempFile, vnPath); + string idPath = Path.Combine(PathHelper.APPS_DIR, curEntry.Id); + string vnPath = Path.Combine(idPath, curEntry.Version.ToLower()); + ExtractFile(tempFile, vnPath); return; } - this.tempFile = this.GetTempFileName(this.curFile, true); - this.curEntry.Temps[this.curFile] = this.tempFile; // Save for cmd - this.webClient.DownloadFileAsync(new Uri(this.curFile), this.tempFile); - this.statusLabel.Text = this.localeData.DownloadingFile + this.curFile; + tempFile = GetTempFileName(curFile, true); + curEntry.Temps[curFile] = tempFile; // Save for cmd + webClient.DownloadFileAsync(new Uri(curFile), tempFile); + statusLabel.Text = localeData.DownloadingFile + curFile; } catch (Exception ex) { @@ -886,46 +1166,75 @@ private void DownloadNextFromQueue() /// /// Updates the progress bar for individual downloads. /// - private void DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e) + void DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { - this.progressBar.Value = e.ProgressPercentage; + progressBar.Value = e.ProgressPercentage; + TaskbarProgress.SetValue(Handle, e.ProgressPercentage, 100); } /// /// When file is downloaded, check for errors and extract the file. /// - private void DownloadFileCompleted(Object sender, AsyncCompletedEventArgs e) + void DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { try { if (e.Cancelled) { - this.isLoading = false; - this.cancelButton.Enabled = false; - this.statusLabel.Text = this.localeData.ItemListDownloadCancelled; - this.TryDeleteOldTempFiles(); - this.progressBar.Value = 0; - this.UpdateButtonLabels(); + isLoading = false; + cancelButton.Enabled = false; + statusLabel.Text = localeData.ItemListDownloadCancelled; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress); + TryDeleteOldTempFiles(); + progressBar.Value = 0; + UpdateButtonLabels(); } else if (e.Error == null) { - String idPath = Path.Combine(PathHelper.APPS_DIR, this.curEntry.Id); - String vnPath = Path.Combine(idPath, this.curEntry.Version.ToLower()); - this.ExtractFile(this.tempFile, vnPath); + // Verify checksum of the file if specified + if (!string.IsNullOrEmpty(curEntry.Checksum) && !VerifyFile(curEntry.Checksum, tempFile)) + { + string message = localeData.ChecksumVerifyError + curFile + ".\n"; + if (downloadQueue.Count > 0) message += localeData.ContinueWithNextItem; + DialogHelper.ShowError(message); // Show message first... + if (downloadQueue.Count > 0) DownloadNextFromQueue(); + else + { + isLoading = false; + progressBar.Value = 0; + cancelButton.Enabled = false; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress); + statusLabel.Text = localeData.AllItemsCompleted; + NoneLinkLabelLinkClicked(null, null); + TryDeleteEntryDir(curEntry); + TryDeleteOldTempFiles(); + UpdateButtonLabels(); + } + } + else + { + string idPath = Path.Combine(PathHelper.APPS_DIR, curEntry.Id); + string vnPath = Path.Combine(idPath, curEntry.Version.ToLower()); + ExtractFile(tempFile, vnPath); + } } else { - String message = this.localeData.DownloadingError + this.curFile + ".\n"; - if (this.downloadQueue.Count > 1) message += this.localeData.ContinueWithNextItem; + string message = localeData.DownloadingError + curFile + ".\n"; + if (downloadQueue.Count > 0) message += localeData.ContinueWithNextItem; DialogHelper.ShowError(message); // Show message first... - if (this.downloadQueue.Count > 1) this.DownloadNextFromQueue(); + if (downloadQueue.Count > 0) DownloadNextFromQueue(); else { - this.isLoading = false; - this.cancelButton.Enabled = false; - this.TryDeleteOldTempFiles(); - this.progressBar.Value = 0; - this.UpdateButtonLabels(); + isLoading = false; + progressBar.Value = 0; + cancelButton.Enabled = false; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress); + statusLabel.Text = localeData.AllItemsCompleted; + NoneLinkLabelLinkClicked(null, null); + TryDeleteEntryDir(curEntry); + TryDeleteOldTempFiles(); + UpdateButtonLabels(); } } } @@ -938,110 +1247,140 @@ private void DownloadFileCompleted(Object sender, AsyncCompletedEventArgs e) /// /// Starts the extraction work in a background thread. /// - private void ExtractFile(String file, String path) + void ExtractFile(string file, string path) { try { - this.bgWorker = new BackgroundWorker(); - this.bgWorker.DoWork += new DoWorkEventHandler(this.WorkerDoWork); - this.bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(this.WorkerDoCompleted); - this.bgWorker.RunWorkerAsync(new BgArg(file, path)); - this.statusLabel.Text = this.localeData.ExtractingFile + this.curFile; - this.progressBar.Style = ProgressBarStyle.Marquee; + bgWorker = new BackgroundWorker(); + bgWorker.DoWork += WorkerDoWork; + bgWorker.RunWorkerCompleted += WorkerDoCompleted; + bgWorker.RunWorkerAsync(new BgArg(file, path)); + statusLabel.Text = localeData.ExtractingFile + curFile; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.Indeterminate); + progressBar.Style = ProgressBarStyle.Marquee; } catch { - String message = this.localeData.ExtractingError + this.curFile + ".\n"; - if (this.downloadQueue.Count > 1) message += this.localeData.ContinueWithNextItem; - DialogHelper.ShowError(message); - this.DownloadNextFromQueue(); + string message = localeData.ExtractingError + curFile + ".\n"; + if (downloadQueue.Count > 0) message += localeData.ContinueWithNextItem; + DialogHelper.ShowError(message); // Show message first... + if (downloadQueue.Count > 0) DownloadNextFromQueue(); + else + { + isLoading = false; + progressBar.Value = 0; + cancelButton.Enabled = false; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress); + statusLabel.Text = localeData.AllItemsCompleted; + NoneLinkLabelLinkClicked(null, null); + TryDeleteEntryDir(curEntry); + TryDeleteOldTempFiles(); + UpdateButtonLabels(); + } } } /// /// Completes the actual extraction or file manipulation. /// - private void WorkerDoWork(Object sender, DoWorkEventArgs e) + void WorkerDoWork(object sender, DoWorkEventArgs e) { try { BgArg args = e.Argument as BgArg; - String url = new Uri(this.curFile).LocalPath; - Boolean shouldExecute = this.IsExecutable(this.curEntry); + string url = new Uri(curFile).LocalPath; + bool shouldExecute = IsExecutable(curEntry); if (!Directory.Exists(args.Path) && !shouldExecute) Directory.CreateDirectory(args.Path); if (Path.GetExtension(url) == ".zip") ZipHelper.ExtractZip(args.File, args.Path); else if (!shouldExecute) { - String fileName = Path.GetFileName(url); - File.Copy(this.tempFile, Path.Combine(args.Path, fileName), true); + string fileName = Path.GetFileName(url); + File.Copy(tempFile, Path.Combine(args.Path, fileName), true); } } catch { - DialogHelper.ShowError(this.localeData.ExtractingError + this.curFile + ".\n" + this.localeData.ContinueWithNextItem); - this.DownloadNextFromQueue(); + string message = localeData.ExtractingError + curFile + ".\n"; + if (downloadQueue.Count > 0) message += localeData.ContinueWithNextItem; + DialogHelper.ShowError(message); // Show message first... + if (downloadQueue.Count > 0) DownloadNextFromQueue(); + else + { + isLoading = false; + progressBar.Value = 0; + cancelButton.Enabled = false; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress); + statusLabel.Text = localeData.AllItemsCompleted; + NoneLinkLabelLinkClicked(null, null); + TryDeleteEntryDir(curEntry); + TryDeleteOldTempFiles(); + UpdateButtonLabels(); + } } } /// - /// When file hasd been handled, continues to next file or download next item. + /// When file has been handled, continues to next file or download next item. /// - private void WorkerDoCompleted(Object sender, RunWorkerCompletedEventArgs e) + void WorkerDoCompleted(object sender, RunWorkerCompletedEventArgs e) { try { - this.progressBar.Style = ProgressBarStyle.Continuous; - if (this.fileQueue.Count > 0) + progressBar.Style = ProgressBarStyle.Continuous; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.Normal); + if (fileQueue.Count > 0) { - this.curFile = this.fileQueue.Dequeue(); - this.tempFile = this.GetTempFileName(this.curFile, false); - this.curEntry.Temps[this.curFile] = this.tempFile; // Save for cmd - if (File.Exists(this.tempFile)) // Use downloaded temp... + curFile = fileQueue.Dequeue(); + tempFile = GetTempFileName(curFile, false); + curEntry.Temps[curFile] = tempFile; // Save for cmd + if (File.Exists(tempFile)) // Use downloaded temp... { - String idPath = Path.Combine(PathHelper.APPS_DIR, this.curEntry.Id); - String vnPath = Path.Combine(idPath, this.curEntry.Version.ToLower()); - this.ExtractFile(this.tempFile, vnPath); - this.bgWorker.Dispose(); + string idPath = Path.Combine(PathHelper.APPS_DIR, curEntry.Id); + string vnPath = Path.Combine(idPath, curEntry.Version.ToLower()); + ExtractFile(tempFile, vnPath); + bgWorker.Dispose(); return; } - this.tempFile = this.GetTempFileName(this.curFile, true); - this.curEntry.Temps[this.curFile] = this.tempFile; // Save for cmd - this.webClient.DownloadFileAsync(new Uri(this.curFile), this.tempFile); - this.statusLabel.Text = this.localeData.DownloadingFile + this.curFile; + tempFile = GetTempFileName(curFile, true); + curEntry.Temps[curFile] = tempFile; // Save for cmd + webClient.DownloadFileAsync(new Uri(curFile), tempFile); + statusLabel.Text = localeData.DownloadingFile + curFile; } else { - if (!this.IsExecutable(this.curEntry)) + if (!IsExecutable(curEntry)) { - String idPath = Path.Combine(PathHelper.APPS_DIR, this.curEntry.Id); - this.RunEntrySetup(idPath, this.curEntry); - this.SaveEntryInfo(idPath, this.curEntry); + string idPath = Path.Combine(PathHelper.APPS_DIR, curEntry.Id); + RunEntrySetup(idPath, curEntry); + SaveEntryInfo(idPath, curEntry); #if FLASHDEVELOP - if (this.curEntry.Urls[0].ToLower().EndsWith(".fdz")) + if (curEntry.Urls[0].ToLower().EndsWith(".fdz")) { - String vnPath = Path.Combine(idPath, this.curEntry.Version.ToLower()); - String fileName = Path.GetFileName(this.curEntry.Urls[0]); - this.RunExecutableProcess(Path.Combine(vnPath, fileName)); + string vnPath = Path.Combine(idPath, curEntry.Version.ToLower()); + string fileName = Path.GetFileName(curEntry.Urls[0]); + string filePath = Path.Combine(vnPath, fileName); + RunExecutableProcess(filePath); } #endif Thread.Sleep(100); // Wait for files... - this.LoadInstalledEntries(); - this.shouldNotify = true; - this.UpdateEntryStates(); + LoadInstalledEntries(); + UpdateEntryStates(); + NotifyPaths(false); } - else this.RunExecutableProcess(this.tempFile); - if (this.downloadQueue.Count > 0) this.DownloadNextFromQueue(); + else RunExecutableProcess(tempFile, true); + if (downloadQueue.Count > 0) DownloadNextFromQueue(); else { - this.isLoading = false; - this.progressBar.Value = 0; - this.cancelButton.Enabled = false; - this.statusLabel.Text = this.localeData.AllItemsCompleted; - this.NoneLinkLabelLinkClicked(null, null); - this.UpdateButtonLabels(); + isLoading = false; + progressBar.Value = 0; + cancelButton.Enabled = false; + TaskbarProgress.SetState(Handle, TaskbarProgress.TaskbarStates.NoProgress); + statusLabel.Text = localeData.AllItemsCompleted; + NoneLinkLabelLinkClicked(null, null); + UpdateButtonLabels(); } } - this.bgWorker.Dispose(); + bgWorker.Dispose(); } catch (Exception ex) { @@ -1052,7 +1391,7 @@ private void WorkerDoCompleted(Object sender, RunWorkerCompletedEventArgs e) /// /// Saves the entry info into a xml file. /// - private void SaveEntryInfo(String path, DepEntry entry) + void SaveEntryInfo(string path, DepEntry entry) { try { @@ -1068,21 +1407,21 @@ private void SaveEntryInfo(String path, DepEntry entry) /// /// Reads the xml entry files from the archive. /// - private void LoadInstalledEntries() + void LoadInstalledEntries() { try { - this.instEntries = new DepEntries(); - List entryFiles = new List(); - String[] entryDirs = Directory.GetDirectories(PathHelper.APPS_DIR); - foreach (String dir in entryDirs) + instEntries = new DepEntries(); + List entryFiles = new List(); + string[] entryDirs = Directory.GetDirectories(PathHelper.APPS_DIR); + foreach (string dir in entryDirs) { entryFiles.AddRange(Directory.GetFiles(dir, "*.xml")); } - foreach (String file in entryFiles) + foreach (string file in entryFiles) { - Object data = ObjectSerializer.Deserialize(file, new DepEntry()); - this.instEntries.Add(data as DepEntry); + object data = ObjectSerializer.Deserialize(file, new DepEntry()); + instEntries.Add(data as DepEntry); } } catch (Exception ex) @@ -1094,74 +1433,134 @@ private void LoadInstalledEntries() /// /// Updates the entry states of the all items. /// - private void UpdateEntryStates() + void UpdateEntryStates() { try { - this.listView.BeginUpdate(); - foreach (ListViewItem item in this.listView.Items) + listView.BeginUpdate(); + foreach (ListViewItem item in listView.Items) { DepEntry dep = item.Tag as DepEntry; - item.SubItems[3].ForeColor = SystemColors.ControlText; - this.entryStates[dep.Id] = this.localeData.StateNew; - item.SubItems[3].Text = this.localeData.StateNew; - foreach (DepEntry inst in this.instEntries) + item.UseItemStyleForSubItems = false; + item.SubItems[4].ForeColor = SystemColors.ControlText; + item.SubItems[4].Text = GetLocaleState(STATE_NEW); + entryStates[dep.Id] = STATE_NEW; + foreach (DepEntry inst in instEntries) { - item.UseItemStyleForSubItems = false; if (dep.Id == inst.Id) { Color color = Color.Green; - String text = this.localeData.StateInstalled; - if (String.CompareOrdinal(dep.Version, inst.Version) > 0 || (dep.Version == inst.Version && dep.Build != inst.Build)) + string state = STATE_INSTALLED; + string text = GetLocaleState(STATE_INSTALLED); + if (CustomCompare(dep, inst) > 0 || (dep.Version == inst.Version && dep.Build != inst.Build)) { - this.haveUpdates = true; - text = this.localeData.StateUpdate; + haveUpdates = true; + text = GetLocaleState(STATE_UPDATE); + state = STATE_UPDATE; color = Color.Orange; } - this.entryStates[inst.Id] = text; - item.SubItems[3].ForeColor = color; - item.SubItems[3].Text = text; + entryStates[inst.Id] = state; + item.SubItems[4].ForeColor = color; + item.SubItems[4].Text = text; + // If we get an exact match, we don't need to compare more... + if (dep.Version == inst.Version && dep.Build == inst.Build) + { + break; + } } } } - this.listView.EndUpdate(); + listView.EndUpdate(); + } + catch (Exception ex) + { + DialogHelper.ShowError(ex.ToString()); + } + } + + /// + /// Compare version numbers + /// + int CustomCompare(DepEntry dep, DepEntry inst) + { + try + { + string[] v1 = dep.Version.Replace("+", ".").Split('.'); + string[] v2 = inst.Version.Replace("+", ".").Split('.'); + for (int i = 0; i < v1.Length; i++) + { + try + { + int t1 = Convert.ToInt32(v1[i]); + int t2 = Convert.ToInt32(v2[i]); + int comp = t1.CompareTo(t2); + if (comp > 0) return 1; + else if (comp < 0) return -1; + } + catch {}; + } + return 0; + } + catch (Exception ex) + { + DialogHelper.ShowError(ex.ToString()); + return 0; + } + } + + /// + /// Verifies the checksum (MD5 in hex) of the file. + /// + bool VerifyFile(string checksum, string file) + { + try + { + using (MD5 md5 = MD5.Create()) + { + using (Stream stream = File.OpenRead(file)) + { + string hex = BitConverter.ToString(md5.ComputeHash(stream)).Replace("-", ""); + return hex.ToLower() == checksum.ToLower(); + } + } } catch (Exception ex) { DialogHelper.ShowError(ex.ToString()); + return false; } } /// /// Executes the next setup command from queue. /// - private void RunEntrySetup(String path, DepEntry entry) + void RunEntrySetup(string path, DepEntry entry) { try { - if (!String.IsNullOrEmpty(entry.Cmd)) + if (!string.IsNullOrEmpty(entry.Cmd)) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); - String data = ArgProcessor.ProcessArguments(entry.Cmd); - for (var i = 0; i < entry.Urls.Length; i++) + string data = ArgProcessor.ProcessArguments(entry.Cmd); + for (int i = 0; i < entry.Urls.Length; i++) { - String url = entry.Urls[i]; + string url = entry.Urls[i]; if (entry.Temps.ContainsKey(url)) { - String index = i.ToString(); - String temp = entry.Temps[url]; + string index = i.ToString(); + string temp = entry.Temps[url]; data = data.Replace("$URL{" + index + "}", url); data = data.Replace("$TMP{" + index + "}", temp); } } - String cmd = Path.Combine(path, entry.Version + ".cmd"); + string cmd = Path.Combine(path, entry.Version + ".cmd"); File.WriteAllText(cmd, data); Process process = new Process(); process.StartInfo.FileName = cmd; process.EnableRaisingEvents = true; process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; process.StartInfo.WorkingDirectory = Path.GetDirectoryName(cmd); - process.Exited += delegate(Object sender, EventArgs e) + process.Exited += delegate(object sender, EventArgs e) { try { File.Delete(cmd); } catch { /* NO ERRORS */ }; @@ -1177,19 +1576,49 @@ private void RunEntrySetup(String path, DepEntry entry) #endregion + #region Scaling Helpers + + /// + /// Current scale of the form. + /// + double curScale = double.MinValue; + + /// + /// Resizes based on display scale. + /// + public int ScaleValue(int value) + { + return (int)(value * GetScale()); + } + + /// + /// Gets the current display scale. + /// + public double GetScale() + { + if (curScale != double.MinValue) return curScale; + using (Graphics g = Graphics.FromHwnd(Handle)) + { + curScale = g.DpiX / 96f; + } + return curScale; + } + + #endregion + } #region Data Items public class BgArg { - public String File = ""; - public String Path = ""; + public string File; + public string Path; - public BgArg(String file, String path) + public BgArg(string file, string path) { - this.File = file; - this.Path = path; + File = file; + Path = path; } } @@ -1197,41 +1626,47 @@ public BgArg(String file, String path) [XmlType("Entry")] public class DepEntry { - public String Id = ""; - public String Name = ""; - public String Desc = ""; - public String Group = ""; - public String Version = ""; - public String Build = ""; - public String Type = ""; - public String Info = ""; - public String Cmd = ""; + public string Id = ""; + public string Name = ""; + public string Desc = ""; + public string Group = ""; + public string Version = ""; + public string Checksum = ""; + public string Build = ""; + public string Type = ""; + public string Info = ""; + public string Cmd = ""; [XmlArrayItem("Url")] - public String[] Urls = new String[0]; + public string[] Urls = new string[0]; + + [XmlArrayItem("Bundle")] + public string[] Bundles = new string[0]; [XmlIgnore] - public Dictionary Temps; + public Dictionary Temps; public DepEntry() { - this.Type = "Archive"; - this.Temps = new Dictionary(); + Type = MainForm.TYPE_ARCHIVE; + Temps = new Dictionary(); } - public DepEntry(String id, String name, String desc, String group, String version, String build, String type, String info, String cmd, String[] urls) + public DepEntry(string id, string name, string desc, string group, string version, string build, string type, string info, string cmd, string[] urls, string[] bundles, string checksum) { - this.Id = id; - this.Name = name; - this.Desc = desc; - this.Group = group; - this.Build = build; - this.Version = version; - this.Temps = new Dictionary(); - if (!String.IsNullOrEmpty(type)) this.Type = type; - else this.Type = "Archive"; - this.Info = info; - this.Urls = urls; - this.Cmd = cmd; + Id = id; + Name = name; + Desc = desc; + Group = group; + Build = build; + Version = version; + Bundles = bundles; + Checksum = checksum; + Temps = new Dictionary(); + if (!string.IsNullOrEmpty(type)) Type = type; + else Type = MainForm.TYPE_ARCHIVE; + Info = info; + Urls = urls; + Cmd = cmd; } } @@ -1245,22 +1680,28 @@ public DepEntries() {} [Serializable] public class Settings { - public String Help = ""; - public String Config = ""; - public String Archive = ""; - public String Locale = "en_US"; + public string Help = ""; + public string Logs = ""; + public string Config = ""; + public string Archive = ""; + public string Locale = "en_US"; + public string Name = "FlashDevelop"; + public string Groups = "FD5"; [XmlArrayItem("Path")] - public String[] Paths = new String[0]; + public string[] Paths = new string[0]; public Settings() {} - public Settings(String config, String archive, String[] paths, String locale, String help) + public Settings(string config, string archive, string[] paths, string locale, string help, string logs, string name, string groups) { - this.Paths = paths; - this.Config = config; - this.Archive = archive; - this.Locale = locale; - this.Help = help; + Logs = logs; + Paths = paths; + Config = config; + Archive = archive; + Locale = locale; + Groups = groups; + Name = name; + Help = help; } } @@ -1270,45 +1711,47 @@ public Settings(String config, String archive, String[] paths, String locale, St public class LocaleData { public LocaleData() {} - public String NameHeader = "Name"; - public String VersionHeader = "Version"; - public String DescHeader = "Description"; - public String StatusHeader = "Status"; - public String TypeHeader = "Type"; - public String StateNew = "New"; - public String StateUpdate = "Update"; - public String StateInstalled = "Installed"; - public String ExtractingFile = "Extracting: "; - public String DownloadingFile = "Downloading: "; - public String DownloadingItemList = "Downloading item list..."; - public String NoItemsSelected = "No items selected."; - public String ItemListOpened = "Item list read from file."; - public String DownloadedItemList = "Item list downloaded."; - public String AllItemsCompleted = "All selected items completed."; - public String ItemListDownloadCancelled = "Item list download cancelled."; - public String ItemListDownloadFailed = "Item list could not be downloaded."; - public String DeleteSelectedConfirm = "Are you sure to delete all versions of the selected items?"; - public String ContinueWithNextItem = "Trying to continue with the next item."; - public String DownloadingError = "Error while downloading file: "; - public String ExtractingError = "Error while extracting file: "; - public String MainFormTitle = "AppMan"; - public String ConfirmTitle = "Confirm"; - public String LinkAll = "All"; - public String LinkNone = "None"; - public String LinkInstalled = "Installed"; - public String LinkUpdates = "Updates"; - public String LinkNew = "New"; - public String SelectLabel = "Select:"; - public String ExploreLabel = "Explore..."; - public String InstallPathLabel = "Install path:"; - public String DeleteSelectedLabel = "Delete {0} items."; - public String InstallSelectedLabel = "Install {0} items."; - public String ToggleCheckedLabel = "Toggle Checked"; - public String ShowInfoLabel = "Show Info..."; - public String ExecutableType = "Executable"; - public String ArchiveType = "Archive"; + public string NameHeader = "Name"; + public string VersionHeader = "Version"; + public string DescHeader = "Description"; + public string StatusHeader = "Status"; + public string TypeHeader = "Type"; + public string StateNew = "New"; + public string StateUpdate = "Update"; + public string StateInstalled = "Installed"; + public string ExtractingFile = "Extracting: "; + public string DownloadingFile = "Downloading: "; + public string DownloadingItemList = "Downloading item list..."; + public string NoItemsSelected = "No items selected."; + public string ItemListOpened = "Item list read from file."; + public string DownloadedItemList = "Item list downloaded."; + public string AllItemsCompleted = "All selected items completed."; + public string ItemListDownloadCancelled = "Item list download cancelled."; + public string ItemListDownloadFailed = "Item list could not be downloaded."; + public string DeleteSelectedConfirm = "Are you sure to delete all versions of the selected items?"; + public string ContinueWithNextItem = "Trying to continue with the next item."; + public string ChecksumVerifyError = "The specified checksum did not match the file: "; + public string DownloadingError = "Error while downloading file: "; + public string ExtractingError = "Error while extracting file: "; + public string DeleteDirError = "Error while deleting directory: "; + public string MainFormTitle = "AppMan"; + public string ConfirmTitle = "Confirm"; + public string LinkAll = "All"; + public string LinkNone = "None"; + public string LinkInstalled = "Installed"; + public string LinkUpdates = "Updates"; + public string LinkNew = "New"; + public string SelectLabel = "Select:"; + public string ExploreLabel = "Explore..."; + public string InstallPathLabel = "Install path:"; + public string DeleteSelectedLabel = "Delete {0} items."; + public string InstallSelectedLabel = "Install {0} items."; + public string ToggleCheckedLabel = "Toggle Checked"; + public string ShowInfoLabel = "Show Info..."; + public string TypeExecutable = "Executable"; + public string TypeArchive = "Archive"; + public string TypeLink = "Link"; } #endregion - -} +} \ No newline at end of file diff --git a/External/Tools/AppMan/Program.cs b/External/Tools/AppMan/Program.cs index 773c9bb5a8..ffb23ce135 100644 --- a/External/Tools/AppMan/Program.cs +++ b/External/Tools/AppMan/Program.cs @@ -1,35 +1,41 @@ using System; -using System.Collections.Generic; -using System.Runtime.InteropServices; using System.Windows.Forms; using System.Threading; namespace AppMan { - static class Program + internal static class Program { /// /// SIA Mutex entry /// - private static Mutex mutex = new Mutex(true, "{2A46BA9B-F8DA-40AA-904F-4C1630BA4428}"); + static readonly Mutex mutex = new Mutex(true, "{2A46BA9B-F8DA-40AA-904F-4C1630BA4428}"); /// /// The main entry point for the application. /// [STAThread] - static void Main(String[] args) + static void Main(string[] args) { - if (mutex.WaitOne(TimeSpan.Zero, true)) + try { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new MainForm(args)); - mutex.ReleaseMutex(); + if (mutex.WaitOne(TimeSpan.Zero, true)) + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new MainForm(args)); + mutex.ReleaseMutex(); + } + else if (Array.IndexOf(args, "-minimized") == -1) + { + if (Win32.IsRunningOnMono) MessageBox.Show("AppMan is already running."); + else Win32.PostMessage((IntPtr)Win32.HWND_BROADCAST, Win32.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); + } } - else if (Array.IndexOf(args, "-minimized") == -1) + catch (Exception ex) { - MessageBox.Show("AppMan is already running."); + MessageBox.Show("Error while starting AppMan:\n" + ex.ToString()); } } } -} +} \ No newline at end of file diff --git a/External/Tools/AppMan/Properties/AssemblyInfo.cs b/External/Tools/AppMan/Properties/AssemblyInfo.cs index b74f1a1c66..3327b94282 100644 --- a/External/Tools/AppMan/Properties/AssemblyInfo.cs +++ b/External/Tools/AppMan/Properties/AssemblyInfo.cs @@ -1,15 +1,13 @@ using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; // Information about this assembly is defined by the following attributes. // Change them to the information which is associated with the assembly you compile. [assembly: AssemblyTitle("AppMan")] [assembly: AssemblyProduct("AppMan")] [assembly: AssemblyDescription("Tool for managing apps.")] -[assembly: AssemblyCopyright("FlashDevelop.org 2005-2014")] +[assembly: AssemblyCopyright("FlashDevelop.org 2005-2015")] [assembly: AssemblyCompany("FlashDevelop.org")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] -[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyVersion("1.0.0.1")] diff --git a/External/Tools/AppMan/Properties/Program.manifest b/External/Tools/AppMan/Properties/Program.manifest new file mode 100644 index 0000000000..d06ae0c81a --- /dev/null +++ b/External/Tools/AppMan/Properties/Program.manifest @@ -0,0 +1,8 @@ + + + + + true + + + \ No newline at end of file diff --git a/External/Tools/AppMan/Resources/Cancel.png b/External/Tools/AppMan/Resources/Cancel.png index d1f5b925bd..1b20ae0d08 100644 Binary files a/External/Tools/AppMan/Resources/Cancel.png and b/External/Tools/AppMan/Resources/Cancel.png differ diff --git a/External/Tools/AppMan/Resources/Information.png b/External/Tools/AppMan/Resources/Information.png new file mode 100644 index 0000000000..93c67f2bf0 Binary files /dev/null and b/External/Tools/AppMan/Resources/Information.png differ diff --git a/External/Tools/AppMan/Utilities/ArgProcessor.cs b/External/Tools/AppMan/Utilities/ArgProcessor.cs index ffe638df4b..85a8b69bb5 100644 --- a/External/Tools/AppMan/Utilities/ArgProcessor.cs +++ b/External/Tools/AppMan/Utilities/ArgProcessor.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.IO; namespace AppMan.Utilities @@ -8,12 +6,23 @@ namespace AppMan.Utilities public class ArgProcessor { /// - /// Processes the internal argruments in a string. + /// Processes the internal arguments in a string. /// - public static String ProcessArguments(String data) + public static string ProcessArguments(string data) { data = data.Replace("$(Quote)", "\""); data = data.Replace("$(AppDir)", PathHelper.GetExeDirectory()); + #if FLASHDEVELOP + var local = Path.Combine(PathHelper.GetExeDirectory(), @"..\..\.local"); + local = Path.GetFullPath(local); /* Fix weird path */ + if (!File.Exists(local)) + { + var userAppDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + var fdUserPath = Path.Combine(userAppDir, MainForm.DISTRO_NAME); + data = data.Replace("$(BaseDir)", fdUserPath); + } + else data = data.Replace("$(BaseDir)", Path.GetDirectoryName(local)); + #endif data = Environment.ExpandEnvironmentVariables(data); return data; } diff --git a/External/Tools/AppMan/Utilities/DialogHelper.cs b/External/Tools/AppMan/Utilities/DialogHelper.cs index 21f7c12ac2..0eaa021399 100644 --- a/External/Tools/AppMan/Utilities/DialogHelper.cs +++ b/External/Tools/AppMan/Utilities/DialogHelper.cs @@ -1,7 +1,4 @@ -using System; -using System.IO; -using System.Text; -using System.Collections.Generic; +using System.IO; using System.Windows.Forms; namespace AppMan.Utilities @@ -11,12 +8,12 @@ public class DialogHelper /// /// Shows an error dialog to the user. /// - public static void ShowError(String message) + public static void ShowError(string message) { MessageBox.Show(message, " Error", MessageBoxButtons.OK, MessageBoxIcon.Error); try { - String logFile = Path.Combine(PathHelper.LOG_DIR, "Exceptions.log"); + var logFile = Path.Combine(PathHelper.LOG_DIR, "Exceptions.log"); File.AppendAllText(logFile, message + "\n\r\n\r"); } catch { /* NO ERRORS */ } @@ -25,19 +22,11 @@ public static void ShowError(String message) /// /// Shows a warning dialog to the user. /// - public static void ShowWarning(String message) - { - MessageBox.Show(message, " Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); - } + public static void ShowWarning(string message) => MessageBox.Show(message, " Warning", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); /// - /// Shows an infromation dialog to the user. + /// Shows an information dialog to the user. /// - public static void ShowInformation(String message) - { - MessageBox.Show(message, " Information", MessageBoxButtons.OK, MessageBoxIcon.Information); - } - + public static void ShowInformation(string message) => MessageBox.Show(message, " Information", MessageBoxButtons.OK, MessageBoxIcon.Information); } - -} +} \ No newline at end of file diff --git a/External/Tools/AppMan/Utilities/ObjectSerializer.cs b/External/Tools/AppMan/Utilities/ObjectSerializer.cs index f73b8f7f15..546cefa34a 100644 --- a/External/Tools/AppMan/Utilities/ObjectSerializer.cs +++ b/External/Tools/AppMan/Utilities/ObjectSerializer.cs @@ -2,7 +2,6 @@ using System.IO; using System.Text; using System.Xml.Serialization; -using System.Windows.Forms; namespace AppMan.Utilities { @@ -11,13 +10,13 @@ public class ObjectSerializer /// /// Serializes the specified object to a xml file. /// - public static void Serialize(String file, Object obj) + public static void Serialize(string file, object obj) { try { using (TextWriter writer = new StreamWriter(file, false, Encoding.UTF8)) { - XmlSerializer serializer = new XmlSerializer(obj.GetType()); + var serializer = new XmlSerializer(obj.GetType()); serializer.Serialize(writer, obj); } } @@ -28,16 +27,24 @@ public static void Serialize(String file, Object obj) } /// - /// Deserializes the specified object from a xml file. + /// Deserializes the specified object from a xml file. Optionally exposes commented groups. /// - public static Object Deserialize(String file, Object obj) + public static object Deserialize(string file, object obj) => Deserialize(file, obj, string.Empty); + + public static object Deserialize(string file, object obj, string groups) { try { using (TextReader reader = new StreamReader(file, Encoding.UTF8, false)) { - XmlSerializer serializer = new XmlSerializer(obj.GetType()); - return serializer.Deserialize(reader); + var xmlData = reader.ReadToEnd(); + var exGroups = groups.Split(','); + foreach (var group in exGroups) + { + xmlData = xmlData.Replace("", ""); + } + var serializer = new XmlSerializer(obj.GetType()); + return serializer.Deserialize(new StringReader(xmlData)); } } catch (Exception ex) @@ -46,7 +53,5 @@ public static Object Deserialize(String file, Object obj) return null; } } - } - -} +} \ No newline at end of file diff --git a/External/Tools/AppMan/Utilities/PathHelper.cs b/External/Tools/AppMan/Utilities/PathHelper.cs index f4d8c63377..7ea2b11525 100644 --- a/External/Tools/AppMan/Utilities/PathHelper.cs +++ b/External/Tools/AppMan/Utilities/PathHelper.cs @@ -1,7 +1,4 @@ -using System; -using System.IO; -using System.Text; -using System.Collections.Generic; +using System.IO; using System.Windows.Forms; namespace AppMan.Utilities @@ -11,31 +8,26 @@ public class PathHelper /// /// Default path to the log dir. /// - public static String LOG_DIR = ArgProcessor.ProcessArguments("$(AppDir)"); + public static string LOG_DIR = ArgProcessor.ProcessArguments("$(AppDir)"); /// /// Default path to the apps directory. /// - public static String APPS_DIR = ArgProcessor.ProcessArguments("$(AppDir)/Apps"); + public static string APPS_DIR = ArgProcessor.ProcessArguments("$(AppDir)/Apps"); /// /// Default path to the app help. /// - public static String HELP_ADR = ArgProcessor.ProcessArguments("$(AppDir)/Help.html"); + public static string HELP_ADR = ArgProcessor.ProcessArguments("$(AppDir)/Help.html"); /// /// Default path to the config xml file. /// - public static String CONFIG_ADR = ArgProcessor.ProcessArguments("$(AppDir)/Config.xml"); + public static string CONFIG_ADR = ArgProcessor.ProcessArguments("$(AppDir)/Config.xml"); /// /// Gets the directory of the app. /// - public static String GetExeDirectory() - { - return Path.GetDirectoryName(Application.ExecutablePath); - } - + public static string GetExeDirectory() => Path.GetDirectoryName(Application.ExecutablePath); } - -} +} \ No newline at end of file diff --git a/External/Tools/AppMan/Utilities/TaskbarProgress.cs b/External/Tools/AppMan/Utilities/TaskbarProgress.cs new file mode 100644 index 0000000000..44b0c19185 --- /dev/null +++ b/External/Tools/AppMan/Utilities/TaskbarProgress.cs @@ -0,0 +1,71 @@ +using System; +using System.Runtime.InteropServices; + +// http://stackoverflow.com/questions/1295890/windows-7-progress-bar-in-taskbar-in-c + +namespace AppMan.Utilities +{ + public static class TaskbarProgress + { + public enum TaskbarStates + { + NoProgress = 0, + Indeterminate = 0x1, + Normal = 0x2, + Error = 0x4, + Paused = 0x8 + } + + [ComImportAttribute()] + [GuidAttribute("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")] + [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + interface ITaskbarList3 + { + // ITaskbarList + [PreserveSig] + void HrInit(); + [PreserveSig] + void AddTab(IntPtr hwnd); + [PreserveSig] + void DeleteTab(IntPtr hwnd); + [PreserveSig] + void ActivateTab(IntPtr hwnd); + [PreserveSig] + void SetActiveAlt(IntPtr hwnd); + // ITaskbarList2 + [PreserveSig] + void MarkFullscreenWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.Bool)] bool fFullscreen); + // ITaskbarList3 + [PreserveSig] + void SetProgressValue(IntPtr hwnd, ulong ullCompleted, ulong ullTotal); + [PreserveSig] + void SetProgressState(IntPtr hwnd, TaskbarStates state); + } + + [GuidAttribute("56FDF344-FD6D-11d0-958A-006097C9A090")] + [ClassInterfaceAttribute(ClassInterfaceType.None)] + [ComImportAttribute()] + class TaskbarInstance {} + + static ITaskbarList3 taskbarInstance; + static readonly bool taskbarSupported = (Environment.OSVersion.Version >= new Version(6, 1)) && !Win32.IsRunningOnMono; + + public static void SetState(IntPtr windowHandle, TaskbarStates taskbarState) + { + if (taskbarSupported) + { + if (taskbarInstance == null) taskbarInstance = (ITaskbarList3)new TaskbarInstance(); + taskbarInstance.SetProgressState(windowHandle, taskbarState); + } + } + + public static void SetValue(IntPtr windowHandle, double progressValue, double progressMax) + { + if (taskbarSupported) + { + if (taskbarInstance == null) taskbarInstance = (ITaskbarList3)new TaskbarInstance(); + taskbarInstance.SetProgressValue(windowHandle, (ulong)progressValue, (ulong)progressMax); + } + } + } +} \ No newline at end of file diff --git a/External/Tools/AppMan/Utilities/ZipHelper.cs b/External/Tools/AppMan/Utilities/ZipHelper.cs index 8d9777632f..f00d3d182d 100644 --- a/External/Tools/AppMan/Utilities/ZipHelper.cs +++ b/External/Tools/AppMan/Utilities/ZipHelper.cs @@ -1,7 +1,5 @@ using System; using System.IO; -using System.Text; -using System.Collections.Generic; using ICSharpCode.SharpZipLib.Zip; namespace AppMan.Utilities @@ -11,31 +9,33 @@ public class ZipHelper /// /// Extracts a zip file to specified directory. /// - public static void ExtractZip(String file, String path) + public static void ExtractZip(string file, string path) { // Save current directory - String curDir = Environment.CurrentDirectory; + var curDir = Environment.CurrentDirectory; try { - ZipEntry entry = null; - ZipInputStream zis = new ZipInputStream(new FileStream(file, FileMode.Open, FileAccess.Read)); + ZipEntry entry; + var zis = new ZipInputStream(new FileStream(file, FileMode.Open, FileAccess.Read)); Environment.CurrentDirectory = path; // Used to work around long path issue while ((entry = zis.GetNextEntry()) != null) { - Int32 size = 4096; - Byte[] data = new Byte[4096]; + var data = new byte[4096]; if (entry.IsFile) { - String ext = Path.GetExtension(entry.Name); - String dirPath = Path.GetDirectoryName(entry.Name); - if (!String.IsNullOrEmpty(dirPath) && !Directory.Exists(dirPath)) + var dirPath = Path.GetDirectoryName(entry.Name); + if (!string.IsNullOrEmpty(dirPath) && !Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } - FileStream extracted = new FileStream(entry.Name, FileMode.Create); + + var fullPath = Path.Combine(path, entry.Name); + var extracted = Win32.IsRunningOnMono + ? File.Open(fullPath, FileMode.Create, FileAccess.Write) + : Win32.LongPathFileOpen(fullPath); while (true) { - size = zis.Read(data, 0, data.Length); + var size = zis.Read(data, 0, data.Length); if (size > 0) extracted.Write(data, 0, size); else break; } @@ -55,7 +55,5 @@ public static void ExtractZip(String file, String path) // Restore current directory Environment.CurrentDirectory = curDir; } - } - -} +} \ No newline at end of file diff --git a/External/Tools/AppMan/Win32.cs b/External/Tools/AppMan/Win32.cs new file mode 100644 index 0000000000..640fcc01df --- /dev/null +++ b/External/Tools/AppMan/Win32.cs @@ -0,0 +1,96 @@ +using System; +using System.IO; +using System.Text; +using System.Drawing; +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +namespace AppMan +{ + public class Win32 + { + /// + /// Public static props + /// + public static bool IsRunningOnMono; + public static int HWND_BROADCAST = 0xffff; + public static int WM_SHOWME; + + static Win32() + { + IsRunningOnMono = Type.GetType("Mono.Runtime") != null; + if (!IsRunningOnMono) WM_SHOWME = RegisterWindowMessage("WM_SHOWME"); + } + + #region Externs + + [DllImport("user32.dll")] + public static extern IntPtr WindowFromPoint(Point pt); + + [DllImport("user32.dll")] + public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern uint GetFullPathName(string lpFileName, uint nBufferLength, StringBuilder lpBuffer, IntPtr mustBeNull); + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + internal static extern SafeFileHandle CreateFile(string lpFileName, EFileAccess dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile); + + [DllImport("user32.dll")] + public static extern bool PostMessage(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam); + + [DllImport("user32.dll")] + public static extern int RegisterWindowMessage(string message); + + #endregion + + #region Long Path + + // See: http://bcl.codeplex.com/wikipage?title=Long%20Path&referringTitle=Home + const string LongPathPrefix = @"\\?\"; + + [Flags] + internal enum EFileAccess : uint + { + GenericRead = 0x80000000, + GenericWrite = 0x40000000, + GenericExecute = 0x20000000, + GenericAll = 0x10000000, + } + + /// + /// + /// + public static FileStream LongPathFileOpen(string path) + { + string normalizedPath = NormalizeLongPath(path); + SafeFileHandle handle = CreateFile(normalizedPath, EFileAccess.GenericWrite, (uint)FileShare.None, IntPtr.Zero, (uint)FileMode.Create, (uint)FileOptions.None, IntPtr.Zero); + if (handle.IsInvalid) throw new Exception("Error while resolving path."); + return new FileStream(handle, FileAccess.Write, 1024, false); + } + + /// + /// + /// + internal static string NormalizeLongPath(string path) + { + StringBuilder buffer = new StringBuilder(path.Length + 1); + uint length = GetFullPathName(path, (uint)buffer.Capacity, buffer, IntPtr.Zero); + if (length > buffer.Capacity) + { + buffer.Capacity = (int)length; + length = GetFullPathName(path, length, buffer, IntPtr.Zero); + } + if (length == 0 || length > 32000) + { + throw new Exception("Error while resolving path."); + } + return LongPathPrefix + buffer.ToString(); + } + + #endregion + + } + +} + diff --git a/External/Tools/AppMan/ZipLib/BZip2/BZip2.cs b/External/Tools/AppMan/ZipLib/BZip2/BZip2.cs index 91669a86d1..e593d3bf13 100644 --- a/External/Tools/AppMan/ZipLib/BZip2/BZip2.cs +++ b/External/Tools/AppMan/ZipLib/BZip2/BZip2.cs @@ -40,66 +40,66 @@ using System.IO; namespace ICSharpCode.SharpZipLib.BZip2 { - - /// - /// An example class to demonstrate compression and decompression of BZip2 streams. - /// - public static class BZip2 - { - /// - /// Decompress the input writing - /// uncompressed data to the output stream - /// - /// The readable stream containing data to decompress. - /// The output stream to receive the decompressed data. - /// Both streams are closed on completion if true. - public static void Decompress(Stream inStream, Stream outStream, bool isStreamOwner) - { - if (inStream == null || outStream == null) { - throw new Exception("Null Stream"); - } - - try { - using (BZip2InputStream bzipInput = new BZip2InputStream(inStream)) { - bzipInput.IsStreamOwner = isStreamOwner; - Core.StreamUtils.Copy(bzipInput, outStream, new byte[4096]); - } - } finally { - if (isStreamOwner) { - // inStream is closed by the BZip2InputStream if stream owner - outStream.Close(); - } - } - } - - /// - /// Compress the input stream sending - /// result data to output stream - /// - /// The readable stream to compress. - /// The output stream to receive the compressed data. - /// Both streams are closed on completion if true. - /// Block size acts as compression level (1 to 9) with 1 giving - /// the lowest compression and 9 the highest. - public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int level) - { - if (inStream == null || outStream == null) { - throw new Exception("Null Stream"); - } + + /// + /// An example class to demonstrate compression and decompression of BZip2 streams. + /// + public static class BZip2 + { + /// + /// Decompress the input writing + /// uncompressed data to the output stream + /// + /// The readable stream containing data to decompress. + /// The output stream to receive the decompressed data. + /// Both streams are closed on completion if true. + public static void Decompress(Stream inStream, Stream outStream, bool isStreamOwner) + { + if (inStream == null || outStream == null) { + throw new Exception("Null Stream"); + } + + try { + using (BZip2InputStream bzipInput = new BZip2InputStream(inStream)) { + bzipInput.IsStreamOwner = isStreamOwner; + Core.StreamUtils.Copy(bzipInput, outStream, new byte[4096]); + } + } finally { + if (isStreamOwner) { + // inStream is closed by the BZip2InputStream if stream owner + outStream.Close(); + } + } + } + + /// + /// Compress the input stream sending + /// result data to output stream + /// + /// The readable stream to compress. + /// The output stream to receive the compressed data. + /// Both streams are closed on completion if true. + /// Block size acts as compression level (1 to 9) with 1 giving + /// the lowest compression and 9 the highest. + public static void Compress(Stream inStream, Stream outStream, bool isStreamOwner, int level) + { + if (inStream == null || outStream == null) { + throw new Exception("Null Stream"); + } - try { - using (BZip2OutputStream bzipOutput = new BZip2OutputStream(outStream, level)) { - bzipOutput.IsStreamOwner = isStreamOwner; - Core.StreamUtils.Copy(inStream, bzipOutput, new byte[4096]); - } - } finally { - if (isStreamOwner) { - // outStream is closed by the BZip2OutputStream if stream owner - inStream.Close(); - } - } - } + try { + using (BZip2OutputStream bzipOutput = new BZip2OutputStream(outStream, level)) { + bzipOutput.IsStreamOwner = isStreamOwner; + Core.StreamUtils.Copy(inStream, bzipOutput, new byte[4096]); + } + } finally { + if (isStreamOwner) { + // outStream is closed by the BZip2OutputStream if stream owner + inStream.Close(); + } + } + } - } + } } #endif diff --git a/External/Tools/AppMan/ZipLib/BZip2/BZip2Constants.cs b/External/Tools/AppMan/ZipLib/BZip2/BZip2Constants.cs index ad3f40d77f..c4cd15c5c2 100644 --- a/External/Tools/AppMan/ZipLib/BZip2/BZip2Constants.cs +++ b/External/Tools/AppMan/ZipLib/BZip2/BZip2Constants.cs @@ -34,127 +34,127 @@ namespace ICSharpCode.SharpZipLib.BZip2 { - - /// - /// Defines internal values for both compression and decompression - /// - internal sealed class BZip2Constants - { - /// - /// Random numbers used to randomise repetitive blocks - /// - public readonly static int[] RandomNumbers = { - 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, - 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, - 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, - 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, - 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, - 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, - 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, - 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, - 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, - 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, - 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, - 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, - 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, - 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, - 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, - 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, - 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, - 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, - 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, - 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, - 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, - 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, - 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, - 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, - 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, - 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, - 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, - 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, - 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, - 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, - 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, - 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, - 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, - 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, - 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, - 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, - 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, - 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, - 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, - 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, - 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, - 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, - 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, - 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, - 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, - 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, - 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, - 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, - 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, - 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, - 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, - 936, 638 - }; + + /// + /// Defines internal values for both compression and decompression + /// + internal sealed class BZip2Constants + { + /// + /// Random numbers used to randomise repetitive blocks + /// + public readonly static int[] RandomNumbers = { + 619, 720, 127, 481, 931, 816, 813, 233, 566, 247, + 985, 724, 205, 454, 863, 491, 741, 242, 949, 214, + 733, 859, 335, 708, 621, 574, 73, 654, 730, 472, + 419, 436, 278, 496, 867, 210, 399, 680, 480, 51, + 878, 465, 811, 169, 869, 675, 611, 697, 867, 561, + 862, 687, 507, 283, 482, 129, 807, 591, 733, 623, + 150, 238, 59, 379, 684, 877, 625, 169, 643, 105, + 170, 607, 520, 932, 727, 476, 693, 425, 174, 647, + 73, 122, 335, 530, 442, 853, 695, 249, 445, 515, + 909, 545, 703, 919, 874, 474, 882, 500, 594, 612, + 641, 801, 220, 162, 819, 984, 589, 513, 495, 799, + 161, 604, 958, 533, 221, 400, 386, 867, 600, 782, + 382, 596, 414, 171, 516, 375, 682, 485, 911, 276, + 98, 553, 163, 354, 666, 933, 424, 341, 533, 870, + 227, 730, 475, 186, 263, 647, 537, 686, 600, 224, + 469, 68, 770, 919, 190, 373, 294, 822, 808, 206, + 184, 943, 795, 384, 383, 461, 404, 758, 839, 887, + 715, 67, 618, 276, 204, 918, 873, 777, 604, 560, + 951, 160, 578, 722, 79, 804, 96, 409, 713, 940, + 652, 934, 970, 447, 318, 353, 859, 672, 112, 785, + 645, 863, 803, 350, 139, 93, 354, 99, 820, 908, + 609, 772, 154, 274, 580, 184, 79, 626, 630, 742, + 653, 282, 762, 623, 680, 81, 927, 626, 789, 125, + 411, 521, 938, 300, 821, 78, 343, 175, 128, 250, + 170, 774, 972, 275, 999, 639, 495, 78, 352, 126, + 857, 956, 358, 619, 580, 124, 737, 594, 701, 612, + 669, 112, 134, 694, 363, 992, 809, 743, 168, 974, + 944, 375, 748, 52, 600, 747, 642, 182, 862, 81, + 344, 805, 988, 739, 511, 655, 814, 334, 249, 515, + 897, 955, 664, 981, 649, 113, 974, 459, 893, 228, + 433, 837, 553, 268, 926, 240, 102, 654, 459, 51, + 686, 754, 806, 760, 493, 403, 415, 394, 687, 700, + 946, 670, 656, 610, 738, 392, 760, 799, 887, 653, + 978, 321, 576, 617, 626, 502, 894, 679, 243, 440, + 680, 879, 194, 572, 640, 724, 926, 56, 204, 700, + 707, 151, 457, 449, 797, 195, 791, 558, 945, 679, + 297, 59, 87, 824, 713, 663, 412, 693, 342, 606, + 134, 108, 571, 364, 631, 212, 174, 643, 304, 329, + 343, 97, 430, 751, 497, 314, 983, 374, 822, 928, + 140, 206, 73, 263, 980, 736, 876, 478, 430, 305, + 170, 514, 364, 692, 829, 82, 855, 953, 676, 246, + 369, 970, 294, 750, 807, 827, 150, 790, 288, 923, + 804, 378, 215, 828, 592, 281, 565, 555, 710, 82, + 896, 831, 547, 261, 524, 462, 293, 465, 502, 56, + 661, 821, 976, 991, 658, 869, 905, 758, 745, 193, + 768, 550, 608, 933, 378, 286, 215, 979, 792, 961, + 61, 688, 793, 644, 986, 403, 106, 366, 905, 644, + 372, 567, 466, 434, 645, 210, 389, 550, 919, 135, + 780, 773, 635, 389, 707, 100, 626, 958, 165, 504, + 920, 176, 193, 713, 857, 265, 203, 50, 668, 108, + 645, 990, 626, 197, 510, 357, 358, 850, 858, 364, + 936, 638 + }; - /// - /// When multiplied by compression parameter (1-9) gives the block size for compression - /// 9 gives the best compression but uses the most memory. - /// - public const int BaseBlockSize = 100000; - - /// - /// Backend constant - /// - public const int MaximumAlphaSize = 258; - - /// - /// Backend constant - /// - public const int MaximumCodeLength = 23; - - /// - /// Backend constant - /// - public const int RunA = 0; - - /// - /// Backend constant - /// - public const int RunB = 1; - - /// - /// Backend constant - /// - public const int GroupCount = 6; - - /// - /// Backend constant - /// - public const int GroupSize = 50; - - /// - /// Backend constant - /// - public const int NumberOfIterations = 4; - - /// - /// Backend constant - /// - public const int MaximumSelectors = (2 + (900000 / GroupSize)); - - /// - /// Backend constant - /// - public const int OvershootBytes = 20; - - private BZip2Constants() - { - } - } + /// + /// When multiplied by compression parameter (1-9) gives the block size for compression + /// 9 gives the best compression but uses the most memory. + /// + public const int BaseBlockSize = 100000; + + /// + /// Backend constant + /// + public const int MaximumAlphaSize = 258; + + /// + /// Backend constant + /// + public const int MaximumCodeLength = 23; + + /// + /// Backend constant + /// + public const int RunA = 0; + + /// + /// Backend constant + /// + public const int RunB = 1; + + /// + /// Backend constant + /// + public const int GroupCount = 6; + + /// + /// Backend constant + /// + public const int GroupSize = 50; + + /// + /// Backend constant + /// + public const int NumberOfIterations = 4; + + /// + /// Backend constant + /// + public const int MaximumSelectors = (2 + (900000 / GroupSize)); + + /// + /// Backend constant + /// + public const int OvershootBytes = 20; + + private BZip2Constants() + { + } + } } - + /* This file was derived from a file containing this license: * * This file is a part of bzip2 and/or libbzip2, a program and diff --git a/External/Tools/AppMan/ZipLib/BZip2/BZip2Exception.cs b/External/Tools/AppMan/ZipLib/BZip2/BZip2Exception.cs index 3b7c8ffe54..09bccbb7af 100644 --- a/External/Tools/AppMan/ZipLib/BZip2/BZip2Exception.cs +++ b/External/Tools/AppMan/ZipLib/BZip2/BZip2Exception.cs @@ -41,50 +41,50 @@ namespace ICSharpCode.SharpZipLib.BZip2 { - /// - /// BZip2Exception represents exceptions specific to Bzip2 algorithm - /// + /// + /// BZip2Exception represents exceptions specific to Bzip2 algorithm + /// #if !NETCF_1_0 && !NETCF_2_0 - [Serializable] -#endif - public class BZip2Exception : SharpZipBaseException - { + [Serializable] +#endif + public class BZip2Exception : SharpZipBaseException + { #if !NETCF_1_0 && !NETCF_2_0 - /// - /// Deserialization constructor - /// - /// for this constructor - /// for this constructor - protected BZip2Exception(SerializationInfo info, StreamingContext context) - : base(info, context) + /// + /// Deserialization constructor + /// + /// for this constructor + /// for this constructor + protected BZip2Exception(SerializationInfo info, StreamingContext context) + : base(info, context) - { - } + { + } #endif - /// - /// Initialise a new instance of BZip2Exception. - /// - public BZip2Exception() - { - } - - /// - /// Initialise a new instance of BZip2Exception with its message set to message. - /// - /// The message describing the error. - public BZip2Exception(string message) : base(message) - { - } + /// + /// Initialise a new instance of BZip2Exception. + /// + public BZip2Exception() + { + } + + /// + /// Initialise a new instance of BZip2Exception with its message set to message. + /// + /// The message describing the error. + public BZip2Exception(string message) : base(message) + { + } - /// - /// Initialise an instance of BZip2Exception - /// - /// A message describing the error. - /// The exception that is the cause of the current exception. - public BZip2Exception(string message, Exception exception) - : base(message, exception) - { - } - } + /// + /// Initialise an instance of BZip2Exception + /// + /// A message describing the error. + /// The exception that is the cause of the current exception. + public BZip2Exception(string message, Exception exception) + : base(message, exception) + { + } + } } diff --git a/External/Tools/AppMan/ZipLib/BZip2/BZip2InputStream.cs b/External/Tools/AppMan/ZipLib/BZip2/BZip2InputStream.cs index 162c9d0123..94e65daf08 100644 --- a/External/Tools/AppMan/ZipLib/BZip2/BZip2InputStream.cs +++ b/External/Tools/AppMan/ZipLib/BZip2/BZip2InputStream.cs @@ -40,926 +40,926 @@ namespace ICSharpCode.SharpZipLib.BZip2 { - - /// - /// An input stream that decompresses files in the BZip2 format - /// - public class BZip2InputStream : Stream - { - #region Constants - const int START_BLOCK_STATE = 1; - const int RAND_PART_A_STATE = 2; - const int RAND_PART_B_STATE = 3; - const int RAND_PART_C_STATE = 4; - const int NO_RAND_PART_A_STATE = 5; - const int NO_RAND_PART_B_STATE = 6; - const int NO_RAND_PART_C_STATE = 7; - #endregion - #region Constructors - /// - /// Construct instance for reading from stream - /// - /// Data source - public BZip2InputStream(Stream stream) - { - // init arrays - for (int i = 0; i < BZip2Constants.GroupCount; ++i) - { - limit[i] = new int[BZip2Constants.MaximumAlphaSize]; - baseArray[i] = new int[BZip2Constants.MaximumAlphaSize]; - perm[i] = new int[BZip2Constants.MaximumAlphaSize]; - } - - BsSetStream(stream); - Initialize(); - InitBlock(); - SetupBlock(); - } - - #endregion + + /// + /// An input stream that decompresses files in the BZip2 format + /// + public class BZip2InputStream : Stream + { + #region Constants + const int START_BLOCK_STATE = 1; + const int RAND_PART_A_STATE = 2; + const int RAND_PART_B_STATE = 3; + const int RAND_PART_C_STATE = 4; + const int NO_RAND_PART_A_STATE = 5; + const int NO_RAND_PART_B_STATE = 6; + const int NO_RAND_PART_C_STATE = 7; + #endregion + #region Constructors + /// + /// Construct instance for reading from stream + /// + /// Data source + public BZip2InputStream(Stream stream) + { + // init arrays + for (int i = 0; i < BZip2Constants.GroupCount; ++i) + { + limit[i] = new int[BZip2Constants.MaximumAlphaSize]; + baseArray[i] = new int[BZip2Constants.MaximumAlphaSize]; + perm[i] = new int[BZip2Constants.MaximumAlphaSize]; + } + + BsSetStream(stream); + Initialize(); + InitBlock(); + SetupBlock(); + } + + #endregion - /// - /// Get/set flag indicating ownership of underlying stream. - /// When the flag is true will close the underlying stream also. - /// - public bool IsStreamOwner - { - get { return isStreamOwner; } - set { isStreamOwner = value; } - } - + /// + /// Get/set flag indicating ownership of underlying stream. + /// When the flag is true will close the underlying stream also. + /// + public bool IsStreamOwner + { + get { return isStreamOwner; } + set { isStreamOwner = value; } + } + - #region Stream Overrides - /// - /// Gets a value indicating if the stream supports reading - /// - public override bool CanRead - { - get { - return baseStream.CanRead; - } - } - - /// - /// Gets a value indicating whether the current stream supports seeking. - /// - public override bool CanSeek { - get { - return baseStream.CanSeek; - } - } - - /// - /// Gets a value indicating whether the current stream supports writing. - /// This property always returns false - /// - public override bool CanWrite { - get { - return false; - } - } - - /// - /// Gets the length in bytes of the stream. - /// - public override long Length { - get { - return baseStream.Length; - } - } - - /// - /// Gets or sets the streams position. - /// Setting the position is not supported and will throw a NotSupportException - /// - /// Any attempt to set the position - public override long Position { - get { - return baseStream.Position; - } - set { - throw new NotSupportedException("BZip2InputStream position cannot be set"); - } - } - - /// - /// Flushes the stream. - /// - public override void Flush() - { - if (baseStream != null) { - baseStream.Flush(); - } - } - - /// - /// Set the streams position. This operation is not supported and will throw a NotSupportedException - /// - /// A byte offset relative to the parameter. - /// A value of type indicating the reference point used to obtain the new position. - /// The new position of the stream. - /// Any access - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException("BZip2InputStream Seek not supported"); - } - - /// - /// Sets the length of this stream to the given value. - /// This operation is not supported and will throw a NotSupportedExceptionortedException - /// - /// The new length for the stream. - /// Any access - public override void SetLength(long value) - { - throw new NotSupportedException("BZip2InputStream SetLength not supported"); - } - - /// - /// Writes a block of bytes to this stream using data from a buffer. - /// This operation is not supported and will throw a NotSupportedException - /// - /// The buffer to source data from. - /// The offset to start obtaining data from. - /// The number of bytes of data to write. - /// Any access - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotSupportedException("BZip2InputStream Write not supported"); - } - - /// - /// Writes a byte to the current position in the file stream. - /// This operation is not supported and will throw a NotSupportedException - /// - /// The value to write. - /// Any access - public override void WriteByte(byte value) - { - throw new NotSupportedException("BZip2InputStream WriteByte not supported"); - } - - /// - /// Read a sequence of bytes and advances the read position by one byte. - /// - /// Array of bytes to store values in - /// Offset in array to begin storing data - /// The maximum number of bytes to read - /// The total number of bytes read into the buffer. This might be less - /// than the number of bytes requested if that number of bytes are not - /// currently available or zero if the end of the stream is reached. - /// - public override int Read(byte[] buffer, int offset, int count) - { - if ( buffer == null ) - { - throw new ArgumentNullException("buffer"); - } + #region Stream Overrides + /// + /// Gets a value indicating if the stream supports reading + /// + public override bool CanRead + { + get { + return baseStream.CanRead; + } + } + + /// + /// Gets a value indicating whether the current stream supports seeking. + /// + public override bool CanSeek { + get { + return baseStream.CanSeek; + } + } + + /// + /// Gets a value indicating whether the current stream supports writing. + /// This property always returns false + /// + public override bool CanWrite { + get { + return false; + } + } + + /// + /// Gets the length in bytes of the stream. + /// + public override long Length { + get { + return baseStream.Length; + } + } + + /// + /// Gets or sets the streams position. + /// Setting the position is not supported and will throw a NotSupportException + /// + /// Any attempt to set the position + public override long Position { + get { + return baseStream.Position; + } + set { + throw new NotSupportedException("BZip2InputStream position cannot be set"); + } + } + + /// + /// Flushes the stream. + /// + public override void Flush() + { + if (baseStream != null) { + baseStream.Flush(); + } + } + + /// + /// Set the streams position. This operation is not supported and will throw a NotSupportedException + /// + /// A byte offset relative to the parameter. + /// A value of type indicating the reference point used to obtain the new position. + /// The new position of the stream. + /// Any access + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException("BZip2InputStream Seek not supported"); + } + + /// + /// Sets the length of this stream to the given value. + /// This operation is not supported and will throw a NotSupportedExceptionortedException + /// + /// The new length for the stream. + /// Any access + public override void SetLength(long value) + { + throw new NotSupportedException("BZip2InputStream SetLength not supported"); + } + + /// + /// Writes a block of bytes to this stream using data from a buffer. + /// This operation is not supported and will throw a NotSupportedException + /// + /// The buffer to source data from. + /// The offset to start obtaining data from. + /// The number of bytes of data to write. + /// Any access + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException("BZip2InputStream Write not supported"); + } + + /// + /// Writes a byte to the current position in the file stream. + /// This operation is not supported and will throw a NotSupportedException + /// + /// The value to write. + /// Any access + public override void WriteByte(byte value) + { + throw new NotSupportedException("BZip2InputStream WriteByte not supported"); + } + + /// + /// Read a sequence of bytes and advances the read position by one byte. + /// + /// Array of bytes to store values in + /// Offset in array to begin storing data + /// The maximum number of bytes to read + /// The total number of bytes read into the buffer. This might be less + /// than the number of bytes requested if that number of bytes are not + /// currently available or zero if the end of the stream is reached. + /// + public override int Read(byte[] buffer, int offset, int count) + { + if ( buffer == null ) + { + throw new ArgumentNullException("buffer"); + } - for (int i = 0; i < count; ++i) { - int rb = ReadByte(); - if (rb == -1) { - return i; - } - buffer[offset + i] = (byte)rb; - } - return count; - } - - /// - /// Closes the stream, releasing any associated resources. - /// - public override void Close() - { - if ( IsStreamOwner && (baseStream != null) ) { - baseStream.Close(); - } - } - /// - /// Read a byte from stream advancing position - /// - /// byte read or -1 on end of stream - public override int ReadByte() - { - if (streamEnd) - { - return -1; // ok - } - - int retChar = currentChar; - switch (currentState) - { - case RAND_PART_B_STATE: - SetupRandPartB(); - break; - case RAND_PART_C_STATE: - SetupRandPartC(); - break; - case NO_RAND_PART_B_STATE: - SetupNoRandPartB(); - break; - case NO_RAND_PART_C_STATE: - SetupNoRandPartC(); - break; - case START_BLOCK_STATE: - case NO_RAND_PART_A_STATE: - case RAND_PART_A_STATE: - break; - default: - break; - } - return retChar; - } - - #endregion + for (int i = 0; i < count; ++i) { + int rb = ReadByte(); + if (rb == -1) { + return i; + } + buffer[offset + i] = (byte)rb; + } + return count; + } + + /// + /// Closes the stream, releasing any associated resources. + /// + public override void Close() + { + if ( IsStreamOwner && (baseStream != null) ) { + baseStream.Close(); + } + } + /// + /// Read a byte from stream advancing position + /// + /// byte read or -1 on end of stream + public override int ReadByte() + { + if (streamEnd) + { + return -1; // ok + } + + int retChar = currentChar; + switch (currentState) + { + case RAND_PART_B_STATE: + SetupRandPartB(); + break; + case RAND_PART_C_STATE: + SetupRandPartC(); + break; + case NO_RAND_PART_B_STATE: + SetupNoRandPartB(); + break; + case NO_RAND_PART_C_STATE: + SetupNoRandPartC(); + break; + case START_BLOCK_STATE: + case NO_RAND_PART_A_STATE: + case RAND_PART_A_STATE: + break; + default: + break; + } + return retChar; + } + + #endregion - void MakeMaps() - { - nInUse = 0; - for (int i = 0; i < 256; ++i) { - if (inUse[i]) { - seqToUnseq[nInUse] = (byte)i; - unseqToSeq[i] = (byte)nInUse; - nInUse++; - } - } - } - - void Initialize() - { - char magic1 = BsGetUChar(); - char magic2 = BsGetUChar(); - - char magic3 = BsGetUChar(); - char magic4 = BsGetUChar(); - - if (magic1 != 'B' || magic2 != 'Z' || magic3 != 'h' || magic4 < '1' || magic4 > '9') { - streamEnd = true; - return; - } - - SetDecompressStructureSizes(magic4 - '0'); - computedCombinedCRC = 0; - } - - void InitBlock() - { - char magic1 = BsGetUChar(); - char magic2 = BsGetUChar(); - char magic3 = BsGetUChar(); - char magic4 = BsGetUChar(); - char magic5 = BsGetUChar(); - char magic6 = BsGetUChar(); - - if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) { - Complete(); - return; - } - - if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) { - BadBlockHeader(); - streamEnd = true; - return; - } - - storedBlockCRC = BsGetInt32(); - - blockRandomised = (BsR(1) == 1); - - GetAndMoveToFrontDecode(); - - mCrc.Reset(); - currentState = START_BLOCK_STATE; - } - - void EndBlock() - { - computedBlockCRC = (int)mCrc.Value; - - // -- A bad CRC is considered a fatal error. -- - if (storedBlockCRC != computedBlockCRC) { - CrcError(); - } - - // 1528150659 - computedCombinedCRC = ((computedCombinedCRC << 1) & 0xFFFFFFFF) | (computedCombinedCRC >> 31); - computedCombinedCRC = computedCombinedCRC ^ (uint)computedBlockCRC; - } - - void Complete() - { - storedCombinedCRC = BsGetInt32(); - if (storedCombinedCRC != (int)computedCombinedCRC) { - CrcError(); - } - - streamEnd = true; - } - - void BsSetStream(Stream stream) - { - baseStream = stream; - bsLive = 0; - bsBuff = 0; - } - - void FillBuffer() - { - int thech = 0; - - try { - thech = baseStream.ReadByte(); - } catch (Exception) { - CompressedStreamEOF(); - } - - if (thech == -1) { - CompressedStreamEOF(); - } - - bsBuff = (bsBuff << 8) | (thech & 0xFF); - bsLive += 8; - } - - int BsR(int n) - { - while (bsLive < n) { - FillBuffer(); - } - - int v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1); - bsLive -= n; - return v; - } - - char BsGetUChar() - { - return (char)BsR(8); - } - - int BsGetIntVS(int numBits) - { - return BsR(numBits); - } - - int BsGetInt32() - { - int result = BsR(8); - result = (result << 8) | BsR(8); - result = (result << 8) | BsR(8); - result = (result << 8) | BsR(8); - return result; - } - - void RecvDecodingTables() - { - char[][] len = new char[BZip2Constants.GroupCount][]; - for (int i = 0; i < BZip2Constants.GroupCount; ++i) { - len[i] = new char[BZip2Constants.MaximumAlphaSize]; - } - - bool[] inUse16 = new bool[16]; - - //--- Receive the mapping table --- - for (int i = 0; i < 16; i++) { - inUse16[i] = (BsR(1) == 1); - } - - for (int i = 0; i < 16; i++) { - if (inUse16[i]) { - for (int j = 0; j < 16; j++) { - inUse[i * 16 + j] = (BsR(1) == 1); - } - } else { - for (int j = 0; j < 16; j++) { - inUse[i * 16 + j] = false; - } - } - } - - MakeMaps(); - int alphaSize = nInUse + 2; - - //--- Now the selectors --- - int nGroups = BsR(3); - int nSelectors = BsR(15); - - for (int i = 0; i < nSelectors; i++) { - int j = 0; - while (BsR(1) == 1) { - j++; - } - selectorMtf[i] = (byte)j; - } - - //--- Undo the MTF values for the selectors. --- - byte[] pos = new byte[BZip2Constants.GroupCount]; - for (int v = 0; v < nGroups; v++) { - pos[v] = (byte)v; - } - - for (int i = 0; i < nSelectors; i++) { - int v = selectorMtf[i]; - byte tmp = pos[v]; - while (v > 0) { - pos[v] = pos[v - 1]; - v--; - } - pos[0] = tmp; - selector[i] = tmp; - } - - //--- Now the coding tables --- - for (int t = 0; t < nGroups; t++) { - int curr = BsR(5); - for (int i = 0; i < alphaSize; i++) { - while (BsR(1) == 1) { - if (BsR(1) == 0) { - curr++; - } else { - curr--; - } - } - len[t][i] = (char)curr; - } - } - - //--- Create the Huffman decoding tables --- - for (int t = 0; t < nGroups; t++) { - int minLen = 32; - int maxLen = 0; - for (int i = 0; i < alphaSize; i++) { - maxLen = Math.Max(maxLen, len[t][i]); - minLen = Math.Min(minLen, len[t][i]); - } - HbCreateDecodeTables(limit[t], baseArray[t], perm[t], len[t], minLen, maxLen, alphaSize); - minLens[t] = minLen; - } - } - - void GetAndMoveToFrontDecode() - { - byte[] yy = new byte[256]; - int nextSym; - - int limitLast = BZip2Constants.BaseBlockSize * blockSize100k; - origPtr = BsGetIntVS(24); - - RecvDecodingTables(); - int EOB = nInUse+1; - int groupNo = -1; - int groupPos = 0; - - /*-- - Setting up the unzftab entries here is not strictly - necessary, but it does save having to do it later - in a separate pass, and so saves a block's worth of - cache misses. - --*/ - for (int i = 0; i <= 255; i++) { - unzftab[i] = 0; - } - - for (int i = 0; i <= 255; i++) { - yy[i] = (byte)i; - } - - last = -1; - - if (groupPos == 0) { - groupNo++; - groupPos = BZip2Constants.GroupSize; - } - - groupPos--; - int zt = selector[groupNo]; - int zn = minLens[zt]; - int zvec = BsR(zn); - int zj; - - while (zvec > limit[zt][zn]) { - if (zn > 20) { // the longest code - throw new BZip2Exception("Bzip data error"); - } - zn++; - while (bsLive < 1) { - FillBuffer(); - } - zj = (bsBuff >> (bsLive-1)) & 1; - bsLive--; - zvec = (zvec << 1) | zj; - } - if (zvec - baseArray[zt][zn] < 0 || zvec - baseArray[zt][zn] >= BZip2Constants.MaximumAlphaSize) { - throw new BZip2Exception("Bzip data error"); - } - nextSym = perm[zt][zvec - baseArray[zt][zn]]; - - while (true) { - if (nextSym == EOB) { - break; - } - - if (nextSym == BZip2Constants.RunA || nextSym == BZip2Constants.RunB) { - int s = -1; - int n = 1; - do { - if (nextSym == BZip2Constants.RunA) { - s += (0 + 1) * n; - } else if (nextSym == BZip2Constants.RunB) { - s += (1 + 1) * n; - } + void MakeMaps() + { + nInUse = 0; + for (int i = 0; i < 256; ++i) { + if (inUse[i]) { + seqToUnseq[nInUse] = (byte)i; + unseqToSeq[i] = (byte)nInUse; + nInUse++; + } + } + } + + void Initialize() + { + char magic1 = BsGetUChar(); + char magic2 = BsGetUChar(); + + char magic3 = BsGetUChar(); + char magic4 = BsGetUChar(); + + if (magic1 != 'B' || magic2 != 'Z' || magic3 != 'h' || magic4 < '1' || magic4 > '9') { + streamEnd = true; + return; + } + + SetDecompressStructureSizes(magic4 - '0'); + computedCombinedCRC = 0; + } + + void InitBlock() + { + char magic1 = BsGetUChar(); + char magic2 = BsGetUChar(); + char magic3 = BsGetUChar(); + char magic4 = BsGetUChar(); + char magic5 = BsGetUChar(); + char magic6 = BsGetUChar(); + + if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 && magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90) { + Complete(); + return; + } + + if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 || magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59) { + BadBlockHeader(); + streamEnd = true; + return; + } + + storedBlockCRC = BsGetInt32(); + + blockRandomised = (BsR(1) == 1); + + GetAndMoveToFrontDecode(); + + mCrc.Reset(); + currentState = START_BLOCK_STATE; + } + + void EndBlock() + { + computedBlockCRC = (int)mCrc.Value; + + // -- A bad CRC is considered a fatal error. -- + if (storedBlockCRC != computedBlockCRC) { + CrcError(); + } + + // 1528150659 + computedCombinedCRC = ((computedCombinedCRC << 1) & 0xFFFFFFFF) | (computedCombinedCRC >> 31); + computedCombinedCRC = computedCombinedCRC ^ (uint)computedBlockCRC; + } + + void Complete() + { + storedCombinedCRC = BsGetInt32(); + if (storedCombinedCRC != (int)computedCombinedCRC) { + CrcError(); + } + + streamEnd = true; + } + + void BsSetStream(Stream stream) + { + baseStream = stream; + bsLive = 0; + bsBuff = 0; + } + + void FillBuffer() + { + int thech = 0; + + try { + thech = baseStream.ReadByte(); + } catch (Exception) { + CompressedStreamEOF(); + } + + if (thech == -1) { + CompressedStreamEOF(); + } + + bsBuff = (bsBuff << 8) | (thech & 0xFF); + bsLive += 8; + } + + int BsR(int n) + { + while (bsLive < n) { + FillBuffer(); + } + + int v = (bsBuff >> (bsLive - n)) & ((1 << n) - 1); + bsLive -= n; + return v; + } + + char BsGetUChar() + { + return (char)BsR(8); + } + + int BsGetIntVS(int numBits) + { + return BsR(numBits); + } + + int BsGetInt32() + { + int result = BsR(8); + result = (result << 8) | BsR(8); + result = (result << 8) | BsR(8); + result = (result << 8) | BsR(8); + return result; + } + + void RecvDecodingTables() + { + char[][] len = new char[BZip2Constants.GroupCount][]; + for (int i = 0; i < BZip2Constants.GroupCount; ++i) { + len[i] = new char[BZip2Constants.MaximumAlphaSize]; + } + + bool[] inUse16 = new bool[16]; + + //--- Receive the mapping table --- + for (int i = 0; i < 16; i++) { + inUse16[i] = (BsR(1) == 1); + } + + for (int i = 0; i < 16; i++) { + if (inUse16[i]) { + for (int j = 0; j < 16; j++) { + inUse[i * 16 + j] = (BsR(1) == 1); + } + } else { + for (int j = 0; j < 16; j++) { + inUse[i * 16 + j] = false; + } + } + } + + MakeMaps(); + int alphaSize = nInUse + 2; + + //--- Now the selectors --- + int nGroups = BsR(3); + int nSelectors = BsR(15); + + for (int i = 0; i < nSelectors; i++) { + int j = 0; + while (BsR(1) == 1) { + j++; + } + selectorMtf[i] = (byte)j; + } + + //--- Undo the MTF values for the selectors. --- + byte[] pos = new byte[BZip2Constants.GroupCount]; + for (int v = 0; v < nGroups; v++) { + pos[v] = (byte)v; + } + + for (int i = 0; i < nSelectors; i++) { + int v = selectorMtf[i]; + byte tmp = pos[v]; + while (v > 0) { + pos[v] = pos[v - 1]; + v--; + } + pos[0] = tmp; + selector[i] = tmp; + } + + //--- Now the coding tables --- + for (int t = 0; t < nGroups; t++) { + int curr = BsR(5); + for (int i = 0; i < alphaSize; i++) { + while (BsR(1) == 1) { + if (BsR(1) == 0) { + curr++; + } else { + curr--; + } + } + len[t][i] = (char)curr; + } + } + + //--- Create the Huffman decoding tables --- + for (int t = 0; t < nGroups; t++) { + int minLen = 32; + int maxLen = 0; + for (int i = 0; i < alphaSize; i++) { + maxLen = Math.Max(maxLen, len[t][i]); + minLen = Math.Min(minLen, len[t][i]); + } + HbCreateDecodeTables(limit[t], baseArray[t], perm[t], len[t], minLen, maxLen, alphaSize); + minLens[t] = minLen; + } + } + + void GetAndMoveToFrontDecode() + { + byte[] yy = new byte[256]; + int nextSym; + + int limitLast = BZip2Constants.BaseBlockSize * blockSize100k; + origPtr = BsGetIntVS(24); + + RecvDecodingTables(); + int EOB = nInUse+1; + int groupNo = -1; + int groupPos = 0; + + /*-- + Setting up the unzftab entries here is not strictly + necessary, but it does save having to do it later + in a separate pass, and so saves a block's worth of + cache misses. + --*/ + for (int i = 0; i <= 255; i++) { + unzftab[i] = 0; + } + + for (int i = 0; i <= 255; i++) { + yy[i] = (byte)i; + } + + last = -1; + + if (groupPos == 0) { + groupNo++; + groupPos = BZip2Constants.GroupSize; + } + + groupPos--; + int zt = selector[groupNo]; + int zn = minLens[zt]; + int zvec = BsR(zn); + int zj; + + while (zvec > limit[zt][zn]) { + if (zn > 20) { // the longest code + throw new BZip2Exception("Bzip data error"); + } + zn++; + while (bsLive < 1) { + FillBuffer(); + } + zj = (bsBuff >> (bsLive-1)) & 1; + bsLive--; + zvec = (zvec << 1) | zj; + } + if (zvec - baseArray[zt][zn] < 0 || zvec - baseArray[zt][zn] >= BZip2Constants.MaximumAlphaSize) { + throw new BZip2Exception("Bzip data error"); + } + nextSym = perm[zt][zvec - baseArray[zt][zn]]; + + while (true) { + if (nextSym == EOB) { + break; + } + + if (nextSym == BZip2Constants.RunA || nextSym == BZip2Constants.RunB) { + int s = -1; + int n = 1; + do { + if (nextSym == BZip2Constants.RunA) { + s += (0 + 1) * n; + } else if (nextSym == BZip2Constants.RunB) { + s += (1 + 1) * n; + } - n <<= 1; - - if (groupPos == 0) { - groupNo++; - groupPos = BZip2Constants.GroupSize; - } - - groupPos--; - - zt = selector[groupNo]; - zn = minLens[zt]; - zvec = BsR(zn); - - while (zvec > limit[zt][zn]) { - zn++; - while (bsLive < 1) { - FillBuffer(); - } - zj = (bsBuff >> (bsLive - 1)) & 1; - bsLive--; - zvec = (zvec << 1) | zj; - } - nextSym = perm[zt][zvec - baseArray[zt][zn]]; - } while (nextSym == BZip2Constants.RunA || nextSym == BZip2Constants.RunB); - - s++; - byte ch = seqToUnseq[yy[0]]; - unzftab[ch] += s; - - while (s > 0) { - last++; - ll8[last] = ch; - s--; - } - - if (last >= limitLast) { - BlockOverrun(); - } - continue; - } else { - last++; - if (last >= limitLast) { - BlockOverrun(); - } - - byte tmp = yy[nextSym - 1]; - unzftab[seqToUnseq[tmp]]++; - ll8[last] = seqToUnseq[tmp]; - - for (int j = nextSym-1; j > 0; --j) { - yy[j] = yy[j - 1]; - } - yy[0] = tmp; - - if (groupPos == 0) { - groupNo++; - groupPos = BZip2Constants.GroupSize; - } - - groupPos--; - zt = selector[groupNo]; - zn = minLens[zt]; - zvec = BsR(zn); - while (zvec > limit[zt][zn]) { - zn++; - while (bsLive < 1) { - FillBuffer(); - } - zj = (bsBuff >> (bsLive-1)) & 1; - bsLive--; - zvec = (zvec << 1) | zj; - } - nextSym = perm[zt][zvec - baseArray[zt][zn]]; - continue; - } - } - } - - void SetupBlock() - { - int[] cftab = new int[257]; - - cftab[0] = 0; - Array.Copy(unzftab, 0, cftab, 1, 256); - - for (int i = 1; i <= 256; i++) { - cftab[i] += cftab[i - 1]; - } - - for (int i = 0; i <= last; i++) { - byte ch = ll8[i]; - tt[cftab[ch]] = i; - cftab[ch]++; - } - - cftab = null; - - tPos = tt[origPtr]; - - count = 0; - i2 = 0; - ch2 = 256; /*-- not a char and not EOF --*/ - - if (blockRandomised) { - rNToGo = 0; - rTPos = 0; - SetupRandPartA(); - } else { - SetupNoRandPartA(); - } - } - - void SetupRandPartA() - { - if (i2 <= last) { - chPrev = ch2; - ch2 = ll8[tPos]; - tPos = tt[tPos]; - if (rNToGo == 0) { - rNToGo = BZip2Constants.RandomNumbers[rTPos]; - rTPos++; - if (rTPos == 512) { - rTPos = 0; - } - } - rNToGo--; - ch2 ^= (int)((rNToGo == 1) ? 1 : 0); - i2++; - - currentChar = ch2; - currentState = RAND_PART_B_STATE; - mCrc.Update(ch2); - } else { - EndBlock(); - InitBlock(); - SetupBlock(); - } - } - - void SetupNoRandPartA() - { - if (i2 <= last) { - chPrev = ch2; - ch2 = ll8[tPos]; - tPos = tt[tPos]; - i2++; - - currentChar = ch2; - currentState = NO_RAND_PART_B_STATE; - mCrc.Update(ch2); - } else { - EndBlock(); - InitBlock(); - SetupBlock(); - } - } - - void SetupRandPartB() - { - if (ch2 != chPrev) { - currentState = RAND_PART_A_STATE; - count = 1; - SetupRandPartA(); - } else { - count++; - if (count >= 4) { - z = ll8[tPos]; - tPos = tt[tPos]; - if (rNToGo == 0) { - rNToGo = BZip2Constants.RandomNumbers[rTPos]; - rTPos++; - if (rTPos == 512) { - rTPos = 0; - } - } - rNToGo--; - z ^= (byte)((rNToGo == 1) ? 1 : 0); - j2 = 0; - currentState = RAND_PART_C_STATE; - SetupRandPartC(); - } else { - currentState = RAND_PART_A_STATE; - SetupRandPartA(); - } - } - } - - void SetupRandPartC() - { - if (j2 < (int)z) { - currentChar = ch2; - mCrc.Update(ch2); - j2++; - } else { - currentState = RAND_PART_A_STATE; - i2++; - count = 0; - SetupRandPartA(); - } - } - - void SetupNoRandPartB() - { - if (ch2 != chPrev) { - currentState = NO_RAND_PART_A_STATE; - count = 1; - SetupNoRandPartA(); - } else { - count++; - if (count >= 4) { - z = ll8[tPos]; - tPos = tt[tPos]; - currentState = NO_RAND_PART_C_STATE; - j2 = 0; - SetupNoRandPartC(); - } else { - currentState = NO_RAND_PART_A_STATE; - SetupNoRandPartA(); - } - } - } - - void SetupNoRandPartC() - { - if (j2 < (int)z) { - currentChar = ch2; - mCrc.Update(ch2); - j2++; - } else { - currentState = NO_RAND_PART_A_STATE; - i2++; - count = 0; - SetupNoRandPartA(); - } - } - - void SetDecompressStructureSizes(int newSize100k) - { - if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k && blockSize100k <= 9)) { - throw new BZip2Exception("Invalid block size"); - } - - blockSize100k = newSize100k; - - if (newSize100k == 0) { - return; - } - - int n = BZip2Constants.BaseBlockSize * newSize100k; - ll8 = new byte[n]; - tt = new int[n]; - } + n <<= 1; + + if (groupPos == 0) { + groupNo++; + groupPos = BZip2Constants.GroupSize; + } + + groupPos--; + + zt = selector[groupNo]; + zn = minLens[zt]; + zvec = BsR(zn); + + while (zvec > limit[zt][zn]) { + zn++; + while (bsLive < 1) { + FillBuffer(); + } + zj = (bsBuff >> (bsLive - 1)) & 1; + bsLive--; + zvec = (zvec << 1) | zj; + } + nextSym = perm[zt][zvec - baseArray[zt][zn]]; + } while (nextSym == BZip2Constants.RunA || nextSym == BZip2Constants.RunB); + + s++; + byte ch = seqToUnseq[yy[0]]; + unzftab[ch] += s; + + while (s > 0) { + last++; + ll8[last] = ch; + s--; + } + + if (last >= limitLast) { + BlockOverrun(); + } + continue; + } else { + last++; + if (last >= limitLast) { + BlockOverrun(); + } + + byte tmp = yy[nextSym - 1]; + unzftab[seqToUnseq[tmp]]++; + ll8[last] = seqToUnseq[tmp]; + + for (int j = nextSym-1; j > 0; --j) { + yy[j] = yy[j - 1]; + } + yy[0] = tmp; + + if (groupPos == 0) { + groupNo++; + groupPos = BZip2Constants.GroupSize; + } + + groupPos--; + zt = selector[groupNo]; + zn = minLens[zt]; + zvec = BsR(zn); + while (zvec > limit[zt][zn]) { + zn++; + while (bsLive < 1) { + FillBuffer(); + } + zj = (bsBuff >> (bsLive-1)) & 1; + bsLive--; + zvec = (zvec << 1) | zj; + } + nextSym = perm[zt][zvec - baseArray[zt][zn]]; + continue; + } + } + } + + void SetupBlock() + { + int[] cftab = new int[257]; + + cftab[0] = 0; + Array.Copy(unzftab, 0, cftab, 1, 256); + + for (int i = 1; i <= 256; i++) { + cftab[i] += cftab[i - 1]; + } + + for (int i = 0; i <= last; i++) { + byte ch = ll8[i]; + tt[cftab[ch]] = i; + cftab[ch]++; + } + + cftab = null; + + tPos = tt[origPtr]; + + count = 0; + i2 = 0; + ch2 = 256; /*-- not a char and not EOF --*/ + + if (blockRandomised) { + rNToGo = 0; + rTPos = 0; + SetupRandPartA(); + } else { + SetupNoRandPartA(); + } + } + + void SetupRandPartA() + { + if (i2 <= last) { + chPrev = ch2; + ch2 = ll8[tPos]; + tPos = tt[tPos]; + if (rNToGo == 0) { + rNToGo = BZip2Constants.RandomNumbers[rTPos]; + rTPos++; + if (rTPos == 512) { + rTPos = 0; + } + } + rNToGo--; + ch2 ^= (int)((rNToGo == 1) ? 1 : 0); + i2++; + + currentChar = ch2; + currentState = RAND_PART_B_STATE; + mCrc.Update(ch2); + } else { + EndBlock(); + InitBlock(); + SetupBlock(); + } + } + + void SetupNoRandPartA() + { + if (i2 <= last) { + chPrev = ch2; + ch2 = ll8[tPos]; + tPos = tt[tPos]; + i2++; + + currentChar = ch2; + currentState = NO_RAND_PART_B_STATE; + mCrc.Update(ch2); + } else { + EndBlock(); + InitBlock(); + SetupBlock(); + } + } + + void SetupRandPartB() + { + if (ch2 != chPrev) { + currentState = RAND_PART_A_STATE; + count = 1; + SetupRandPartA(); + } else { + count++; + if (count >= 4) { + z = ll8[tPos]; + tPos = tt[tPos]; + if (rNToGo == 0) { + rNToGo = BZip2Constants.RandomNumbers[rTPos]; + rTPos++; + if (rTPos == 512) { + rTPos = 0; + } + } + rNToGo--; + z ^= (byte)((rNToGo == 1) ? 1 : 0); + j2 = 0; + currentState = RAND_PART_C_STATE; + SetupRandPartC(); + } else { + currentState = RAND_PART_A_STATE; + SetupRandPartA(); + } + } + } + + void SetupRandPartC() + { + if (j2 < (int)z) { + currentChar = ch2; + mCrc.Update(ch2); + j2++; + } else { + currentState = RAND_PART_A_STATE; + i2++; + count = 0; + SetupRandPartA(); + } + } + + void SetupNoRandPartB() + { + if (ch2 != chPrev) { + currentState = NO_RAND_PART_A_STATE; + count = 1; + SetupNoRandPartA(); + } else { + count++; + if (count >= 4) { + z = ll8[tPos]; + tPos = tt[tPos]; + currentState = NO_RAND_PART_C_STATE; + j2 = 0; + SetupNoRandPartC(); + } else { + currentState = NO_RAND_PART_A_STATE; + SetupNoRandPartA(); + } + } + } + + void SetupNoRandPartC() + { + if (j2 < (int)z) { + currentChar = ch2; + mCrc.Update(ch2); + j2++; + } else { + currentState = NO_RAND_PART_A_STATE; + i2++; + count = 0; + SetupNoRandPartA(); + } + } + + void SetDecompressStructureSizes(int newSize100k) + { + if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k && blockSize100k <= 9)) { + throw new BZip2Exception("Invalid block size"); + } + + blockSize100k = newSize100k; + + if (newSize100k == 0) { + return; + } + + int n = BZip2Constants.BaseBlockSize * newSize100k; + ll8 = new byte[n]; + tt = new int[n]; + } - static void CompressedStreamEOF() - { - throw new EndOfStreamException("BZip2 input stream end of compressed stream"); - } - - static void BlockOverrun() - { - throw new BZip2Exception("BZip2 input stream block overrun"); - } - - static void BadBlockHeader() - { - throw new BZip2Exception("BZip2 input stream bad block header"); - } - - static void CrcError() - { - throw new BZip2Exception("BZip2 input stream crc error"); - } - - static void HbCreateDecodeTables(int[] limit, int[] baseArray, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) - { - int pp = 0; - - for (int i = minLen; i <= maxLen; ++i) - { - for (int j = 0; j < alphaSize; ++j) - { - if (length[j] == i) - { - perm[pp] = j; - ++pp; - } - } - } - - for (int i = 0; i < BZip2Constants.MaximumCodeLength; i++) - { - baseArray[i] = 0; - } - - for (int i = 0; i < alphaSize; i++) - { - ++baseArray[length[i] + 1]; - } - - for (int i = 1; i < BZip2Constants.MaximumCodeLength; i++) - { - baseArray[i] += baseArray[i - 1]; - } - - for (int i = 0; i < BZip2Constants.MaximumCodeLength; i++) - { - limit[i] = 0; - } - - int vec = 0; - - for (int i = minLen; i <= maxLen; i++) - { - vec += (baseArray[i + 1] - baseArray[i]); - limit[i] = vec - 1; - vec <<= 1; - } - - for (int i = minLen + 1; i <= maxLen; i++) - { - baseArray[i] = ((limit[i - 1] + 1) << 1) - baseArray[i]; - } - } - - #region Instance Fields - /*-- - index of the last char in the block, so - the block size == last + 1. - --*/ - int last; - - /*-- - index in zptr[] of original string after sorting. - --*/ - int origPtr; - - /*-- - always: in the range 0 .. 9. - The current block size is 100000 * this number. - --*/ - int blockSize100k; - - bool blockRandomised; - - int bsBuff; - int bsLive; - IChecksum mCrc = new StrangeCRC(); - - bool[] inUse = new bool[256]; - int nInUse; - - byte[] seqToUnseq = new byte[256]; - byte[] unseqToSeq = new byte[256]; - - byte[] selector = new byte[BZip2Constants.MaximumSelectors]; - byte[] selectorMtf = new byte[BZip2Constants.MaximumSelectors]; - - int[] tt; - byte[] ll8; - - /*-- - freq table collected to save a pass over the data - during decompression. - --*/ - int[] unzftab = new int[256]; - - int[][] limit = new int[BZip2Constants.GroupCount][]; - int[][] baseArray = new int[BZip2Constants.GroupCount][]; - int[][] perm = new int[BZip2Constants.GroupCount][]; - int[] minLens = new int[BZip2Constants.GroupCount]; - - Stream baseStream; - bool streamEnd; - - int currentChar = -1; - - int currentState = START_BLOCK_STATE; - - int storedBlockCRC, storedCombinedCRC; - int computedBlockCRC; - uint computedCombinedCRC; - - int count, chPrev, ch2; - int tPos; - int rNToGo; - int rTPos; - int i2, j2; - byte z; - bool isStreamOwner = true; - #endregion - } + static void CompressedStreamEOF() + { + throw new EndOfStreamException("BZip2 input stream end of compressed stream"); + } + + static void BlockOverrun() + { + throw new BZip2Exception("BZip2 input stream block overrun"); + } + + static void BadBlockHeader() + { + throw new BZip2Exception("BZip2 input stream bad block header"); + } + + static void CrcError() + { + throw new BZip2Exception("BZip2 input stream crc error"); + } + + static void HbCreateDecodeTables(int[] limit, int[] baseArray, int[] perm, char[] length, int minLen, int maxLen, int alphaSize) + { + int pp = 0; + + for (int i = minLen; i <= maxLen; ++i) + { + for (int j = 0; j < alphaSize; ++j) + { + if (length[j] == i) + { + perm[pp] = j; + ++pp; + } + } + } + + for (int i = 0; i < BZip2Constants.MaximumCodeLength; i++) + { + baseArray[i] = 0; + } + + for (int i = 0; i < alphaSize; i++) + { + ++baseArray[length[i] + 1]; + } + + for (int i = 1; i < BZip2Constants.MaximumCodeLength; i++) + { + baseArray[i] += baseArray[i - 1]; + } + + for (int i = 0; i < BZip2Constants.MaximumCodeLength; i++) + { + limit[i] = 0; + } + + int vec = 0; + + for (int i = minLen; i <= maxLen; i++) + { + vec += (baseArray[i + 1] - baseArray[i]); + limit[i] = vec - 1; + vec <<= 1; + } + + for (int i = minLen + 1; i <= maxLen; i++) + { + baseArray[i] = ((limit[i - 1] + 1) << 1) - baseArray[i]; + } + } + + #region Instance Fields + /*-- + index of the last char in the block, so + the block size == last + 1. + --*/ + int last; + + /*-- + index in zptr[] of original string after sorting. + --*/ + int origPtr; + + /*-- + always: in the range 0 .. 9. + The current block size is 100000 * this number. + --*/ + int blockSize100k; + + bool blockRandomised; + + int bsBuff; + int bsLive; + IChecksum mCrc = new StrangeCRC(); + + bool[] inUse = new bool[256]; + int nInUse; + + byte[] seqToUnseq = new byte[256]; + byte[] unseqToSeq = new byte[256]; + + byte[] selector = new byte[BZip2Constants.MaximumSelectors]; + byte[] selectorMtf = new byte[BZip2Constants.MaximumSelectors]; + + int[] tt; + byte[] ll8; + + /*-- + freq table collected to save a pass over the data + during decompression. + --*/ + int[] unzftab = new int[256]; + + int[][] limit = new int[BZip2Constants.GroupCount][]; + int[][] baseArray = new int[BZip2Constants.GroupCount][]; + int[][] perm = new int[BZip2Constants.GroupCount][]; + int[] minLens = new int[BZip2Constants.GroupCount]; + + Stream baseStream; + bool streamEnd; + + int currentChar = -1; + + int currentState = START_BLOCK_STATE; + + int storedBlockCRC, storedCombinedCRC; + int computedBlockCRC; + uint computedCombinedCRC; + + int count, chPrev, ch2; + int tPos; + int rNToGo; + int rTPos; + int i2, j2; + byte z; + bool isStreamOwner = true; + #endregion + } } /* This file was derived from a file containing this license: * diff --git a/External/Tools/AppMan/ZipLib/BZip2/BZip2OutputStream.cs b/External/Tools/AppMan/ZipLib/BZip2/BZip2OutputStream.cs index 582f7a4e3c..641a25776d 100644 --- a/External/Tools/AppMan/ZipLib/BZip2/BZip2OutputStream.cs +++ b/External/Tools/AppMan/ZipLib/BZip2/BZip2OutputStream.cs @@ -40,1838 +40,1838 @@ namespace ICSharpCode.SharpZipLib.BZip2 { - - // TODO: Update to BZip2 1.0.1, 1.0.2 - - /// - /// An output stream that compresses into the BZip2 format - /// including file header chars into another stream. - /// - public class BZip2OutputStream : Stream - { - #region Constants - const int SETMASK = (1 << 21); - const int CLEARMASK = (~SETMASK); - const int GREATER_ICOST = 15; - const int LESSER_ICOST = 0; - const int SMALL_THRESH = 20; - const int DEPTH_THRESH = 10; - - /*-- - If you are ever unlucky/improbable enough - to get a stack overflow whilst sorting, - increase the following constant and try - again. In practice I have never seen the - stack go above 27 elems, so the following - limit seems very generous. - --*/ - const int QSORT_STACK_SIZE = 1000; + + // TODO: Update to BZip2 1.0.1, 1.0.2 + + /// + /// An output stream that compresses into the BZip2 format + /// including file header chars into another stream. + /// + public class BZip2OutputStream : Stream + { + #region Constants + const int SETMASK = (1 << 21); + const int CLEARMASK = (~SETMASK); + const int GREATER_ICOST = 15; + const int LESSER_ICOST = 0; + const int SMALL_THRESH = 20; + const int DEPTH_THRESH = 10; + + /*-- + If you are ever unlucky/improbable enough + to get a stack overflow whilst sorting, + increase the following constant and try + again. In practice I have never seen the + stack go above 27 elems, so the following + limit seems very generous. + --*/ + const int QSORT_STACK_SIZE = 1000; - /*-- - Knuth's increments seem to work better - than Incerpi-Sedgewick here. Possibly - because the number of elems to sort is - usually small, typically <= 20. - --*/ - readonly int[] increments = new int[] { - 1, 4, 13, 40, 121, 364, 1093, 3280, - 9841, 29524, 88573, 265720, - 797161, 2391484 - }; - #endregion + /*-- + Knuth's increments seem to work better + than Incerpi-Sedgewick here. Possibly + because the number of elems to sort is + usually small, typically <= 20. + --*/ + readonly int[] increments = new int[] { + 1, 4, 13, 40, 121, 364, 1093, 3280, + 9841, 29524, 88573, 265720, + 797161, 2391484 + }; + #endregion - #region Constructors - /// - /// Construct a default output stream with maximum block size - /// - /// The stream to write BZip data onto. - public BZip2OutputStream(Stream stream) : this(stream, 9) - { - } - - /// - /// Initialise a new instance of the - /// for the specified stream, using the given blocksize. - /// - /// The stream to write compressed data to. - /// The block size to use. - /// - /// Valid block sizes are in the range 1..9, with 1 giving - /// the lowest compression and 9 the highest. - /// - public BZip2OutputStream(Stream stream, int blockSize) - { - BsSetStream(stream); - - workFactor = 50; - if (blockSize > 9) { - blockSize = 9; - } - - if (blockSize < 1) { - blockSize = 1; - } - blockSize100k = blockSize; - AllocateCompressStructures(); - Initialize(); - InitBlock(); - } - #endregion - - #region Destructor - /// - /// Ensures that resources are freed and other cleanup operations - /// are performed when the garbage collector reclaims the BZip2OutputStream. - /// - ~BZip2OutputStream() - { - Dispose(false); - } - #endregion - - /// - /// Get/set flag indicating ownership of underlying stream. - /// When the flag is true will close the underlying stream also. - /// - public bool IsStreamOwner - { - get { return isStreamOwner; } - set { isStreamOwner = value; } - } - + #region Constructors + /// + /// Construct a default output stream with maximum block size + /// + /// The stream to write BZip data onto. + public BZip2OutputStream(Stream stream) : this(stream, 9) + { + } + + /// + /// Initialise a new instance of the + /// for the specified stream, using the given blocksize. + /// + /// The stream to write compressed data to. + /// The block size to use. + /// + /// Valid block sizes are in the range 1..9, with 1 giving + /// the lowest compression and 9 the highest. + /// + public BZip2OutputStream(Stream stream, int blockSize) + { + BsSetStream(stream); + + workFactor = 50; + if (blockSize > 9) { + blockSize = 9; + } + + if (blockSize < 1) { + blockSize = 1; + } + blockSize100k = blockSize; + AllocateCompressStructures(); + Initialize(); + InitBlock(); + } + #endregion + + #region Destructor + /// + /// Ensures that resources are freed and other cleanup operations + /// are performed when the garbage collector reclaims the BZip2OutputStream. + /// + ~BZip2OutputStream() + { + Dispose(false); + } + #endregion + + /// + /// Get/set flag indicating ownership of underlying stream. + /// When the flag is true will close the underlying stream also. + /// + public bool IsStreamOwner + { + get { return isStreamOwner; } + set { isStreamOwner = value; } + } + - #region Stream overrides - /// - /// Gets a value indicating whether the current stream supports reading - /// - public override bool CanRead - { - get { - return false; - } - } - - /// - /// Gets a value indicating whether the current stream supports seeking - /// - public override bool CanSeek { - get { - return false; - } - } - - /// - /// Gets a value indicating whether the current stream supports writing - /// - public override bool CanWrite { - get { - return baseStream.CanWrite; - } - } - - /// - /// Gets the length in bytes of the stream - /// - public override long Length { - get { - return baseStream.Length; - } - } - - /// - /// Gets or sets the current position of this stream. - /// - public override long Position { - get { - return baseStream.Position; - } - set { - throw new NotSupportedException("BZip2OutputStream position cannot be set"); - } - } - - /// - /// Sets the current position of this stream to the given value. - /// - /// The point relative to the offset from which to being seeking. - /// The reference point from which to begin seeking. - /// The new position in the stream. - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException("BZip2OutputStream Seek not supported"); - } - - /// - /// Sets the length of this stream to the given value. - /// - /// The new stream length. - public override void SetLength(long value) - { - throw new NotSupportedException("BZip2OutputStream SetLength not supported"); - } - - /// - /// Read a byte from the stream advancing the position. - /// - /// The byte read cast to an int; -1 if end of stream. - public override int ReadByte() - { - throw new NotSupportedException("BZip2OutputStream ReadByte not supported"); - } - - /// - /// Read a block of bytes - /// - /// The buffer to read into. - /// The offset in the buffer to start storing data at. - /// The maximum number of bytes to read. - /// The total number of bytes read. This might be less than the number of bytes - /// requested if that number of bytes are not currently available, or zero - /// if the end of the stream is reached. - public override int Read(byte[] buffer, int offset, int count) - { - throw new NotSupportedException("BZip2OutputStream Read not supported"); - } - - /// - /// Write a block of bytes to the stream - /// - /// The buffer containing data to write. - /// The offset of the first byte to write. - /// The number of bytes to write. - public override void Write(byte[] buffer, int offset, int count) - { - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } + #region Stream overrides + /// + /// Gets a value indicating whether the current stream supports reading + /// + public override bool CanRead + { + get { + return false; + } + } + + /// + /// Gets a value indicating whether the current stream supports seeking + /// + public override bool CanSeek { + get { + return false; + } + } + + /// + /// Gets a value indicating whether the current stream supports writing + /// + public override bool CanWrite { + get { + return baseStream.CanWrite; + } + } + + /// + /// Gets the length in bytes of the stream + /// + public override long Length { + get { + return baseStream.Length; + } + } + + /// + /// Gets or sets the current position of this stream. + /// + public override long Position { + get { + return baseStream.Position; + } + set { + throw new NotSupportedException("BZip2OutputStream position cannot be set"); + } + } + + /// + /// Sets the current position of this stream to the given value. + /// + /// The point relative to the offset from which to being seeking. + /// The reference point from which to begin seeking. + /// The new position in the stream. + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException("BZip2OutputStream Seek not supported"); + } + + /// + /// Sets the length of this stream to the given value. + /// + /// The new stream length. + public override void SetLength(long value) + { + throw new NotSupportedException("BZip2OutputStream SetLength not supported"); + } + + /// + /// Read a byte from the stream advancing the position. + /// + /// The byte read cast to an int; -1 if end of stream. + public override int ReadByte() + { + throw new NotSupportedException("BZip2OutputStream ReadByte not supported"); + } + + /// + /// Read a block of bytes + /// + /// The buffer to read into. + /// The offset in the buffer to start storing data at. + /// The maximum number of bytes to read. + /// The total number of bytes read. This might be less than the number of bytes + /// requested if that number of bytes are not currently available, or zero + /// if the end of the stream is reached. + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException("BZip2OutputStream Read not supported"); + } + + /// + /// Write a block of bytes to the stream + /// + /// The buffer containing data to write. + /// The offset of the first byte to write. + /// The number of bytes to write. + public override void Write(byte[] buffer, int offset, int count) + { + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } - if ( offset < 0 ) - { - throw new ArgumentOutOfRangeException("offset"); - } + if ( offset < 0 ) + { + throw new ArgumentOutOfRangeException("offset"); + } - if ( count < 0 ) - { - throw new ArgumentOutOfRangeException("count"); - } + if ( count < 0 ) + { + throw new ArgumentOutOfRangeException("count"); + } - if ( buffer.Length - offset < count ) - { - throw new ArgumentException("Offset/count out of range"); - } + if ( buffer.Length - offset < count ) + { + throw new ArgumentException("Offset/count out of range"); + } - for (int i = 0; i < count; ++i) { - WriteByte(buffer[offset + i]); - } - } - - /// - /// Write a byte to the stream. - /// - /// The byte to write to the stream. - public override void WriteByte(byte value) - { - int b = (256 + value) % 256; - if (currentChar != -1) { - if (currentChar == b) { - runLength++; - if (runLength > 254) { - WriteRun(); - currentChar = -1; - runLength = 0; - } - } else { - WriteRun(); - runLength = 1; - currentChar = b; - } - } else { - currentChar = b; - runLength++; - } - } - - /// - /// End the current block and end compression. - /// Close the stream and free any resources - /// - public override void Close() - { - Dispose(true); - GC.SuppressFinalize(this); - } + for (int i = 0; i < count; ++i) { + WriteByte(buffer[offset + i]); + } + } + + /// + /// Write a byte to the stream. + /// + /// The byte to write to the stream. + public override void WriteByte(byte value) + { + int b = (256 + value) % 256; + if (currentChar != -1) { + if (currentChar == b) { + runLength++; + if (runLength > 254) { + WriteRun(); + currentChar = -1; + runLength = 0; + } + } else { + WriteRun(); + runLength = 1; + currentChar = b; + } + } else { + currentChar = b; + runLength++; + } + } + + /// + /// End the current block and end compression. + /// Close the stream and free any resources + /// + public override void Close() + { + Dispose(true); + GC.SuppressFinalize(this); + } - #endregion - void MakeMaps() - { - nInUse = 0; - for (int i = 0; i < 256; i++) { - if (inUse[i]) { - seqToUnseq[nInUse] = (char)i; - unseqToSeq[i] = (char)nInUse; - nInUse++; - } - } - } - - /// - /// Get the number of bytes written to output. - /// - void WriteRun() - { - if (last < allowableBlockSize) { - inUse[currentChar] = true; - for (int i = 0; i < runLength; i++) { - mCrc.Update(currentChar); - } - - switch (runLength) { - case 1: - last++; - block[last + 1] = (byte)currentChar; - break; - case 2: - last++; - block[last + 1] = (byte)currentChar; - last++; - block[last + 1] = (byte)currentChar; - break; - case 3: - last++; - block[last + 1] = (byte)currentChar; - last++; - block[last + 1] = (byte)currentChar; - last++; - block[last + 1] = (byte)currentChar; - break; - default: - inUse[runLength - 4] = true; - last++; - block[last + 1] = (byte)currentChar; - last++; - block[last + 1] = (byte)currentChar; - last++; - block[last + 1] = (byte)currentChar; - last++; - block[last + 1] = (byte)currentChar; - last++; - block[last + 1] = (byte)(runLength - 4); - break; - } - } else { - EndBlock(); - InitBlock(); - WriteRun(); - } - } - - /// - /// Get the number of bytes written to the output. - /// - public int BytesWritten - { - get { return bytesOut; } - } + #endregion + void MakeMaps() + { + nInUse = 0; + for (int i = 0; i < 256; i++) { + if (inUse[i]) { + seqToUnseq[nInUse] = (char)i; + unseqToSeq[i] = (char)nInUse; + nInUse++; + } + } + } + + /// + /// Get the number of bytes written to output. + /// + void WriteRun() + { + if (last < allowableBlockSize) { + inUse[currentChar] = true; + for (int i = 0; i < runLength; i++) { + mCrc.Update(currentChar); + } + + switch (runLength) { + case 1: + last++; + block[last + 1] = (byte)currentChar; + break; + case 2: + last++; + block[last + 1] = (byte)currentChar; + last++; + block[last + 1] = (byte)currentChar; + break; + case 3: + last++; + block[last + 1] = (byte)currentChar; + last++; + block[last + 1] = (byte)currentChar; + last++; + block[last + 1] = (byte)currentChar; + break; + default: + inUse[runLength - 4] = true; + last++; + block[last + 1] = (byte)currentChar; + last++; + block[last + 1] = (byte)currentChar; + last++; + block[last + 1] = (byte)currentChar; + last++; + block[last + 1] = (byte)currentChar; + last++; + block[last + 1] = (byte)(runLength - 4); + break; + } + } else { + EndBlock(); + InitBlock(); + WriteRun(); + } + } + + /// + /// Get the number of bytes written to the output. + /// + public int BytesWritten + { + get { return bytesOut; } + } - /// - /// Releases the unmanaged resources used by the and optionally releases the managed resources. - /// - /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + /// + /// Releases the unmanaged resources used by the and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. #if NET_1_0 || NET_1_1 || NETCF_1_0 - protected virtual void Dispose(bool disposing) -#else - override protected void Dispose(bool disposing) -#endif - { - try { + protected virtual void Dispose(bool disposing) +#else + override protected void Dispose(bool disposing) +#endif + { + try { #if !NET_1_0 && !NET_1_1 && !NETCF_1_0 - base.Dispose(disposing); -#endif - if( !disposed_ ) { - disposed_=true; + base.Dispose(disposing); +#endif + if( !disposed_ ) { + disposed_=true; - if( runLength>0 ) { - WriteRun(); - } + if( runLength>0 ) { + WriteRun(); + } - currentChar=-1; - EndBlock(); - EndCompression(); - Flush(); - } - } - finally { - if ( disposing ) { - if ( IsStreamOwner ) { - baseStream.Close(); - } - } - } - } + currentChar=-1; + EndBlock(); + EndCompression(); + Flush(); + } + } + finally { + if ( disposing ) { + if ( IsStreamOwner ) { + baseStream.Close(); + } + } + } + } - /// - /// Flush output buffers - /// - public override void Flush() - { - baseStream.Flush(); - } - - void Initialize() - { - bytesOut = 0; - nBlocksRandomised = 0; - - /*--- Write header `magic' bytes indicating file-format == huffmanised, - followed by a digit indicating blockSize100k. - ---*/ - - BsPutUChar('B'); - BsPutUChar('Z'); - - BsPutUChar('h'); - BsPutUChar('0' + blockSize100k); - - combinedCRC = 0; - } - - void InitBlock() - { - mCrc.Reset(); - last = -1; - - for (int i = 0; i < 256; i++) { - inUse[i] = false; - } - - /*--- 20 is just a paranoia constant ---*/ - allowableBlockSize = BZip2Constants.BaseBlockSize * blockSize100k - 20; - } - - void EndBlock() - { - if (last < 0) { // dont do anything for empty files, (makes empty files compatible with original Bzip) - return; - } - - blockCRC = unchecked((uint)mCrc.Value); - combinedCRC = (combinedCRC << 1) | (combinedCRC >> 31); - combinedCRC ^= blockCRC; - - /*-- sort the block and establish position of original string --*/ - DoReversibleTransformation(); - - /*-- - A 6-byte block header, the value chosen arbitrarily - as 0x314159265359 :-). A 32 bit value does not really - give a strong enough guarantee that the value will not - appear by chance in the compressed datastream. Worst-case - probability of this event, for a 900k block, is about - 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits. - For a compressed file of size 100Gb -- about 100000 blocks -- - only a 48-bit marker will do. NB: normal compression/ - decompression do *not* rely on these statistical properties. - They are only important when trying to recover blocks from - damaged files. - --*/ - BsPutUChar(0x31); - BsPutUChar(0x41); - BsPutUChar(0x59); - BsPutUChar(0x26); - BsPutUChar(0x53); - BsPutUChar(0x59); - - /*-- Now the block's CRC, so it is in a known place. --*/ - unchecked { - BsPutint((int)blockCRC); - } - - /*-- Now a single bit indicating randomisation. --*/ - if (blockRandomised) { - BsW(1,1); - nBlocksRandomised++; - } else { - BsW(1,0); - } - - /*-- Finally, block's contents proper. --*/ - MoveToFrontCodeAndSend(); - } - - void EndCompression() - { - /*-- - Now another magic 48-bit number, 0x177245385090, to - indicate the end of the last block. (sqrt(pi), if - you want to know. I did want to use e, but it contains - too much repetition -- 27 18 28 18 28 46 -- for me - to feel statistically comfortable. Call me paranoid.) - --*/ - BsPutUChar(0x17); - BsPutUChar(0x72); - BsPutUChar(0x45); - BsPutUChar(0x38); - BsPutUChar(0x50); - BsPutUChar(0x90); - - unchecked { - BsPutint((int)combinedCRC); - } - - BsFinishedWithStream(); - } - - void BsSetStream(Stream stream) - { - baseStream = stream; - bsLive = 0; - bsBuff = 0; - bytesOut = 0; - } - - void BsFinishedWithStream() - { - while (bsLive > 0) - { - int ch = (bsBuff >> 24); - baseStream.WriteByte((byte)ch); // write 8-bit - bsBuff <<= 8; - bsLive -= 8; - bytesOut++; - } - } - - void BsW(int n, int v) - { - while (bsLive >= 8) { - int ch = (bsBuff >> 24); - unchecked{baseStream.WriteByte((byte)ch);} // write 8-bit - bsBuff <<= 8; - bsLive -= 8; - ++bytesOut; - } - bsBuff |= (v << (32 - bsLive - n)); - bsLive += n; - } - - void BsPutUChar(int c) - { - BsW(8, c); - } - - void BsPutint(int u) - { - BsW(8, (u >> 24) & 0xFF); - BsW(8, (u >> 16) & 0xFF); - BsW(8, (u >> 8) & 0xFF); - BsW(8, u & 0xFF); - } - - void BsPutIntVS(int numBits, int c) - { - BsW(numBits, c); - } - - void SendMTFValues() - { - char[][] len = new char[BZip2Constants.GroupCount][]; - for (int i = 0; i < BZip2Constants.GroupCount; ++i) { - len[i] = new char[BZip2Constants.MaximumAlphaSize]; - } - - int gs, ge, totc, bt, bc, iter; - int nSelectors = 0, alphaSize, minLen, maxLen, selCtr; - int nGroups; - - alphaSize = nInUse + 2; - for (int t = 0; t < BZip2Constants.GroupCount; t++) { - for (int v = 0; v < alphaSize; v++) { - len[t][v] = (char)GREATER_ICOST; - } - } - - /*--- Decide how many coding tables to use ---*/ - if (nMTF <= 0) { - Panic(); - } - - if (nMTF < 200) { - nGroups = 2; - } else if (nMTF < 600) { - nGroups = 3; - } else if (nMTF < 1200) { - nGroups = 4; - } else if (nMTF < 2400) { - nGroups = 5; - } else { - nGroups = 6; - } - - /*--- Generate an initial set of coding tables ---*/ - int nPart = nGroups; - int remF = nMTF; - gs = 0; - while (nPart > 0) { - int tFreq = remF / nPart; - int aFreq = 0; - ge = gs - 1; - while (aFreq < tFreq && ge < alphaSize - 1) { - ge++; - aFreq += mtfFreq[ge]; - } - - if (ge > gs && nPart != nGroups && nPart != 1 && ((nGroups - nPart) % 2 == 1)) { - aFreq -= mtfFreq[ge]; - ge--; - } - - for (int v = 0; v < alphaSize; v++) { - if (v >= gs && v <= ge) { - len[nPart - 1][v] = (char)LESSER_ICOST; - } else { - len[nPart - 1][v] = (char)GREATER_ICOST; - } - } - - nPart--; - gs = ge + 1; - remF -= aFreq; - } - - int[][] rfreq = new int[BZip2Constants.GroupCount][]; - for (int i = 0; i < BZip2Constants.GroupCount; ++i) { - rfreq[i] = new int[BZip2Constants.MaximumAlphaSize]; - } - - int[] fave = new int[BZip2Constants.GroupCount]; - short[] cost = new short[BZip2Constants.GroupCount]; - /*--- - Iterate up to N_ITERS times to improve the tables. - ---*/ - for (iter = 0; iter < BZip2Constants.NumberOfIterations; ++iter) { - for (int t = 0; t < nGroups; ++t) { - fave[t] = 0; - } - - for (int t = 0; t < nGroups; ++t) { - for (int v = 0; v < alphaSize; ++v) { - rfreq[t][v] = 0; - } - } - - nSelectors = 0; - totc = 0; - gs = 0; - while (true) { - /*--- Set group start & end marks. --*/ - if (gs >= nMTF) { - break; - } - ge = gs + BZip2Constants.GroupSize - 1; - if (ge >= nMTF) { - ge = nMTF - 1; - } - - /*-- - Calculate the cost of this group as coded - by each of the coding tables. - --*/ - for (int t = 0; t < nGroups; t++) { - cost[t] = 0; - } - - if (nGroups == 6) { - short cost0, cost1, cost2, cost3, cost4, cost5; - cost0 = cost1 = cost2 = cost3 = cost4 = cost5 = 0; - for (int i = gs; i <= ge; ++i) { - short icv = szptr[i]; - cost0 += (short)len[0][icv]; - cost1 += (short)len[1][icv]; - cost2 += (short)len[2][icv]; - cost3 += (short)len[3][icv]; - cost4 += (short)len[4][icv]; - cost5 += (short)len[5][icv]; - } - cost[0] = cost0; - cost[1] = cost1; - cost[2] = cost2; - cost[3] = cost3; - cost[4] = cost4; - cost[5] = cost5; - } else { - for (int i = gs; i <= ge; ++i) { - short icv = szptr[i]; - for (int t = 0; t < nGroups; t++) { - cost[t] += (short)len[t][icv]; - } - } - } - - /*-- - Find the coding table which is best for this group, - and record its identity in the selector table. - --*/ - bc = 999999999; - bt = -1; - for (int t = 0; t < nGroups; ++t) { - if (cost[t] < bc) { - bc = cost[t]; - bt = t; - } - } - totc += bc; - fave[bt]++; - selector[nSelectors] = (char)bt; - nSelectors++; - - /*-- - Increment the symbol frequencies for the selected table. - --*/ - for (int i = gs; i <= ge; ++i) { - ++rfreq[bt][szptr[i]]; - } - - gs = ge+1; - } - - /*-- - Recompute the tables based on the accumulated frequencies. - --*/ - for (int t = 0; t < nGroups; ++t) { - HbMakeCodeLengths(len[t], rfreq[t], alphaSize, 20); - } - } - - rfreq = null; - fave = null; - cost = null; - - if (!(nGroups < 8)) { - Panic(); - } - - if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / BZip2Constants.GroupSize)))) { - Panic(); - } - - /*--- Compute MTF values for the selectors. ---*/ - char[] pos = new char[BZip2Constants.GroupCount]; - char ll_i, tmp2, tmp; - - for (int i = 0; i < nGroups; i++) { - pos[i] = (char)i; - } - - for (int i = 0; i < nSelectors; i++) { - ll_i = selector[i]; - int j = 0; - tmp = pos[j]; - while (ll_i != tmp) { - j++; - tmp2 = tmp; - tmp = pos[j]; - pos[j] = tmp2; - } - pos[0] = tmp; - selectorMtf[i] = (char)j; - } - - int[][] code = new int[BZip2Constants.GroupCount][]; - - for (int i = 0; i < BZip2Constants.GroupCount; ++i) { - code[i] = new int[BZip2Constants.MaximumAlphaSize]; - } - - /*--- Assign actual codes for the tables. --*/ - for (int t = 0; t < nGroups; t++) { - minLen = 32; - maxLen = 0; - for (int i = 0; i < alphaSize; i++) { - if (len[t][i] > maxLen) { - maxLen = len[t][i]; - } - if (len[t][i] < minLen) { - minLen = len[t][i]; - } - } - if (maxLen > 20) { - Panic(); - } - if (minLen < 1) { - Panic(); - } - HbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize); - } - - /*--- Transmit the mapping table. ---*/ - bool[] inUse16 = new bool[16]; - for (int i = 0; i < 16; ++i) { - inUse16[i] = false; - for (int j = 0; j < 16; ++j) { - if (inUse[i * 16 + j]) { - inUse16[i] = true; - } - } - } - - for (int i = 0; i < 16; ++i) { - if (inUse16[i]) { - BsW(1,1); - } else { - BsW(1,0); - } - } - - for (int i = 0; i < 16; ++i) { - if (inUse16[i]) { - for (int j = 0; j < 16; ++j) { - if (inUse[i * 16 + j]) { - BsW(1,1); - } else { - BsW(1,0); - } - } - } - } - - /*--- Now the selectors. ---*/ - BsW(3, nGroups); - BsW(15, nSelectors); - for (int i = 0; i < nSelectors; ++i) { - for (int j = 0; j < selectorMtf[i]; ++j) { - BsW(1,1); - } - BsW(1,0); - } - - /*--- Now the coding tables. ---*/ - for (int t = 0; t < nGroups; ++t) { - int curr = len[t][0]; - BsW(5, curr); - for (int i = 0; i < alphaSize; ++i) { - while (curr < len[t][i]) { - BsW(2, 2); - curr++; /* 10 */ - } - while (curr > len[t][i]) { - BsW(2, 3); - curr--; /* 11 */ - } - BsW (1, 0); - } - } - - /*--- And finally, the block data proper ---*/ - selCtr = 0; - gs = 0; - while (true) { - if (gs >= nMTF) { - break; - } - ge = gs + BZip2Constants.GroupSize - 1; - if (ge >= nMTF) { - ge = nMTF - 1; - } - - for (int i = gs; i <= ge; i++) { - BsW(len[selector[selCtr]][szptr[i]], code[selector[selCtr]][szptr[i]]); - } - - gs = ge + 1; - ++selCtr; - } - if (!(selCtr == nSelectors)) { - Panic(); - } - } - - void MoveToFrontCodeAndSend () - { - BsPutIntVS(24, origPtr); - GenerateMTFValues(); - SendMTFValues(); - } - - void SimpleSort(int lo, int hi, int d) - { - int i, j, h, bigN, hp; - int v; - - bigN = hi - lo + 1; - if (bigN < 2) { - return; - } - - hp = 0; - while (increments[hp] < bigN) { - hp++; - } - hp--; - - for (; hp >= 0; hp--) { - h = increments[hp]; - - i = lo + h; - while (true) { - /*-- copy 1 --*/ - if (i > hi) - break; - v = zptr[i]; - j = i; - while (FullGtU(zptr[j-h]+d, v+d)) { - zptr[j] = zptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) - break; - } - zptr[j] = v; - i++; - - /*-- copy 2 --*/ - if (i > hi) { - break; - } - v = zptr[i]; - j = i; - while (FullGtU ( zptr[j-h]+d, v+d )) { - zptr[j] = zptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) { - break; - } - } - zptr[j] = v; - i++; - - /*-- copy 3 --*/ - if (i > hi) { - break; - } - v = zptr[i]; - j = i; - while (FullGtU ( zptr[j-h]+d, v+d)) { - zptr[j] = zptr[j-h]; - j = j - h; - if (j <= (lo + h - 1)) { - break; - } - } - zptr[j] = v; - i++; - - if (workDone > workLimit && firstAttempt) { - return; - } - } - } - } - - void Vswap(int p1, int p2, int n ) - { - int temp = 0; - while (n > 0) { - temp = zptr[p1]; - zptr[p1] = zptr[p2]; - zptr[p2] = temp; - p1++; - p2++; - n--; - } - } - - void QSort3(int loSt, int hiSt, int dSt) - { - int unLo, unHi, ltLo, gtHi, med, n, m; - int lo, hi, d; - - StackElement[] stack = new StackElement[QSORT_STACK_SIZE]; + /// + /// Flush output buffers + /// + public override void Flush() + { + baseStream.Flush(); + } + + void Initialize() + { + bytesOut = 0; + nBlocksRandomised = 0; + + /*--- Write header `magic' bytes indicating file-format == huffmanised, + followed by a digit indicating blockSize100k. + ---*/ + + BsPutUChar('B'); + BsPutUChar('Z'); + + BsPutUChar('h'); + BsPutUChar('0' + blockSize100k); + + combinedCRC = 0; + } + + void InitBlock() + { + mCrc.Reset(); + last = -1; + + for (int i = 0; i < 256; i++) { + inUse[i] = false; + } + + /*--- 20 is just a paranoia constant ---*/ + allowableBlockSize = BZip2Constants.BaseBlockSize * blockSize100k - 20; + } + + void EndBlock() + { + if (last < 0) { // dont do anything for empty files, (makes empty files compatible with original Bzip) + return; + } + + blockCRC = unchecked((uint)mCrc.Value); + combinedCRC = (combinedCRC << 1) | (combinedCRC >> 31); + combinedCRC ^= blockCRC; + + /*-- sort the block and establish position of original string --*/ + DoReversibleTransformation(); + + /*-- + A 6-byte block header, the value chosen arbitrarily + as 0x314159265359 :-). A 32 bit value does not really + give a strong enough guarantee that the value will not + appear by chance in the compressed datastream. Worst-case + probability of this event, for a 900k block, is about + 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits. + For a compressed file of size 100Gb -- about 100000 blocks -- + only a 48-bit marker will do. NB: normal compression/ + decompression do *not* rely on these statistical properties. + They are only important when trying to recover blocks from + damaged files. + --*/ + BsPutUChar(0x31); + BsPutUChar(0x41); + BsPutUChar(0x59); + BsPutUChar(0x26); + BsPutUChar(0x53); + BsPutUChar(0x59); + + /*-- Now the block's CRC, so it is in a known place. --*/ + unchecked { + BsPutint((int)blockCRC); + } + + /*-- Now a single bit indicating randomisation. --*/ + if (blockRandomised) { + BsW(1,1); + nBlocksRandomised++; + } else { + BsW(1,0); + } + + /*-- Finally, block's contents proper. --*/ + MoveToFrontCodeAndSend(); + } + + void EndCompression() + { + /*-- + Now another magic 48-bit number, 0x177245385090, to + indicate the end of the last block. (sqrt(pi), if + you want to know. I did want to use e, but it contains + too much repetition -- 27 18 28 18 28 46 -- for me + to feel statistically comfortable. Call me paranoid.) + --*/ + BsPutUChar(0x17); + BsPutUChar(0x72); + BsPutUChar(0x45); + BsPutUChar(0x38); + BsPutUChar(0x50); + BsPutUChar(0x90); + + unchecked { + BsPutint((int)combinedCRC); + } + + BsFinishedWithStream(); + } + + void BsSetStream(Stream stream) + { + baseStream = stream; + bsLive = 0; + bsBuff = 0; + bytesOut = 0; + } + + void BsFinishedWithStream() + { + while (bsLive > 0) + { + int ch = (bsBuff >> 24); + baseStream.WriteByte((byte)ch); // write 8-bit + bsBuff <<= 8; + bsLive -= 8; + bytesOut++; + } + } + + void BsW(int n, int v) + { + while (bsLive >= 8) { + int ch = (bsBuff >> 24); + unchecked{baseStream.WriteByte((byte)ch);} // write 8-bit + bsBuff <<= 8; + bsLive -= 8; + ++bytesOut; + } + bsBuff |= (v << (32 - bsLive - n)); + bsLive += n; + } + + void BsPutUChar(int c) + { + BsW(8, c); + } + + void BsPutint(int u) + { + BsW(8, (u >> 24) & 0xFF); + BsW(8, (u >> 16) & 0xFF); + BsW(8, (u >> 8) & 0xFF); + BsW(8, u & 0xFF); + } + + void BsPutIntVS(int numBits, int c) + { + BsW(numBits, c); + } + + void SendMTFValues() + { + char[][] len = new char[BZip2Constants.GroupCount][]; + for (int i = 0; i < BZip2Constants.GroupCount; ++i) { + len[i] = new char[BZip2Constants.MaximumAlphaSize]; + } + + int gs, ge, totc, bt, bc, iter; + int nSelectors = 0, alphaSize, minLen, maxLen, selCtr; + int nGroups; + + alphaSize = nInUse + 2; + for (int t = 0; t < BZip2Constants.GroupCount; t++) { + for (int v = 0; v < alphaSize; v++) { + len[t][v] = (char)GREATER_ICOST; + } + } + + /*--- Decide how many coding tables to use ---*/ + if (nMTF <= 0) { + Panic(); + } + + if (nMTF < 200) { + nGroups = 2; + } else if (nMTF < 600) { + nGroups = 3; + } else if (nMTF < 1200) { + nGroups = 4; + } else if (nMTF < 2400) { + nGroups = 5; + } else { + nGroups = 6; + } + + /*--- Generate an initial set of coding tables ---*/ + int nPart = nGroups; + int remF = nMTF; + gs = 0; + while (nPart > 0) { + int tFreq = remF / nPart; + int aFreq = 0; + ge = gs - 1; + while (aFreq < tFreq && ge < alphaSize - 1) { + ge++; + aFreq += mtfFreq[ge]; + } + + if (ge > gs && nPart != nGroups && nPart != 1 && ((nGroups - nPart) % 2 == 1)) { + aFreq -= mtfFreq[ge]; + ge--; + } + + for (int v = 0; v < alphaSize; v++) { + if (v >= gs && v <= ge) { + len[nPart - 1][v] = (char)LESSER_ICOST; + } else { + len[nPart - 1][v] = (char)GREATER_ICOST; + } + } + + nPart--; + gs = ge + 1; + remF -= aFreq; + } + + int[][] rfreq = new int[BZip2Constants.GroupCount][]; + for (int i = 0; i < BZip2Constants.GroupCount; ++i) { + rfreq[i] = new int[BZip2Constants.MaximumAlphaSize]; + } + + int[] fave = new int[BZip2Constants.GroupCount]; + short[] cost = new short[BZip2Constants.GroupCount]; + /*--- + Iterate up to N_ITERS times to improve the tables. + ---*/ + for (iter = 0; iter < BZip2Constants.NumberOfIterations; ++iter) { + for (int t = 0; t < nGroups; ++t) { + fave[t] = 0; + } + + for (int t = 0; t < nGroups; ++t) { + for (int v = 0; v < alphaSize; ++v) { + rfreq[t][v] = 0; + } + } + + nSelectors = 0; + totc = 0; + gs = 0; + while (true) { + /*--- Set group start & end marks. --*/ + if (gs >= nMTF) { + break; + } + ge = gs + BZip2Constants.GroupSize - 1; + if (ge >= nMTF) { + ge = nMTF - 1; + } + + /*-- + Calculate the cost of this group as coded + by each of the coding tables. + --*/ + for (int t = 0; t < nGroups; t++) { + cost[t] = 0; + } + + if (nGroups == 6) { + short cost0, cost1, cost2, cost3, cost4, cost5; + cost0 = cost1 = cost2 = cost3 = cost4 = cost5 = 0; + for (int i = gs; i <= ge; ++i) { + short icv = szptr[i]; + cost0 += (short)len[0][icv]; + cost1 += (short)len[1][icv]; + cost2 += (short)len[2][icv]; + cost3 += (short)len[3][icv]; + cost4 += (short)len[4][icv]; + cost5 += (short)len[5][icv]; + } + cost[0] = cost0; + cost[1] = cost1; + cost[2] = cost2; + cost[3] = cost3; + cost[4] = cost4; + cost[5] = cost5; + } else { + for (int i = gs; i <= ge; ++i) { + short icv = szptr[i]; + for (int t = 0; t < nGroups; t++) { + cost[t] += (short)len[t][icv]; + } + } + } + + /*-- + Find the coding table which is best for this group, + and record its identity in the selector table. + --*/ + bc = 999999999; + bt = -1; + for (int t = 0; t < nGroups; ++t) { + if (cost[t] < bc) { + bc = cost[t]; + bt = t; + } + } + totc += bc; + fave[bt]++; + selector[nSelectors] = (char)bt; + nSelectors++; + + /*-- + Increment the symbol frequencies for the selected table. + --*/ + for (int i = gs; i <= ge; ++i) { + ++rfreq[bt][szptr[i]]; + } + + gs = ge+1; + } + + /*-- + Recompute the tables based on the accumulated frequencies. + --*/ + for (int t = 0; t < nGroups; ++t) { + HbMakeCodeLengths(len[t], rfreq[t], alphaSize, 20); + } + } + + rfreq = null; + fave = null; + cost = null; + + if (!(nGroups < 8)) { + Panic(); + } + + if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / BZip2Constants.GroupSize)))) { + Panic(); + } + + /*--- Compute MTF values for the selectors. ---*/ + char[] pos = new char[BZip2Constants.GroupCount]; + char ll_i, tmp2, tmp; + + for (int i = 0; i < nGroups; i++) { + pos[i] = (char)i; + } + + for (int i = 0; i < nSelectors; i++) { + ll_i = selector[i]; + int j = 0; + tmp = pos[j]; + while (ll_i != tmp) { + j++; + tmp2 = tmp; + tmp = pos[j]; + pos[j] = tmp2; + } + pos[0] = tmp; + selectorMtf[i] = (char)j; + } + + int[][] code = new int[BZip2Constants.GroupCount][]; + + for (int i = 0; i < BZip2Constants.GroupCount; ++i) { + code[i] = new int[BZip2Constants.MaximumAlphaSize]; + } + + /*--- Assign actual codes for the tables. --*/ + for (int t = 0; t < nGroups; t++) { + minLen = 32; + maxLen = 0; + for (int i = 0; i < alphaSize; i++) { + if (len[t][i] > maxLen) { + maxLen = len[t][i]; + } + if (len[t][i] < minLen) { + minLen = len[t][i]; + } + } + if (maxLen > 20) { + Panic(); + } + if (minLen < 1) { + Panic(); + } + HbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize); + } + + /*--- Transmit the mapping table. ---*/ + bool[] inUse16 = new bool[16]; + for (int i = 0; i < 16; ++i) { + inUse16[i] = false; + for (int j = 0; j < 16; ++j) { + if (inUse[i * 16 + j]) { + inUse16[i] = true; + } + } + } + + for (int i = 0; i < 16; ++i) { + if (inUse16[i]) { + BsW(1,1); + } else { + BsW(1,0); + } + } + + for (int i = 0; i < 16; ++i) { + if (inUse16[i]) { + for (int j = 0; j < 16; ++j) { + if (inUse[i * 16 + j]) { + BsW(1,1); + } else { + BsW(1,0); + } + } + } + } + + /*--- Now the selectors. ---*/ + BsW(3, nGroups); + BsW(15, nSelectors); + for (int i = 0; i < nSelectors; ++i) { + for (int j = 0; j < selectorMtf[i]; ++j) { + BsW(1,1); + } + BsW(1,0); + } + + /*--- Now the coding tables. ---*/ + for (int t = 0; t < nGroups; ++t) { + int curr = len[t][0]; + BsW(5, curr); + for (int i = 0; i < alphaSize; ++i) { + while (curr < len[t][i]) { + BsW(2, 2); + curr++; /* 10 */ + } + while (curr > len[t][i]) { + BsW(2, 3); + curr--; /* 11 */ + } + BsW (1, 0); + } + } + + /*--- And finally, the block data proper ---*/ + selCtr = 0; + gs = 0; + while (true) { + if (gs >= nMTF) { + break; + } + ge = gs + BZip2Constants.GroupSize - 1; + if (ge >= nMTF) { + ge = nMTF - 1; + } + + for (int i = gs; i <= ge; i++) { + BsW(len[selector[selCtr]][szptr[i]], code[selector[selCtr]][szptr[i]]); + } + + gs = ge + 1; + ++selCtr; + } + if (!(selCtr == nSelectors)) { + Panic(); + } + } + + void MoveToFrontCodeAndSend () + { + BsPutIntVS(24, origPtr); + GenerateMTFValues(); + SendMTFValues(); + } + + void SimpleSort(int lo, int hi, int d) + { + int i, j, h, bigN, hp; + int v; + + bigN = hi - lo + 1; + if (bigN < 2) { + return; + } + + hp = 0; + while (increments[hp] < bigN) { + hp++; + } + hp--; + + for (; hp >= 0; hp--) { + h = increments[hp]; + + i = lo + h; + while (true) { + /*-- copy 1 --*/ + if (i > hi) + break; + v = zptr[i]; + j = i; + while (FullGtU(zptr[j-h]+d, v+d)) { + zptr[j] = zptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) + break; + } + zptr[j] = v; + i++; + + /*-- copy 2 --*/ + if (i > hi) { + break; + } + v = zptr[i]; + j = i; + while (FullGtU ( zptr[j-h]+d, v+d )) { + zptr[j] = zptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) { + break; + } + } + zptr[j] = v; + i++; + + /*-- copy 3 --*/ + if (i > hi) { + break; + } + v = zptr[i]; + j = i; + while (FullGtU ( zptr[j-h]+d, v+d)) { + zptr[j] = zptr[j-h]; + j = j - h; + if (j <= (lo + h - 1)) { + break; + } + } + zptr[j] = v; + i++; + + if (workDone > workLimit && firstAttempt) { + return; + } + } + } + } + + void Vswap(int p1, int p2, int n ) + { + int temp = 0; + while (n > 0) { + temp = zptr[p1]; + zptr[p1] = zptr[p2]; + zptr[p2] = temp; + p1++; + p2++; + n--; + } + } + + void QSort3(int loSt, int hiSt, int dSt) + { + int unLo, unHi, ltLo, gtHi, med, n, m; + int lo, hi, d; + + StackElement[] stack = new StackElement[QSORT_STACK_SIZE]; - int sp = 0; - - stack[sp].ll = loSt; - stack[sp].hh = hiSt; - stack[sp].dd = dSt; - sp++; - - while (sp > 0) { - if (sp >= QSORT_STACK_SIZE) { - Panic(); - } - - sp--; - lo = stack[sp].ll; - hi = stack[sp].hh; - d = stack[sp].dd; - - if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) { - SimpleSort(lo, hi, d); - if (workDone > workLimit && firstAttempt) { - return; - } - continue; - } - - med = Med3(block[zptr[lo] + d + 1], - block[zptr[hi ] + d + 1], - block[zptr[(lo + hi) >> 1] + d + 1]); - - unLo = ltLo = lo; - unHi = gtHi = hi; - - while (true) { - while (true) { - if (unLo > unHi) { - break; - } - n = ((int)block[zptr[unLo]+d + 1]) - med; - if (n == 0) { - int temp = zptr[unLo]; - zptr[unLo] = zptr[ltLo]; - zptr[ltLo] = temp; - ltLo++; - unLo++; - continue; - } - if (n > 0) { - break; - } - unLo++; - } + int sp = 0; + + stack[sp].ll = loSt; + stack[sp].hh = hiSt; + stack[sp].dd = dSt; + sp++; + + while (sp > 0) { + if (sp >= QSORT_STACK_SIZE) { + Panic(); + } + + sp--; + lo = stack[sp].ll; + hi = stack[sp].hh; + d = stack[sp].dd; + + if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH) { + SimpleSort(lo, hi, d); + if (workDone > workLimit && firstAttempt) { + return; + } + continue; + } + + med = Med3(block[zptr[lo] + d + 1], + block[zptr[hi ] + d + 1], + block[zptr[(lo + hi) >> 1] + d + 1]); + + unLo = ltLo = lo; + unHi = gtHi = hi; + + while (true) { + while (true) { + if (unLo > unHi) { + break; + } + n = ((int)block[zptr[unLo]+d + 1]) - med; + if (n == 0) { + int temp = zptr[unLo]; + zptr[unLo] = zptr[ltLo]; + zptr[ltLo] = temp; + ltLo++; + unLo++; + continue; + } + if (n > 0) { + break; + } + unLo++; + } - while (true) { - if (unLo > unHi) { - break; - } - n = ((int)block[zptr[unHi]+d + 1]) - med; - if (n == 0) { - int temp = zptr[unHi]; - zptr[unHi] = zptr[gtHi]; - zptr[gtHi] = temp; - gtHi--; - unHi--; - continue; - } - if (n < 0) { - break; - } - unHi--; - } + while (true) { + if (unLo > unHi) { + break; + } + n = ((int)block[zptr[unHi]+d + 1]) - med; + if (n == 0) { + int temp = zptr[unHi]; + zptr[unHi] = zptr[gtHi]; + zptr[gtHi] = temp; + gtHi--; + unHi--; + continue; + } + if (n < 0) { + break; + } + unHi--; + } - if (unLo > unHi) { - break; - } + if (unLo > unHi) { + break; + } - { - int temp = zptr[unLo]; - zptr[unLo] = zptr[unHi]; - zptr[unHi] = temp; - unLo++; - unHi--; - } - } - - if (gtHi < ltLo) { - stack[sp].ll = lo; - stack[sp].hh = hi; - stack[sp].dd = d+1; - sp++; - continue; - } - - n = ((ltLo-lo) < (unLo-ltLo)) ? (ltLo-lo) : (unLo-ltLo); - Vswap(lo, unLo-n, n); - m = ((hi-gtHi) < (gtHi-unHi)) ? (hi-gtHi) : (gtHi-unHi); - Vswap(unLo, hi-m+1, m); - - n = lo + unLo - ltLo - 1; - m = hi - (gtHi - unHi) + 1; - - stack[sp].ll = lo; - stack[sp].hh = n; - stack[sp].dd = d; - sp++; - - stack[sp].ll = n + 1; - stack[sp].hh = m - 1; - stack[sp].dd = d+1; - sp++; - - stack[sp].ll = m; - stack[sp].hh = hi; - stack[sp].dd = d; - sp++; - } - } - - void MainSort() - { - int i, j, ss, sb; - int[] runningOrder = new int[256]; - int[] copy = new int[256]; - bool[] bigDone = new bool[256]; - int c1, c2; - int numQSorted; - - /*-- - In the various block-sized structures, live data runs - from 0 to last+NUM_OVERSHOOT_BYTES inclusive. First, - set up the overshoot area for block. - --*/ - - // if (verbosity >= 4) fprintf ( stderr, " sort initialise ...\n" ); - for (i = 0; i < BZip2Constants.OvershootBytes; i++) { - block[last + i + 2] = block[(i % (last + 1)) + 1]; - } - for (i = 0; i <= last + BZip2Constants.OvershootBytes; i++) { - quadrant[i] = 0; - } - - block[0] = (byte)(block[last + 1]); - - if (last < 4000) { - /*-- - Use simpleSort(), since the full sorting mechanism - has quite a large constant overhead. - --*/ - for (i = 0; i <= last; i++) { - zptr[i] = i; - } - firstAttempt = false; - workDone = workLimit = 0; - SimpleSort(0, last, 0); - } else { - numQSorted = 0; - for (i = 0; i <= 255; i++) { - bigDone[i] = false; - } - for (i = 0; i <= 65536; i++) { - ftab[i] = 0; - } - - c1 = block[0]; - for (i = 0; i <= last; i++) { - c2 = block[i + 1]; - ftab[(c1 << 8) + c2]++; - c1 = c2; - } - - for (i = 1; i <= 65536; i++) { - ftab[i] += ftab[i - 1]; - } - - c1 = block[1]; - for (i = 0; i < last; i++) { - c2 = block[i + 2]; - j = (c1 << 8) + c2; - c1 = c2; - ftab[j]--; - zptr[ftab[j]] = i; - } - - j = ((block[last + 1]) << 8) + (block[1]); - ftab[j]--; - zptr[ftab[j]] = last; - - /*-- - Now ftab contains the first loc of every small bucket. - Calculate the running order, from smallest to largest - big bucket. - --*/ - - for (i = 0; i <= 255; i++) { - runningOrder[i] = i; - } - - int vv; - int h = 1; - do { - h = 3 * h + 1; - } while (h <= 256); - do { - h = h / 3; - for (i = h; i <= 255; i++) { - vv = runningOrder[i]; - j = i; - while ((ftab[((runningOrder[j-h])+1) << 8] - ftab[(runningOrder[j-h]) << 8]) > (ftab[((vv)+1) << 8] - ftab[(vv) << 8])) { - runningOrder[j] = runningOrder[j-h]; - j = j - h; - if (j <= (h - 1)) { - break; - } - } - runningOrder[j] = vv; - } - } while (h != 1); - - /*-- - The main sorting loop. - --*/ - for (i = 0; i <= 255; i++) { - - /*-- - Process big buckets, starting with the least full. - --*/ - ss = runningOrder[i]; - - /*-- - Complete the big bucket [ss] by quicksorting - any unsorted small buckets [ss, j]. Hopefully - previous pointer-scanning phases have already - completed many of the small buckets [ss, j], so - we don't have to sort them at all. - --*/ - for (j = 0; j <= 255; j++) { - sb = (ss << 8) + j; - if(!((ftab[sb] & SETMASK) == SETMASK)) { - int lo = ftab[sb] & CLEARMASK; - int hi = (ftab[sb+1] & CLEARMASK) - 1; - if (hi > lo) { - QSort3(lo, hi, 2); - numQSorted += (hi - lo + 1); - if (workDone > workLimit && firstAttempt) { - return; - } - } - ftab[sb] |= SETMASK; - } - } - - /*-- - The ss big bucket is now done. Record this fact, - and update the quadrant descriptors. Remember to - update quadrants in the overshoot area too, if - necessary. The "if (i < 255)" test merely skips - this updating for the last bucket processed, since - updating for the last bucket is pointless. - --*/ - bigDone[ss] = true; - - if (i < 255) { - int bbStart = ftab[ss << 8] & CLEARMASK; - int bbSize = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart; - int shifts = 0; - - while ((bbSize >> shifts) > 65534) { - shifts++; - } - - for (j = 0; j < bbSize; j++) { - int a2update = zptr[bbStart + j]; - int qVal = (j >> shifts); - quadrant[a2update] = qVal; - if (a2update < BZip2Constants.OvershootBytes) { - quadrant[a2update + last + 1] = qVal; - } - } - - if (!(((bbSize-1) >> shifts) <= 65535)) { - Panic(); - } - } - - /*-- - Now scan this big bucket so as to synthesise the - sorted order for small buckets [t, ss] for all t != ss. - --*/ - for (j = 0; j <= 255; j++) { - copy[j] = ftab[(j << 8) + ss] & CLEARMASK; - } - - for (j = ftab[ss << 8] & CLEARMASK; j < (ftab[(ss+1) << 8] & CLEARMASK); j++) { - c1 = block[zptr[j]]; - if (!bigDone[c1]) { - zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1; - copy[c1] ++; - } - } - - for (j = 0; j <= 255; j++) { - ftab[(j << 8) + ss] |= SETMASK; - } - } - } - } - - void RandomiseBlock() - { - int i; - int rNToGo = 0; - int rTPos = 0; - for (i = 0; i < 256; i++) { - inUse[i] = false; - } - - for (i = 0; i <= last; i++) { - if (rNToGo == 0) { - rNToGo = (int)BZip2Constants.RandomNumbers[rTPos]; - rTPos++; - if (rTPos == 512) { - rTPos = 0; - } - } - rNToGo--; - block[i + 1] ^= (byte)((rNToGo == 1) ? 1 : 0); - // handle 16 bit signed numbers - block[i + 1] &= 0xFF; - - inUse[block[i + 1]] = true; - } - } - - void DoReversibleTransformation() - { - workLimit = workFactor * last; - workDone = 0; - blockRandomised = false; - firstAttempt = true; - - MainSort(); - - if (workDone > workLimit && firstAttempt) { - RandomiseBlock(); - workLimit = workDone = 0; - blockRandomised = true; - firstAttempt = false; - MainSort(); - } - - origPtr = -1; - for (int i = 0; i <= last; i++) { - if (zptr[i] == 0) { - origPtr = i; - break; - } - } - - if (origPtr == -1) { - Panic(); - } - } - - bool FullGtU(int i1, int i2) - { - int k; - byte c1, c2; - int s1, s2; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - i1++; - i2++; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - i1++; - i2++; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - i1++; - i2++; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - i1++; - i2++; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - i1++; - i2++; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - i1++; - i2++; - - k = last + 1; - - do { - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - s1 = quadrant[i1]; - s2 = quadrant[i2]; - if (s1 != s2) { - return s1 > s2; - } - i1++; - i2++; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - s1 = quadrant[i1]; - s2 = quadrant[i2]; - if (s1 != s2) { - return s1 > s2; - } - i1++; - i2++; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - s1 = quadrant[i1]; - s2 = quadrant[i2]; - if (s1 != s2) { - return s1 > s2; - } - i1++; - i2++; - - c1 = block[i1 + 1]; - c2 = block[i2 + 1]; - if (c1 != c2) { - return c1 > c2; - } - s1 = quadrant[i1]; - s2 = quadrant[i2]; - if (s1 != s2) { - return s1 > s2; - } - i1++; - i2++; - - if (i1 > last) { - i1 -= last; - i1--; - } - if (i2 > last) { - i2 -= last; - i2--; - } - - k -= 4; - ++workDone; - } while (k >= 0); - - return false; - } - - void AllocateCompressStructures() - { - int n = BZip2Constants.BaseBlockSize * blockSize100k; - block = new byte[(n + 1 + BZip2Constants.OvershootBytes)]; - quadrant = new int[(n + BZip2Constants.OvershootBytes)]; - zptr = new int[n]; - ftab = new int[65537]; - - if (block == null || quadrant == null || zptr == null || ftab == null) { - // int totalDraw = (n + 1 + NUM_OVERSHOOT_BYTES) + (n + NUM_OVERSHOOT_BYTES) + n + 65537; - // compressOutOfMemory ( totalDraw, n ); - } - - /* - The back end needs a place to store the MTF values - whilst it calculates the coding tables. We could - put them in the zptr array. However, these values - will fit in a short, so we overlay szptr at the - start of zptr, in the hope of reducing the number - of cache misses induced by the multiple traversals - of the MTF values when calculating coding tables. - Seems to improve compression speed by about 1%. - */ - // szptr = zptr; - - - szptr = new short[2 * n]; - } - - void GenerateMTFValues() - { - char[] yy = new char[256]; - int i, j; - char tmp; - char tmp2; - int zPend; - int wr; - int EOB; - - MakeMaps(); - EOB = nInUse+1; - - for (i = 0; i <= EOB; i++) { - mtfFreq[i] = 0; - } - - wr = 0; - zPend = 0; - for (i = 0; i < nInUse; i++) { - yy[i] = (char) i; - } - - - for (i = 0; i <= last; i++) { - char ll_i; - - ll_i = unseqToSeq[block[zptr[i]]]; - - j = 0; - tmp = yy[j]; - while (ll_i != tmp) { - j++; - tmp2 = tmp; - tmp = yy[j]; - yy[j] = tmp2; - } - yy[0] = tmp; - - if (j == 0) { - zPend++; - } else { - if (zPend > 0) { - zPend--; - while (true) { - switch (zPend % 2) { - case 0: - szptr[wr] = (short)BZip2Constants.RunA; - wr++; - mtfFreq[BZip2Constants.RunA]++; - break; - case 1: - szptr[wr] = (short)BZip2Constants.RunB; - wr++; - mtfFreq[BZip2Constants.RunB]++; - break; - } - if (zPend < 2) { - break; - } - zPend = (zPend - 2) / 2; - } - zPend = 0; - } - szptr[wr] = (short)(j + 1); - wr++; - mtfFreq[j + 1]++; - } - } - - if (zPend > 0) { - zPend--; - while (true) { - switch (zPend % 2) { - case 0: - szptr[wr] = (short)BZip2Constants.RunA; - wr++; - mtfFreq[BZip2Constants.RunA]++; - break; - case 1: - szptr[wr] = (short)BZip2Constants.RunB; - wr++; - mtfFreq[BZip2Constants.RunB]++; - break; - } - if (zPend < 2) { - break; - } - zPend = (zPend - 2) / 2; - } - } - - szptr[wr] = (short)EOB; - wr++; - mtfFreq[EOB]++; - - nMTF = wr; - } + { + int temp = zptr[unLo]; + zptr[unLo] = zptr[unHi]; + zptr[unHi] = temp; + unLo++; + unHi--; + } + } + + if (gtHi < ltLo) { + stack[sp].ll = lo; + stack[sp].hh = hi; + stack[sp].dd = d+1; + sp++; + continue; + } + + n = ((ltLo-lo) < (unLo-ltLo)) ? (ltLo-lo) : (unLo-ltLo); + Vswap(lo, unLo-n, n); + m = ((hi-gtHi) < (gtHi-unHi)) ? (hi-gtHi) : (gtHi-unHi); + Vswap(unLo, hi-m+1, m); + + n = lo + unLo - ltLo - 1; + m = hi - (gtHi - unHi) + 1; + + stack[sp].ll = lo; + stack[sp].hh = n; + stack[sp].dd = d; + sp++; + + stack[sp].ll = n + 1; + stack[sp].hh = m - 1; + stack[sp].dd = d+1; + sp++; + + stack[sp].ll = m; + stack[sp].hh = hi; + stack[sp].dd = d; + sp++; + } + } + + void MainSort() + { + int i, j, ss, sb; + int[] runningOrder = new int[256]; + int[] copy = new int[256]; + bool[] bigDone = new bool[256]; + int c1, c2; + int numQSorted; + + /*-- + In the various block-sized structures, live data runs + from 0 to last+NUM_OVERSHOOT_BYTES inclusive. First, + set up the overshoot area for block. + --*/ + + // if (verbosity >= 4) fprintf ( stderr, " sort initialise ...\n" ); + for (i = 0; i < BZip2Constants.OvershootBytes; i++) { + block[last + i + 2] = block[(i % (last + 1)) + 1]; + } + for (i = 0; i <= last + BZip2Constants.OvershootBytes; i++) { + quadrant[i] = 0; + } + + block[0] = (byte)(block[last + 1]); + + if (last < 4000) { + /*-- + Use simpleSort(), since the full sorting mechanism + has quite a large constant overhead. + --*/ + for (i = 0; i <= last; i++) { + zptr[i] = i; + } + firstAttempt = false; + workDone = workLimit = 0; + SimpleSort(0, last, 0); + } else { + numQSorted = 0; + for (i = 0; i <= 255; i++) { + bigDone[i] = false; + } + for (i = 0; i <= 65536; i++) { + ftab[i] = 0; + } + + c1 = block[0]; + for (i = 0; i <= last; i++) { + c2 = block[i + 1]; + ftab[(c1 << 8) + c2]++; + c1 = c2; + } + + for (i = 1; i <= 65536; i++) { + ftab[i] += ftab[i - 1]; + } + + c1 = block[1]; + for (i = 0; i < last; i++) { + c2 = block[i + 2]; + j = (c1 << 8) + c2; + c1 = c2; + ftab[j]--; + zptr[ftab[j]] = i; + } + + j = ((block[last + 1]) << 8) + (block[1]); + ftab[j]--; + zptr[ftab[j]] = last; + + /*-- + Now ftab contains the first loc of every small bucket. + Calculate the running order, from smallest to largest + big bucket. + --*/ + + for (i = 0; i <= 255; i++) { + runningOrder[i] = i; + } + + int vv; + int h = 1; + do { + h = 3 * h + 1; + } while (h <= 256); + do { + h = h / 3; + for (i = h; i <= 255; i++) { + vv = runningOrder[i]; + j = i; + while ((ftab[((runningOrder[j-h])+1) << 8] - ftab[(runningOrder[j-h]) << 8]) > (ftab[((vv)+1) << 8] - ftab[(vv) << 8])) { + runningOrder[j] = runningOrder[j-h]; + j = j - h; + if (j <= (h - 1)) { + break; + } + } + runningOrder[j] = vv; + } + } while (h != 1); + + /*-- + The main sorting loop. + --*/ + for (i = 0; i <= 255; i++) { + + /*-- + Process big buckets, starting with the least full. + --*/ + ss = runningOrder[i]; + + /*-- + Complete the big bucket [ss] by quicksorting + any unsorted small buckets [ss, j]. Hopefully + previous pointer-scanning phases have already + completed many of the small buckets [ss, j], so + we don't have to sort them at all. + --*/ + for (j = 0; j <= 255; j++) { + sb = (ss << 8) + j; + if(!((ftab[sb] & SETMASK) == SETMASK)) { + int lo = ftab[sb] & CLEARMASK; + int hi = (ftab[sb+1] & CLEARMASK) - 1; + if (hi > lo) { + QSort3(lo, hi, 2); + numQSorted += (hi - lo + 1); + if (workDone > workLimit && firstAttempt) { + return; + } + } + ftab[sb] |= SETMASK; + } + } + + /*-- + The ss big bucket is now done. Record this fact, + and update the quadrant descriptors. Remember to + update quadrants in the overshoot area too, if + necessary. The "if (i < 255)" test merely skips + this updating for the last bucket processed, since + updating for the last bucket is pointless. + --*/ + bigDone[ss] = true; + + if (i < 255) { + int bbStart = ftab[ss << 8] & CLEARMASK; + int bbSize = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart; + int shifts = 0; + + while ((bbSize >> shifts) > 65534) { + shifts++; + } + + for (j = 0; j < bbSize; j++) { + int a2update = zptr[bbStart + j]; + int qVal = (j >> shifts); + quadrant[a2update] = qVal; + if (a2update < BZip2Constants.OvershootBytes) { + quadrant[a2update + last + 1] = qVal; + } + } + + if (!(((bbSize-1) >> shifts) <= 65535)) { + Panic(); + } + } + + /*-- + Now scan this big bucket so as to synthesise the + sorted order for small buckets [t, ss] for all t != ss. + --*/ + for (j = 0; j <= 255; j++) { + copy[j] = ftab[(j << 8) + ss] & CLEARMASK; + } + + for (j = ftab[ss << 8] & CLEARMASK; j < (ftab[(ss+1) << 8] & CLEARMASK); j++) { + c1 = block[zptr[j]]; + if (!bigDone[c1]) { + zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1; + copy[c1] ++; + } + } + + for (j = 0; j <= 255; j++) { + ftab[(j << 8) + ss] |= SETMASK; + } + } + } + } + + void RandomiseBlock() + { + int i; + int rNToGo = 0; + int rTPos = 0; + for (i = 0; i < 256; i++) { + inUse[i] = false; + } + + for (i = 0; i <= last; i++) { + if (rNToGo == 0) { + rNToGo = (int)BZip2Constants.RandomNumbers[rTPos]; + rTPos++; + if (rTPos == 512) { + rTPos = 0; + } + } + rNToGo--; + block[i + 1] ^= (byte)((rNToGo == 1) ? 1 : 0); + // handle 16 bit signed numbers + block[i + 1] &= 0xFF; + + inUse[block[i + 1]] = true; + } + } + + void DoReversibleTransformation() + { + workLimit = workFactor * last; + workDone = 0; + blockRandomised = false; + firstAttempt = true; + + MainSort(); + + if (workDone > workLimit && firstAttempt) { + RandomiseBlock(); + workLimit = workDone = 0; + blockRandomised = true; + firstAttempt = false; + MainSort(); + } + + origPtr = -1; + for (int i = 0; i <= last; i++) { + if (zptr[i] == 0) { + origPtr = i; + break; + } + } + + if (origPtr == -1) { + Panic(); + } + } + + bool FullGtU(int i1, int i2) + { + int k; + byte c1, c2; + int s1, s2; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + i1++; + i2++; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + i1++; + i2++; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + i1++; + i2++; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + i1++; + i2++; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + i1++; + i2++; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + i1++; + i2++; + + k = last + 1; + + do { + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + s1 = quadrant[i1]; + s2 = quadrant[i2]; + if (s1 != s2) { + return s1 > s2; + } + i1++; + i2++; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + s1 = quadrant[i1]; + s2 = quadrant[i2]; + if (s1 != s2) { + return s1 > s2; + } + i1++; + i2++; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + s1 = quadrant[i1]; + s2 = quadrant[i2]; + if (s1 != s2) { + return s1 > s2; + } + i1++; + i2++; + + c1 = block[i1 + 1]; + c2 = block[i2 + 1]; + if (c1 != c2) { + return c1 > c2; + } + s1 = quadrant[i1]; + s2 = quadrant[i2]; + if (s1 != s2) { + return s1 > s2; + } + i1++; + i2++; + + if (i1 > last) { + i1 -= last; + i1--; + } + if (i2 > last) { + i2 -= last; + i2--; + } + + k -= 4; + ++workDone; + } while (k >= 0); + + return false; + } + + void AllocateCompressStructures() + { + int n = BZip2Constants.BaseBlockSize * blockSize100k; + block = new byte[(n + 1 + BZip2Constants.OvershootBytes)]; + quadrant = new int[(n + BZip2Constants.OvershootBytes)]; + zptr = new int[n]; + ftab = new int[65537]; + + if (block == null || quadrant == null || zptr == null || ftab == null) { + // int totalDraw = (n + 1 + NUM_OVERSHOOT_BYTES) + (n + NUM_OVERSHOOT_BYTES) + n + 65537; + // compressOutOfMemory ( totalDraw, n ); + } + + /* + The back end needs a place to store the MTF values + whilst it calculates the coding tables. We could + put them in the zptr array. However, these values + will fit in a short, so we overlay szptr at the + start of zptr, in the hope of reducing the number + of cache misses induced by the multiple traversals + of the MTF values when calculating coding tables. + Seems to improve compression speed by about 1%. + */ + // szptr = zptr; + + + szptr = new short[2 * n]; + } + + void GenerateMTFValues() + { + char[] yy = new char[256]; + int i, j; + char tmp; + char tmp2; + int zPend; + int wr; + int EOB; + + MakeMaps(); + EOB = nInUse+1; + + for (i = 0; i <= EOB; i++) { + mtfFreq[i] = 0; + } + + wr = 0; + zPend = 0; + for (i = 0; i < nInUse; i++) { + yy[i] = (char) i; + } + + + for (i = 0; i <= last; i++) { + char ll_i; + + ll_i = unseqToSeq[block[zptr[i]]]; + + j = 0; + tmp = yy[j]; + while (ll_i != tmp) { + j++; + tmp2 = tmp; + tmp = yy[j]; + yy[j] = tmp2; + } + yy[0] = tmp; + + if (j == 0) { + zPend++; + } else { + if (zPend > 0) { + zPend--; + while (true) { + switch (zPend % 2) { + case 0: + szptr[wr] = (short)BZip2Constants.RunA; + wr++; + mtfFreq[BZip2Constants.RunA]++; + break; + case 1: + szptr[wr] = (short)BZip2Constants.RunB; + wr++; + mtfFreq[BZip2Constants.RunB]++; + break; + } + if (zPend < 2) { + break; + } + zPend = (zPend - 2) / 2; + } + zPend = 0; + } + szptr[wr] = (short)(j + 1); + wr++; + mtfFreq[j + 1]++; + } + } + + if (zPend > 0) { + zPend--; + while (true) { + switch (zPend % 2) { + case 0: + szptr[wr] = (short)BZip2Constants.RunA; + wr++; + mtfFreq[BZip2Constants.RunA]++; + break; + case 1: + szptr[wr] = (short)BZip2Constants.RunB; + wr++; + mtfFreq[BZip2Constants.RunB]++; + break; + } + if (zPend < 2) { + break; + } + zPend = (zPend - 2) / 2; + } + } + + szptr[wr] = (short)EOB; + wr++; + mtfFreq[EOB]++; + + nMTF = wr; + } - static void Panic() - { - throw new BZip2Exception("BZip2 output stream panic"); - } - - static void HbMakeCodeLengths(char[] len, int[] freq, int alphaSize, int maxLen) - { - /*-- - Nodes and heap entries run from 1. Entry 0 - for both the heap and nodes is a sentinel. - --*/ - int nNodes, nHeap, n1, n2, j, k; - bool tooLong; - - int[] heap = new int[BZip2Constants.MaximumAlphaSize + 2]; - int[] weight = new int[BZip2Constants.MaximumAlphaSize * 2]; - int[] parent = new int[BZip2Constants.MaximumAlphaSize * 2]; - - for (int i = 0; i < alphaSize; ++i) - { - weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8; - } - - while (true) - { - nNodes = alphaSize; - nHeap = 0; - - heap[0] = 0; - weight[0] = 0; - parent[0] = -2; - - for (int i = 1; i <= alphaSize; ++i) - { - parent[i] = -1; - nHeap++; - heap[nHeap] = i; - int zz = nHeap; - int tmp = heap[zz]; - while (weight[tmp] < weight[heap[zz >> 1]]) - { - heap[zz] = heap[zz >> 1]; - zz >>= 1; - } - heap[zz] = tmp; - } - if (!(nHeap < (BZip2Constants.MaximumAlphaSize+2))) - { - Panic(); - } - - while (nHeap > 1) - { - n1 = heap[1]; - heap[1] = heap[nHeap]; - nHeap--; - int zz = 1; - int yy = 0; - int tmp = heap[zz]; - while (true) - { - yy = zz << 1; - if (yy > nHeap) - { - break; - } - if (yy < nHeap && weight[heap[yy+1]] < weight[heap[yy]]) - { - yy++; - } - if (weight[tmp] < weight[heap[yy]]) - { - break; - } - - heap[zz] = heap[yy]; - zz = yy; - } - heap[zz] = tmp; - n2 = heap[1]; - heap[1] = heap[nHeap]; - nHeap--; - - zz = 1; - yy = 0; - tmp = heap[zz]; - while (true) - { - yy = zz << 1; - if (yy > nHeap) - { - break; - } - if (yy < nHeap && weight[heap[yy+1]] < weight[heap[yy]]) - { - yy++; - } - if (weight[tmp] < weight[heap[yy]]) - { - break; - } - heap[zz] = heap[yy]; - zz = yy; - } - heap[zz] = tmp; - nNodes++; - parent[n1] = parent[n2] = nNodes; - - weight[nNodes] = (int)((weight[n1] & 0xffffff00) + (weight[n2] & 0xffffff00)) | - (int)(1 + (((weight[n1] & 0x000000ff) > (weight[n2] & 0x000000ff)) ? (weight[n1] & 0x000000ff) : (weight[n2] & 0x000000ff))); - - parent[nNodes] = -1; - nHeap++; - heap[nHeap] = nNodes; - - zz = nHeap; - tmp = heap[zz]; - while (weight[tmp] < weight[heap[zz >> 1]]) - { - heap[zz] = heap[zz >> 1]; - zz >>= 1; - } - heap[zz] = tmp; - } - if (!(nNodes < (BZip2Constants.MaximumAlphaSize * 2))) - { - Panic(); - } - - tooLong = false; - for (int i = 1; i <= alphaSize; ++i) - { - j = 0; - k = i; - while (parent[k] >= 0) - { - k = parent[k]; - j++; - } - len[i - 1] = (char)j; - if (j > maxLen) - { - tooLong = true; - } - } - - if (!tooLong) - { - break; - } - - for (int i = 1; i < alphaSize; ++i) - { - j = weight[i] >> 8; - j = 1 + (j / 2); - weight[i] = j << 8; - } - } - } - - static void HbAssignCodes (int[] code, char[] length, int minLen, int maxLen, int alphaSize) - { - int vec = 0; - for (int n = minLen; n <= maxLen; ++n) - { - for (int i = 0; i < alphaSize; ++i) - { - if (length[i] == n) - { - code[i] = vec; - ++vec; - } - } - vec <<= 1; - } - } - - static byte Med3(byte a, byte b, byte c ) - { - byte t; - if (a > b) - { - t = a; - a = b; - b = t; - } - if (b > c) - { - t = b; - b = c; - c = t; - } - if (a > b) - { - b = a; - } - return b; - } + static void Panic() + { + throw new BZip2Exception("BZip2 output stream panic"); + } + + static void HbMakeCodeLengths(char[] len, int[] freq, int alphaSize, int maxLen) + { + /*-- + Nodes and heap entries run from 1. Entry 0 + for both the heap and nodes is a sentinel. + --*/ + int nNodes, nHeap, n1, n2, j, k; + bool tooLong; + + int[] heap = new int[BZip2Constants.MaximumAlphaSize + 2]; + int[] weight = new int[BZip2Constants.MaximumAlphaSize * 2]; + int[] parent = new int[BZip2Constants.MaximumAlphaSize * 2]; + + for (int i = 0; i < alphaSize; ++i) + { + weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8; + } + + while (true) + { + nNodes = alphaSize; + nHeap = 0; + + heap[0] = 0; + weight[0] = 0; + parent[0] = -2; + + for (int i = 1; i <= alphaSize; ++i) + { + parent[i] = -1; + nHeap++; + heap[nHeap] = i; + int zz = nHeap; + int tmp = heap[zz]; + while (weight[tmp] < weight[heap[zz >> 1]]) + { + heap[zz] = heap[zz >> 1]; + zz >>= 1; + } + heap[zz] = tmp; + } + if (!(nHeap < (BZip2Constants.MaximumAlphaSize+2))) + { + Panic(); + } + + while (nHeap > 1) + { + n1 = heap[1]; + heap[1] = heap[nHeap]; + nHeap--; + int zz = 1; + int yy = 0; + int tmp = heap[zz]; + while (true) + { + yy = zz << 1; + if (yy > nHeap) + { + break; + } + if (yy < nHeap && weight[heap[yy+1]] < weight[heap[yy]]) + { + yy++; + } + if (weight[tmp] < weight[heap[yy]]) + { + break; + } + + heap[zz] = heap[yy]; + zz = yy; + } + heap[zz] = tmp; + n2 = heap[1]; + heap[1] = heap[nHeap]; + nHeap--; + + zz = 1; + yy = 0; + tmp = heap[zz]; + while (true) + { + yy = zz << 1; + if (yy > nHeap) + { + break; + } + if (yy < nHeap && weight[heap[yy+1]] < weight[heap[yy]]) + { + yy++; + } + if (weight[tmp] < weight[heap[yy]]) + { + break; + } + heap[zz] = heap[yy]; + zz = yy; + } + heap[zz] = tmp; + nNodes++; + parent[n1] = parent[n2] = nNodes; + + weight[nNodes] = (int)((weight[n1] & 0xffffff00) + (weight[n2] & 0xffffff00)) | + (int)(1 + (((weight[n1] & 0x000000ff) > (weight[n2] & 0x000000ff)) ? (weight[n1] & 0x000000ff) : (weight[n2] & 0x000000ff))); + + parent[nNodes] = -1; + nHeap++; + heap[nHeap] = nNodes; + + zz = nHeap; + tmp = heap[zz]; + while (weight[tmp] < weight[heap[zz >> 1]]) + { + heap[zz] = heap[zz >> 1]; + zz >>= 1; + } + heap[zz] = tmp; + } + if (!(nNodes < (BZip2Constants.MaximumAlphaSize * 2))) + { + Panic(); + } + + tooLong = false; + for (int i = 1; i <= alphaSize; ++i) + { + j = 0; + k = i; + while (parent[k] >= 0) + { + k = parent[k]; + j++; + } + len[i - 1] = (char)j; + if (j > maxLen) + { + tooLong = true; + } + } + + if (!tooLong) + { + break; + } + + for (int i = 1; i < alphaSize; ++i) + { + j = weight[i] >> 8; + j = 1 + (j / 2); + weight[i] = j << 8; + } + } + } + + static void HbAssignCodes (int[] code, char[] length, int minLen, int maxLen, int alphaSize) + { + int vec = 0; + for (int n = minLen; n <= maxLen; ++n) + { + for (int i = 0; i < alphaSize; ++i) + { + if (length[i] == n) + { + code[i] = vec; + ++vec; + } + } + vec <<= 1; + } + } + + static byte Med3(byte a, byte b, byte c ) + { + byte t; + if (a > b) + { + t = a; + a = b; + b = t; + } + if (b > c) + { + t = b; + b = c; + c = t; + } + if (a > b) + { + b = a; + } + return b; + } - struct StackElement - { - public int ll; - public int hh; - public int dd; - } - - #region Instance Fields - bool isStreamOwner = true; - - /*-- - index of the last char in the block, so - the block size == last + 1. - --*/ - int last; - - /*-- - index in zptr[] of original string after sorting. - --*/ - int origPtr; - - /*-- - always: in the range 0 .. 9. - The current block size is 100000 * this number. - --*/ - int blockSize100k; - - bool blockRandomised; - - int bytesOut; - int bsBuff; - int bsLive; - IChecksum mCrc = new StrangeCRC(); - - bool[] inUse = new bool[256]; - int nInUse; - - char[] seqToUnseq = new char[256]; - char[] unseqToSeq = new char[256]; - - char[] selector = new char[BZip2Constants.MaximumSelectors]; - char[] selectorMtf = new char[BZip2Constants.MaximumSelectors]; - - byte[] block; - int[] quadrant; - int[] zptr; - short[] szptr; - int[] ftab; - - int nMTF; - - int[] mtfFreq = new int[BZip2Constants.MaximumAlphaSize]; - - /* - * Used when sorting. If too many long comparisons - * happen, we stop sorting, randomise the block - * slightly, and try again. - */ - int workFactor; - int workDone; - int workLimit; - bool firstAttempt; - int nBlocksRandomised; - - int currentChar = -1; - int runLength; - uint blockCRC, combinedCRC; - int allowableBlockSize; - Stream baseStream; - bool disposed_; - #endregion - } + struct StackElement + { + public int ll; + public int hh; + public int dd; + } + + #region Instance Fields + bool isStreamOwner = true; + + /*-- + index of the last char in the block, so + the block size == last + 1. + --*/ + int last; + + /*-- + index in zptr[] of original string after sorting. + --*/ + int origPtr; + + /*-- + always: in the range 0 .. 9. + The current block size is 100000 * this number. + --*/ + int blockSize100k; + + bool blockRandomised; + + int bytesOut; + int bsBuff; + int bsLive; + IChecksum mCrc = new StrangeCRC(); + + bool[] inUse = new bool[256]; + int nInUse; + + char[] seqToUnseq = new char[256]; + char[] unseqToSeq = new char[256]; + + char[] selector = new char[BZip2Constants.MaximumSelectors]; + char[] selectorMtf = new char[BZip2Constants.MaximumSelectors]; + + byte[] block; + int[] quadrant; + int[] zptr; + short[] szptr; + int[] ftab; + + int nMTF; + + int[] mtfFreq = new int[BZip2Constants.MaximumAlphaSize]; + + /* + * Used when sorting. If too many long comparisons + * happen, we stop sorting, randomise the block + * slightly, and try again. + */ + int workFactor; + int workDone; + int workLimit; + bool firstAttempt; + int nBlocksRandomised; + + int currentChar = -1; + int runLength; + uint blockCRC, combinedCRC; + int allowableBlockSize; + Stream baseStream; + bool disposed_; + #endregion + } } /* This file was derived from a file containing this license: diff --git a/External/Tools/AppMan/ZipLib/Checksums/Adler32.cs b/External/Tools/AppMan/ZipLib/Checksums/Adler32.cs index 6e358bc083..7dafb9cd37 100644 --- a/External/Tools/AppMan/ZipLib/Checksums/Adler32.cs +++ b/External/Tools/AppMan/ZipLib/Checksums/Adler32.cs @@ -39,199 +39,199 @@ namespace ICSharpCode.SharpZipLib.Checksums { - - /// - /// Computes Adler32 checksum for a stream of data. An Adler32 - /// checksum is not as reliable as a CRC32 checksum, but a lot faster to - /// compute. - /// - /// The specification for Adler32 may be found in RFC 1950. - /// ZLIB Compressed Data Format Specification version 3.3) - /// - /// - /// From that document: - /// - /// "ADLER32 (Adler-32 checksum) - /// This contains a checksum value of the uncompressed data - /// (excluding any dictionary data) computed according to Adler-32 - /// algorithm. This algorithm is a 32-bit extension and improvement - /// of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073 - /// standard. - /// - /// Adler-32 is composed of two sums accumulated per byte: s1 is - /// the sum of all bytes, s2 is the sum of all s1 values. Both sums - /// are done modulo 65521. s1 is initialized to 1, s2 to zero. The - /// Adler-32 checksum is stored as s2*65536 + s1 in most- - /// significant-byte first (network) order." - /// - /// "8.2. The Adler-32 algorithm - /// - /// The Adler-32 algorithm is much faster than the CRC32 algorithm yet - /// still provides an extremely low probability of undetected errors. - /// - /// The modulo on unsigned long accumulators can be delayed for 5552 - /// bytes, so the modulo operation time is negligible. If the bytes - /// are a, b, c, the second sum is 3a + 2b + c + 3, and so is position - /// and order sensitive, unlike the first sum, which is just a - /// checksum. That 65521 is prime is important to avoid a possible - /// large class of two-byte errors that leave the check unchanged. - /// (The Fletcher checksum uses 255, which is not prime and which also - /// makes the Fletcher check insensitive to single byte changes 0 - - /// 255.) - /// - /// The sum s1 is initialized to 1 instead of zero to make the length - /// of the sequence part of s2, so that the length does not have to be - /// checked separately. (Any sequence of zeroes has a Fletcher - /// checksum of zero.)" - /// - /// - /// - public sealed class Adler32 : IChecksum - { - /// - /// largest prime smaller than 65536 - /// - const uint BASE = 65521; - - /// - /// Returns the Adler32 data checksum computed so far. - /// - public long Value { - get { - return checksum; - } - } - - /// - /// Creates a new instance of the Adler32 class. - /// The checksum starts off with a value of 1. - /// - public Adler32() - { - Reset(); - } - - /// - /// Resets the Adler32 checksum to the initial value. - /// - public void Reset() - { - checksum = 1; - } - - /// - /// Updates the checksum with a byte value. - /// - /// - /// The data value to add. The high byte of the int is ignored. - /// - public void Update(int value) - { - // We could make a length 1 byte array and call update again, but I - // would rather not have that overhead - uint s1 = checksum & 0xFFFF; - uint s2 = checksum >> 16; - - s1 = (s1 + ((uint)value & 0xFF)) % BASE; - s2 = (s1 + s2) % BASE; - - checksum = (s2 << 16) + s1; - } - - /// - /// Updates the checksum with an array of bytes. - /// - /// - /// The source of the data to update with. - /// - public void Update(byte[] buffer) - { - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } + + /// + /// Computes Adler32 checksum for a stream of data. An Adler32 + /// checksum is not as reliable as a CRC32 checksum, but a lot faster to + /// compute. + /// + /// The specification for Adler32 may be found in RFC 1950. + /// ZLIB Compressed Data Format Specification version 3.3) + /// + /// + /// From that document: + /// + /// "ADLER32 (Adler-32 checksum) + /// This contains a checksum value of the uncompressed data + /// (excluding any dictionary data) computed according to Adler-32 + /// algorithm. This algorithm is a 32-bit extension and improvement + /// of the Fletcher algorithm, used in the ITU-T X.224 / ISO 8073 + /// standard. + /// + /// Adler-32 is composed of two sums accumulated per byte: s1 is + /// the sum of all bytes, s2 is the sum of all s1 values. Both sums + /// are done modulo 65521. s1 is initialized to 1, s2 to zero. The + /// Adler-32 checksum is stored as s2*65536 + s1 in most- + /// significant-byte first (network) order." + /// + /// "8.2. The Adler-32 algorithm + /// + /// The Adler-32 algorithm is much faster than the CRC32 algorithm yet + /// still provides an extremely low probability of undetected errors. + /// + /// The modulo on unsigned long accumulators can be delayed for 5552 + /// bytes, so the modulo operation time is negligible. If the bytes + /// are a, b, c, the second sum is 3a + 2b + c + 3, and so is position + /// and order sensitive, unlike the first sum, which is just a + /// checksum. That 65521 is prime is important to avoid a possible + /// large class of two-byte errors that leave the check unchanged. + /// (The Fletcher checksum uses 255, which is not prime and which also + /// makes the Fletcher check insensitive to single byte changes 0 - + /// 255.) + /// + /// The sum s1 is initialized to 1 instead of zero to make the length + /// of the sequence part of s2, so that the length does not have to be + /// checked separately. (Any sequence of zeroes has a Fletcher + /// checksum of zero.)" + /// + /// + /// + public sealed class Adler32 : IChecksum + { + /// + /// largest prime smaller than 65536 + /// + const uint BASE = 65521; + + /// + /// Returns the Adler32 data checksum computed so far. + /// + public long Value { + get { + return checksum; + } + } + + /// + /// Creates a new instance of the Adler32 class. + /// The checksum starts off with a value of 1. + /// + public Adler32() + { + Reset(); + } + + /// + /// Resets the Adler32 checksum to the initial value. + /// + public void Reset() + { + checksum = 1; + } + + /// + /// Updates the checksum with a byte value. + /// + /// + /// The data value to add. The high byte of the int is ignored. + /// + public void Update(int value) + { + // We could make a length 1 byte array and call update again, but I + // would rather not have that overhead + uint s1 = checksum & 0xFFFF; + uint s2 = checksum >> 16; + + s1 = (s1 + ((uint)value & 0xFF)) % BASE; + s2 = (s1 + s2) % BASE; + + checksum = (s2 << 16) + s1; + } + + /// + /// Updates the checksum with an array of bytes. + /// + /// + /// The source of the data to update with. + /// + public void Update(byte[] buffer) + { + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } - Update(buffer, 0, buffer.Length); - } - - /// - /// Updates the checksum with the bytes taken from the array. - /// - /// - /// an array of bytes - /// - /// - /// the start of the data used for this update - /// - /// - /// the number of bytes to use for this update - /// - public void Update(byte[] buffer, int offset, int count) - { - if (buffer == null) { - throw new ArgumentNullException("buffer"); - } - - if (offset < 0) { + Update(buffer, 0, buffer.Length); + } + + /// + /// Updates the checksum with the bytes taken from the array. + /// + /// + /// an array of bytes + /// + /// + /// the start of the data used for this update + /// + /// + /// the number of bytes to use for this update + /// + public void Update(byte[] buffer, int offset, int count) + { + if (buffer == null) { + throw new ArgumentNullException("buffer"); + } + + if (offset < 0) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "cannot be negative"); -#endif - } + throw new ArgumentOutOfRangeException("offset", "cannot be negative"); +#endif + } - if ( count < 0 ) - { + if ( count < 0 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "cannot be negative"); -#endif - } + throw new ArgumentOutOfRangeException("count", "cannot be negative"); +#endif + } - if (offset >= buffer.Length) - { + if (offset >= buffer.Length) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "not a valid index into buffer"); -#endif - } - - if (offset + count > buffer.Length) - { + throw new ArgumentOutOfRangeException("offset", "not a valid index into buffer"); +#endif + } + + if (offset + count > buffer.Length) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "exceeds buffer size"); -#endif - } + throw new ArgumentOutOfRangeException("count", "exceeds buffer size"); +#endif + } - //(By Per Bothner) - uint s1 = checksum & 0xFFFF; - uint s2 = checksum >> 16; - - while (count > 0) { - // We can defer the modulo operation: - // s1 maximally grows from 65521 to 65521 + 255 * 3800 - // s2 maximally grows by 3800 * median(s1) = 2090079800 < 2^31 - int n = 3800; - if (n > count) { - n = count; - } - count -= n; - while (--n >= 0) { - s1 = s1 + (uint)(buffer[offset++] & 0xff); - s2 = s2 + s1; - } - s1 %= BASE; - s2 %= BASE; - } - - checksum = (s2 << 16) | s1; - } - - #region Instance Fields - uint checksum; - #endregion - } + //(By Per Bothner) + uint s1 = checksum & 0xFFFF; + uint s2 = checksum >> 16; + + while (count > 0) { + // We can defer the modulo operation: + // s1 maximally grows from 65521 to 65521 + 255 * 3800 + // s2 maximally grows by 3800 * median(s1) = 2090079800 < 2^31 + int n = 3800; + if (n > count) { + n = count; + } + count -= n; + while (--n >= 0) { + s1 = s1 + (uint)(buffer[offset++] & 0xff); + s2 = s2 + s1; + } + s1 %= BASE; + s2 %= BASE; + } + + checksum = (s2 << 16) | s1; + } + + #region Instance Fields + uint checksum; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Checksums/CRC32.cs b/External/Tools/AppMan/ZipLib/Checksums/CRC32.cs index 41d5b4bc25..2b5fa4ff6e 100644 --- a/External/Tools/AppMan/ZipLib/Checksums/CRC32.cs +++ b/External/Tools/AppMan/ZipLib/Checksums/CRC32.cs @@ -39,185 +39,185 @@ namespace ICSharpCode.SharpZipLib.Checksums { - - /// - /// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: - /// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - /// - /// Polynomials over GF(2) are represented in binary, one bit per coefficient, - /// with the lowest powers in the most significant bit. Then adding polynomials - /// is just exclusive-or, and multiplying a polynomial by x is a right shift by - /// one. If we call the above polynomial p, and represent a byte as the - /// polynomial q, also with the lowest power in the most significant bit (so the - /// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, - /// where a mod b means the remainder after dividing a by b. - /// - /// This calculation is done using the shift-register method of multiplying and - /// taking the remainder. The register is initialized to zero, and for each - /// incoming bit, x^32 is added mod p to the register if the bit is a one (where - /// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by - /// x (which is shifting right by one and adding x^32 mod p if the bit shifted - /// out is a one). We start with the highest power (least significant bit) of - /// q and repeat for all eight bits of q. - /// - /// The table is simply the CRC of all possible eight bit values. This is all - /// the information needed to generate CRC's on data a byte at a time for all - /// combinations of CRC register values and incoming bytes. - /// - public sealed class Crc32 : IChecksum - { - const uint CrcSeed = 0xFFFFFFFF; - - readonly static uint[] CrcTable = new uint[] { - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, - 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, - 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, - 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, - 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, - 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, - 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, - 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, - 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, - 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, - 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, - 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, - 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, - 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, - 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, - 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, - 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, - 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, - 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, - 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, - 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, - 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, - 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, - 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, - 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, - 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, - 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, - 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, - 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, - 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, - 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, - 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, - 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, - 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, - 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, - 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, - 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, - 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, - 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, - 0x2D02EF8D - }; - - internal static uint ComputeCrc32(uint oldCrc, byte value) - { - return (uint)(Crc32.CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8)); - } - - /// - /// The crc data checksum so far. - /// - uint crc; - - /// - /// Returns the CRC32 data checksum computed so far. - /// - public long Value { - get { - return (long)crc; - } - set { - crc = (uint)value; - } - } - - /// - /// Resets the CRC32 data checksum as if no update was ever called. - /// - public void Reset() - { - crc = 0; - } - - /// - /// Updates the checksum with the int bval. - /// - /// - /// the byte is taken as the lower 8 bits of value - /// - public void Update(int value) - { - crc ^= CrcSeed; - crc = CrcTable[(crc ^ value) & 0xFF] ^ (crc >> 8); - crc ^= CrcSeed; - } - - /// - /// Updates the checksum with the bytes taken from the array. - /// - /// - /// buffer an array of bytes - /// - public void Update(byte[] buffer) - { - if (buffer == null) { - throw new ArgumentNullException("buffer"); - } - - Update(buffer, 0, buffer.Length); - } - - /// - /// Adds the byte array to the data checksum. - /// - /// - /// The buffer which contains the data - /// - /// - /// The offset in the buffer where the data starts - /// - /// - /// The number of data bytes to update the CRC with. - /// - public void Update(byte[] buffer, int offset, int count) - { - if (buffer == null) { - throw new ArgumentNullException("buffer"); - } - - if ( count < 0 ) { + + /// + /// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial: + /// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + /// + /// Polynomials over GF(2) are represented in binary, one bit per coefficient, + /// with the lowest powers in the most significant bit. Then adding polynomials + /// is just exclusive-or, and multiplying a polynomial by x is a right shift by + /// one. If we call the above polynomial p, and represent a byte as the + /// polynomial q, also with the lowest power in the most significant bit (so the + /// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + /// where a mod b means the remainder after dividing a by b. + /// + /// This calculation is done using the shift-register method of multiplying and + /// taking the remainder. The register is initialized to zero, and for each + /// incoming bit, x^32 is added mod p to the register if the bit is a one (where + /// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + /// x (which is shifting right by one and adding x^32 mod p if the bit shifted + /// out is a one). We start with the highest power (least significant bit) of + /// q and repeat for all eight bits of q. + /// + /// The table is simply the CRC of all possible eight bit values. This is all + /// the information needed to generate CRC's on data a byte at a time for all + /// combinations of CRC register values and incoming bytes. + /// + public sealed class Crc32 : IChecksum + { + const uint CrcSeed = 0xFFFFFFFF; + + readonly static uint[] CrcTable = new uint[] { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, + 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, + 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, + 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, + 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, + 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9, + 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, + 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, + 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A, + 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, + 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190, + 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, + 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, + 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED, + 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, + 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, + 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, + 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, + 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, + 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010, + 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, + 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, + 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615, + 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, + 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB, + 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, + 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, + 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C, + 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, + 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE, + 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31, + 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, + 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B, + 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, + 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, + 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, + 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278, + 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, + 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, + 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, + 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, + 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, + 0x2D02EF8D + }; + + internal static uint ComputeCrc32(uint oldCrc, byte value) + { + return (uint)(Crc32.CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8)); + } + + /// + /// The crc data checksum so far. + /// + uint crc; + + /// + /// Returns the CRC32 data checksum computed so far. + /// + public long Value { + get { + return (long)crc; + } + set { + crc = (uint)value; + } + } + + /// + /// Resets the CRC32 data checksum as if no update was ever called. + /// + public void Reset() + { + crc = 0; + } + + /// + /// Updates the checksum with the int bval. + /// + /// + /// the byte is taken as the lower 8 bits of value + /// + public void Update(int value) + { + crc ^= CrcSeed; + crc = CrcTable[(crc ^ value) & 0xFF] ^ (crc >> 8); + crc ^= CrcSeed; + } + + /// + /// Updates the checksum with the bytes taken from the array. + /// + /// + /// buffer an array of bytes + /// + public void Update(byte[] buffer) + { + if (buffer == null) { + throw new ArgumentNullException("buffer"); + } + + Update(buffer, 0, buffer.Length); + } + + /// + /// Adds the byte array to the data checksum. + /// + /// + /// The buffer which contains the data + /// + /// + /// The offset in the buffer where the data starts + /// + /// + /// The number of data bytes to update the CRC with. + /// + public void Update(byte[] buffer, int offset, int count) + { + if (buffer == null) { + throw new ArgumentNullException("buffer"); + } + + if ( count < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero"); -#endif - } - - if (offset < 0 || offset + count > buffer.Length) { - throw new ArgumentOutOfRangeException("offset"); - } - - crc ^= CrcSeed; - - while (--count >= 0) { - crc = CrcTable[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8); - } - - crc ^= CrcSeed; - } - } + throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero"); +#endif + } + + if (offset < 0 || offset + count > buffer.Length) { + throw new ArgumentOutOfRangeException("offset"); + } + + crc ^= CrcSeed; + + while (--count >= 0) { + crc = CrcTable[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8); + } + + crc ^= CrcSeed; + } + } } diff --git a/External/Tools/AppMan/ZipLib/Checksums/IChecksum.cs b/External/Tools/AppMan/ZipLib/Checksums/IChecksum.cs index e2679f9aa6..cb23e9c132 100644 --- a/External/Tools/AppMan/ZipLib/Checksums/IChecksum.cs +++ b/External/Tools/AppMan/ZipLib/Checksums/IChecksum.cs @@ -37,57 +37,57 @@ namespace ICSharpCode.SharpZipLib.Checksums { - - /// - /// Interface to compute a data checksum used by checked input/output streams. - /// A data checksum can be updated by one byte or with a byte array. After each - /// update the value of the current checksum can be returned by calling - /// getValue. The complete checksum object can also be reset - /// so it can be used again with new data. - /// - public interface IChecksum - { - /// - /// Returns the data checksum computed so far. - /// - long Value - { - get; - } - - /// - /// Resets the data checksum as if no update was ever called. - /// - void Reset(); - - /// - /// Adds one byte to the data checksum. - /// - /// - /// the data value to add. The high byte of the int is ignored. - /// - void Update(int value); - - /// - /// Updates the data checksum with the bytes taken from the array. - /// - /// - /// buffer an array of bytes - /// - void Update(byte[] buffer); - - /// - /// Adds the byte array to the data checksum. - /// - /// - /// The buffer which contains the data - /// - /// - /// The offset in the buffer where the data starts - /// - /// - /// the number of data bytes to add. - /// - void Update(byte[] buffer, int offset, int count); - } + + /// + /// Interface to compute a data checksum used by checked input/output streams. + /// A data checksum can be updated by one byte or with a byte array. After each + /// update the value of the current checksum can be returned by calling + /// getValue. The complete checksum object can also be reset + /// so it can be used again with new data. + /// + public interface IChecksum + { + /// + /// Returns the data checksum computed so far. + /// + long Value + { + get; + } + + /// + /// Resets the data checksum as if no update was ever called. + /// + void Reset(); + + /// + /// Adds one byte to the data checksum. + /// + /// + /// the data value to add. The high byte of the int is ignored. + /// + void Update(int value); + + /// + /// Updates the data checksum with the bytes taken from the array. + /// + /// + /// buffer an array of bytes + /// + void Update(byte[] buffer); + + /// + /// Adds the byte array to the data checksum. + /// + /// + /// The buffer which contains the data + /// + /// + /// The offset in the buffer where the data starts + /// + /// + /// the number of data bytes to add. + /// + void Update(byte[] buffer, int offset, int count); + } } diff --git a/External/Tools/AppMan/ZipLib/Checksums/StrangeCRC.cs b/External/Tools/AppMan/ZipLib/Checksums/StrangeCRC.cs index 6ed767970c..909f3095c7 100644 --- a/External/Tools/AppMan/ZipLib/Checksums/StrangeCRC.cs +++ b/External/Tools/AppMan/ZipLib/Checksums/StrangeCRC.cs @@ -40,169 +40,169 @@ namespace ICSharpCode.SharpZipLib.Checksums { - /// - /// Bzip2 checksum algorithm - /// - public class StrangeCRC : IChecksum - { - readonly static uint[] crc32Table = { - 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, - 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, - 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, - 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, - 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, - 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, - 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, - 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, - 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, - 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, - 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, - 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, - 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, - 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, - 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, - 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, - 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, - 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, - 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, - 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, - 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, - 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, - 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, - 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, - 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, - 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, - 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, - 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, - 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, - 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, - 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, - 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, - 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, - 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, - 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, - 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, - 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, - 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, - 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, - 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, - 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, - 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, - 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, - 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, - 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, - 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, - 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, - 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, - 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, - 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, - 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, - 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, - 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, - 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, - 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, - 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, - 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, - 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, - 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, - 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, - 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, - 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, - 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, - 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 - }; - - int globalCrc; + /// + /// Bzip2 checksum algorithm + /// + public class StrangeCRC : IChecksum + { + readonly static uint[] crc32Table = { + 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, + 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, + 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, + 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, + 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, + 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, + 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, + 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, + 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, + 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, + 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, + 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, + 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, + 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, + 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, + 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, + 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, + 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, + 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, + 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, + 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, + 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, + 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, + 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, + 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, + 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, + 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, + 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, + 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, + 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, + 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, + 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, + 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, + 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, + 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, + 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, + 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, + 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, + 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, + 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, + 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, + 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, + 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, + 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, + 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, + 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, + 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, + 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, + 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, + 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, + 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, + 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, + 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, + 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, + 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, + 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, + 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, + 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, + 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, + 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, + 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, + 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, + 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, + 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 + }; + + int globalCrc; - /// - /// Initialise a default instance of - /// - public StrangeCRC() - { - Reset(); - } + /// + /// Initialise a default instance of + /// + public StrangeCRC() + { + Reset(); + } - /// - /// Reset the state of Crc. - /// - public void Reset() - { - globalCrc = -1; - } + /// + /// Reset the state of Crc. + /// + public void Reset() + { + globalCrc = -1; + } - /// - /// Get the current Crc value. - /// - public long Value { - get { - return ~globalCrc; - } - } - - /// - /// Update the Crc value. - /// - /// data update is based on - public void Update(int value) - { - int temp = (globalCrc >> 24) ^ value; - if (temp < 0) { - temp = 256 + temp; - } - globalCrc = unchecked((int)((globalCrc << 8) ^ crc32Table[temp])); - } + /// + /// Get the current Crc value. + /// + public long Value { + get { + return ~globalCrc; + } + } + + /// + /// Update the Crc value. + /// + /// data update is based on + public void Update(int value) + { + int temp = (globalCrc >> 24) ^ value; + if (temp < 0) { + temp = 256 + temp; + } + globalCrc = unchecked((int)((globalCrc << 8) ^ crc32Table[temp])); + } - /// - /// Update Crc based on a block of data - /// - /// The buffer containing data to update the crc with. - public void Update(byte[] buffer) - { - if (buffer == null) { - throw new ArgumentNullException("buffer"); - } - - Update(buffer, 0, buffer.Length); - } - - /// - /// Update Crc based on a portion of a block of data - /// - /// block of data - /// index of first byte to use - /// number of bytes to use - public void Update(byte[] buffer, int offset, int count) - { - if (buffer == null) { - throw new ArgumentNullException("buffer"); - } - - if ( offset < 0 ) - { + /// + /// Update Crc based on a block of data + /// + /// The buffer containing data to update the crc with. + public void Update(byte[] buffer) + { + if (buffer == null) { + throw new ArgumentNullException("buffer"); + } + + Update(buffer, 0, buffer.Length); + } + + /// + /// Update Crc based on a portion of a block of data + /// + /// block of data + /// index of first byte to use + /// number of bytes to use + public void Update(byte[] buffer, int offset, int count) + { + if (buffer == null) { + throw new ArgumentNullException("buffer"); + } + + if ( offset < 0 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "cannot be less than zero"); -#endif - } + throw new ArgumentOutOfRangeException("offset", "cannot be less than zero"); +#endif + } - if ( count < 0 ) - { + if ( count < 0 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "cannot be less than zero"); + throw new ArgumentOutOfRangeException("count", "cannot be less than zero"); #endif - } + } - if ( offset + count > buffer.Length ) - { - throw new ArgumentOutOfRangeException("count"); - } - - for (int i = 0; i < count; ++i) { - Update(buffer[offset++]); - } - } - } + if ( offset + count > buffer.Length ) + { + throw new ArgumentOutOfRangeException("count"); + } + + for (int i = 0; i < count; ++i) { + Update(buffer[offset++]); + } + } + } } diff --git a/External/Tools/AppMan/ZipLib/Core/FileSystemScanner.cs b/External/Tools/AppMan/ZipLib/Core/FileSystemScanner.cs index 4077a455e9..6fd04881d7 100644 --- a/External/Tools/AppMan/ZipLib/Core/FileSystemScanner.cs +++ b/External/Tools/AppMan/ZipLib/Core/FileSystemScanner.cs @@ -38,496 +38,496 @@ namespace ICSharpCode.SharpZipLib.Core { - #region EventArgs - /// - /// Event arguments for scanning. - /// - public class ScanEventArgs : EventArgs - { - #region Constructors - /// - /// Initialise a new instance of - /// - /// The file or directory name. - public ScanEventArgs(string name) - { - name_ = name; - } - #endregion - - /// - /// The file or directory name for this event. - /// - public string Name - { - get { return name_; } - } - - /// - /// Get set a value indicating if scanning should continue or not. - /// - public bool ContinueRunning - { - get { return continueRunning_; } - set { continueRunning_ = value; } - } - - #region Instance Fields - string name_; - bool continueRunning_ = true; - #endregion - } + #region EventArgs + /// + /// Event arguments for scanning. + /// + public class ScanEventArgs : EventArgs + { + #region Constructors + /// + /// Initialise a new instance of + /// + /// The file or directory name. + public ScanEventArgs(string name) + { + name_ = name; + } + #endregion + + /// + /// The file or directory name for this event. + /// + public string Name + { + get { return name_; } + } + + /// + /// Get set a value indicating if scanning should continue or not. + /// + public bool ContinueRunning + { + get { return continueRunning_; } + set { continueRunning_ = value; } + } + + #region Instance Fields + string name_; + bool continueRunning_ = true; + #endregion + } - /// - /// Event arguments during processing of a single file or directory. - /// - public class ProgressEventArgs : EventArgs - { - #region Constructors - /// - /// Initialise a new instance of - /// - /// The file or directory name if known. - /// The number of bytes processed so far - /// The total number of bytes to process, 0 if not known - public ProgressEventArgs(string name, long processed, long target) - { - name_ = name; - processed_ = processed; - target_ = target; - } - #endregion - - /// - /// The name for this event if known. - /// - public string Name - { - get { return name_; } - } - - /// - /// Get set a value indicating wether scanning should continue or not. - /// - public bool ContinueRunning - { - get { return continueRunning_; } - set { continueRunning_ = value; } - } + /// + /// Event arguments during processing of a single file or directory. + /// + public class ProgressEventArgs : EventArgs + { + #region Constructors + /// + /// Initialise a new instance of + /// + /// The file or directory name if known. + /// The number of bytes processed so far + /// The total number of bytes to process, 0 if not known + public ProgressEventArgs(string name, long processed, long target) + { + name_ = name; + processed_ = processed; + target_ = target; + } + #endregion + + /// + /// The name for this event if known. + /// + public string Name + { + get { return name_; } + } + + /// + /// Get set a value indicating wether scanning should continue or not. + /// + public bool ContinueRunning + { + get { return continueRunning_; } + set { continueRunning_ = value; } + } - /// - /// Get a percentage representing how much of the has been processed - /// - /// 0.0 to 100.0 percent; 0 if target is not known. - public float PercentComplete - { - get - { - float result; - if (target_ <= 0) - { - result = 0; - } - else - { - result = ((float)processed_ / (float)target_) * 100.0f; - } - return result; - } - } - - /// - /// The number of bytes processed so far - /// - public long Processed - { - get { return processed_; } - } + /// + /// Get a percentage representing how much of the has been processed + /// + /// 0.0 to 100.0 percent; 0 if target is not known. + public float PercentComplete + { + get + { + float result; + if (target_ <= 0) + { + result = 0; + } + else + { + result = ((float)processed_ / (float)target_) * 100.0f; + } + return result; + } + } + + /// + /// The number of bytes processed so far + /// + public long Processed + { + get { return processed_; } + } - /// - /// The number of bytes to process. - /// - /// Target may be 0 or negative if the value isnt known. - public long Target - { - get { return target_; } - } - - #region Instance Fields - string name_; - long processed_; - long target_; - bool continueRunning_ = true; - #endregion - } + /// + /// The number of bytes to process. + /// + /// Target may be 0 or negative if the value isnt known. + public long Target + { + get { return target_; } + } + + #region Instance Fields + string name_; + long processed_; + long target_; + bool continueRunning_ = true; + #endregion + } - /// - /// Event arguments for directories. - /// - public class DirectoryEventArgs : ScanEventArgs - { - #region Constructors - /// - /// Initialize an instance of . - /// - /// The name for this directory. - /// Flag value indicating if any matching files are contained in this directory. - public DirectoryEventArgs(string name, bool hasMatchingFiles) - : base (name) - { - hasMatchingFiles_ = hasMatchingFiles; - } - #endregion - - /// - /// Get a value indicating if the directory contains any matching files or not. - /// - public bool HasMatchingFiles - { - get { return hasMatchingFiles_; } - } - - #region Instance Fields - bool hasMatchingFiles_; - #endregion - } - - /// - /// Arguments passed when scan failures are detected. - /// - public class ScanFailureEventArgs : EventArgs - { - #region Constructors - /// - /// Initialise a new instance of - /// - /// The name to apply. - /// The exception to use. - public ScanFailureEventArgs(string name, Exception e) - { - name_ = name; - exception_ = e; - continueRunning_ = true; - } - #endregion - - /// - /// The applicable name. - /// - public string Name - { - get { return name_; } - } - - /// - /// The applicable exception. - /// - public Exception Exception - { - get { return exception_; } - } - - /// - /// Get / set a value indicating wether scanning should continue. - /// - public bool ContinueRunning - { - get { return continueRunning_; } - set { continueRunning_ = value; } - } - - #region Instance Fields - string name_; - Exception exception_; - bool continueRunning_; - #endregion - } - - #endregion - - #region Delegates - /// - /// Delegate invoked before starting to process a directory. - /// - public delegate void ProcessDirectoryHandler(object sender, DirectoryEventArgs e); - - /// - /// Delegate invoked before starting to process a file. - /// - /// The source of the event - /// The event arguments. - public delegate void ProcessFileHandler(object sender, ScanEventArgs e); + /// + /// Event arguments for directories. + /// + public class DirectoryEventArgs : ScanEventArgs + { + #region Constructors + /// + /// Initialize an instance of . + /// + /// The name for this directory. + /// Flag value indicating if any matching files are contained in this directory. + public DirectoryEventArgs(string name, bool hasMatchingFiles) + : base (name) + { + hasMatchingFiles_ = hasMatchingFiles; + } + #endregion + + /// + /// Get a value indicating if the directory contains any matching files or not. + /// + public bool HasMatchingFiles + { + get { return hasMatchingFiles_; } + } + + #region Instance Fields + bool hasMatchingFiles_; + #endregion + } + + /// + /// Arguments passed when scan failures are detected. + /// + public class ScanFailureEventArgs : EventArgs + { + #region Constructors + /// + /// Initialise a new instance of + /// + /// The name to apply. + /// The exception to use. + public ScanFailureEventArgs(string name, Exception e) + { + name_ = name; + exception_ = e; + continueRunning_ = true; + } + #endregion + + /// + /// The applicable name. + /// + public string Name + { + get { return name_; } + } + + /// + /// The applicable exception. + /// + public Exception Exception + { + get { return exception_; } + } + + /// + /// Get / set a value indicating wether scanning should continue. + /// + public bool ContinueRunning + { + get { return continueRunning_; } + set { continueRunning_ = value; } + } + + #region Instance Fields + string name_; + Exception exception_; + bool continueRunning_; + #endregion + } + + #endregion + + #region Delegates + /// + /// Delegate invoked before starting to process a directory. + /// + public delegate void ProcessDirectoryHandler(object sender, DirectoryEventArgs e); + + /// + /// Delegate invoked before starting to process a file. + /// + /// The source of the event + /// The event arguments. + public delegate void ProcessFileHandler(object sender, ScanEventArgs e); - /// - /// Delegate invoked during processing of a file or directory - /// - /// The source of the event - /// The event arguments. - public delegate void ProgressHandler(object sender, ProgressEventArgs e); + /// + /// Delegate invoked during processing of a file or directory + /// + /// The source of the event + /// The event arguments. + public delegate void ProgressHandler(object sender, ProgressEventArgs e); - /// - /// Delegate invoked when a file has been completely processed. - /// - /// The source of the event - /// The event arguments. - public delegate void CompletedFileHandler(object sender, ScanEventArgs e); - - /// - /// Delegate invoked when a directory failure is detected. - /// - /// The source of the event - /// The event arguments. - public delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); - - /// - /// Delegate invoked when a file failure is detected. - /// - /// The source of the event - /// The event arguments. - public delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); - #endregion + /// + /// Delegate invoked when a file has been completely processed. + /// + /// The source of the event + /// The event arguments. + public delegate void CompletedFileHandler(object sender, ScanEventArgs e); + + /// + /// Delegate invoked when a directory failure is detected. + /// + /// The source of the event + /// The event arguments. + public delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); + + /// + /// Delegate invoked when a file failure is detected. + /// + /// The source of the event + /// The event arguments. + public delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); + #endregion - /// - /// FileSystemScanner provides facilities scanning of files and directories. - /// - public class FileSystemScanner - { - #region Constructors - /// - /// Initialise a new instance of - /// - /// The file filter to apply when scanning. - public FileSystemScanner(string filter) - { - fileFilter_ = new PathFilter(filter); - } - - /// - /// Initialise a new instance of - /// - /// The file filter to apply. - /// The directory filter to apply. - public FileSystemScanner(string fileFilter, string directoryFilter) - { - fileFilter_ = new PathFilter(fileFilter); - directoryFilter_ = new PathFilter(directoryFilter); - } - - /// - /// Initialise a new instance of - /// - /// The file filter to apply. - public FileSystemScanner(IScanFilter fileFilter) - { - fileFilter_ = fileFilter; - } - - /// - /// Initialise a new instance of - /// - /// The file filter to apply. - /// The directory filter to apply. - public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) - { - fileFilter_ = fileFilter; - directoryFilter_ = directoryFilter; - } - #endregion + /// + /// FileSystemScanner provides facilities scanning of files and directories. + /// + public class FileSystemScanner + { + #region Constructors + /// + /// Initialise a new instance of + /// + /// The file filter to apply when scanning. + public FileSystemScanner(string filter) + { + fileFilter_ = new PathFilter(filter); + } + + /// + /// Initialise a new instance of + /// + /// The file filter to apply. + /// The directory filter to apply. + public FileSystemScanner(string fileFilter, string directoryFilter) + { + fileFilter_ = new PathFilter(fileFilter); + directoryFilter_ = new PathFilter(directoryFilter); + } + + /// + /// Initialise a new instance of + /// + /// The file filter to apply. + public FileSystemScanner(IScanFilter fileFilter) + { + fileFilter_ = fileFilter; + } + + /// + /// Initialise a new instance of + /// + /// The file filter to apply. + /// The directory filter to apply. + public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) + { + fileFilter_ = fileFilter; + directoryFilter_ = directoryFilter; + } + #endregion - #region Delegates - /// - /// Delegate to invoke when a directory is processed. - /// - public ProcessDirectoryHandler ProcessDirectory; - - /// - /// Delegate to invoke when a file is processed. - /// - public ProcessFileHandler ProcessFile; + #region Delegates + /// + /// Delegate to invoke when a directory is processed. + /// + public ProcessDirectoryHandler ProcessDirectory; + + /// + /// Delegate to invoke when a file is processed. + /// + public ProcessFileHandler ProcessFile; - /// - /// Delegate to invoke when processing for a file has finished. - /// - public CompletedFileHandler CompletedFile; + /// + /// Delegate to invoke when processing for a file has finished. + /// + public CompletedFileHandler CompletedFile; - /// - /// Delegate to invoke when a directory failure is detected. - /// - public DirectoryFailureHandler DirectoryFailure; - - /// - /// Delegate to invoke when a file failure is detected. - /// - public FileFailureHandler FileFailure; - #endregion + /// + /// Delegate to invoke when a directory failure is detected. + /// + public DirectoryFailureHandler DirectoryFailure; + + /// + /// Delegate to invoke when a file failure is detected. + /// + public FileFailureHandler FileFailure; + #endregion - /// - /// Raise the DirectoryFailure event. - /// - /// The directory name. - /// The exception detected. - bool OnDirectoryFailure(string directory, Exception e) - { + /// + /// Raise the DirectoryFailure event. + /// + /// The directory name. + /// The exception detected. + bool OnDirectoryFailure(string directory, Exception e) + { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if ( result ) { - ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); - handler(this, args); - alive_ = args.ContinueRunning; - } + ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); + handler(this, args); + alive_ = args.ContinueRunning; + } return result; - } - - /// - /// Raise the FileFailure event. - /// - /// The file name. - /// The exception detected. - bool OnFileFailure(string file, Exception e) - { + } + + /// + /// Raise the FileFailure event. + /// + /// The file name. + /// The exception detected. + bool OnFileFailure(string file, Exception e) + { FileFailureHandler handler = FileFailure; bool result = (handler != null); - if ( result ){ - ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); - FileFailure(this, args); - alive_ = args.ContinueRunning; - } + if ( result ){ + ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); + FileFailure(this, args); + alive_ = args.ContinueRunning; + } return result; - } + } - /// - /// Raise the ProcessFile event. - /// - /// The file name. - void OnProcessFile(string file) - { - ProcessFileHandler handler = ProcessFile; + /// + /// Raise the ProcessFile event. + /// + /// The file name. + void OnProcessFile(string file) + { + ProcessFileHandler handler = ProcessFile; - if ( handler!= null ) { - ScanEventArgs args = new ScanEventArgs(file); - handler(this, args); - alive_ = args.ContinueRunning; - } - } + if ( handler!= null ) { + ScanEventArgs args = new ScanEventArgs(file); + handler(this, args); + alive_ = args.ContinueRunning; + } + } - /// - /// Raise the complete file event - /// - /// The file name - void OnCompleteFile(string file) - { - CompletedFileHandler handler = CompletedFile; + /// + /// Raise the complete file event + /// + /// The file name + void OnCompleteFile(string file) + { + CompletedFileHandler handler = CompletedFile; - if (handler != null) - { - ScanEventArgs args = new ScanEventArgs(file); - handler(this, args); - alive_ = args.ContinueRunning; - } - } + if (handler != null) + { + ScanEventArgs args = new ScanEventArgs(file); + handler(this, args); + alive_ = args.ContinueRunning; + } + } - /// - /// Raise the ProcessDirectory event. - /// - /// The directory name. - /// Flag indicating if the directory has matching files. - void OnProcessDirectory(string directory, bool hasMatchingFiles) - { - ProcessDirectoryHandler handler = ProcessDirectory; + /// + /// Raise the ProcessDirectory event. + /// + /// The directory name. + /// Flag indicating if the directory has matching files. + void OnProcessDirectory(string directory, bool hasMatchingFiles) + { + ProcessDirectoryHandler handler = ProcessDirectory; - if ( handler != null ) { - DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); - handler(this, args); - alive_ = args.ContinueRunning; - } - } + if ( handler != null ) { + DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); + handler(this, args); + alive_ = args.ContinueRunning; + } + } - /// - /// Scan a directory. - /// - /// The base directory to scan. - /// True to recurse subdirectories, false to scan a single directory. - public void Scan(string directory, bool recurse) - { - alive_ = true; - ScanDir(directory, recurse); - } - - void ScanDir(string directory, bool recurse) - { + /// + /// Scan a directory. + /// + /// The base directory to scan. + /// True to recurse subdirectories, false to scan a single directory. + public void Scan(string directory, bool recurse) + { + alive_ = true; + ScanDir(directory, recurse); + } + + void ScanDir(string directory, bool recurse) + { - try { - string[] names = System.IO.Directory.GetFiles(directory); - bool hasMatch = false; - for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { - if ( !fileFilter_.IsMatch(names[fileIndex]) ) { - names[fileIndex] = null; - } else { - hasMatch = true; - } - } - - OnProcessDirectory(directory, hasMatch); - - if ( alive_ && hasMatch ) { - foreach (string fileName in names) { - try { - if ( fileName != null ) { - OnProcessFile(fileName); - if ( !alive_ ) { - break; - } - } - } - catch (Exception e) { + try { + string[] names = System.IO.Directory.GetFiles(directory); + bool hasMatch = false; + for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { + if ( !fileFilter_.IsMatch(names[fileIndex]) ) { + names[fileIndex] = null; + } else { + hasMatch = true; + } + } + + OnProcessDirectory(directory, hasMatch); + + if ( alive_ && hasMatch ) { + foreach (string fileName in names) { + try { + if ( fileName != null ) { + OnProcessFile(fileName); + if ( !alive_ ) { + break; + } + } + } + catch (Exception e) { if (!OnFileFailure(fileName, e)) { throw; } - } - } - } - } - catch (Exception e) { + } + } + } + } + catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } - } + } - if ( alive_ && recurse ) { - try { - string[] names = System.IO.Directory.GetDirectories(directory); - foreach (string fulldir in names) { - if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { - ScanDir(fulldir, true); - if ( !alive_ ) { - break; - } - } - } - } - catch (Exception e) { + if ( alive_ && recurse ) { + try { + string[] names = System.IO.Directory.GetDirectories(directory); + foreach (string fulldir in names) { + if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { + ScanDir(fulldir, true); + if ( !alive_ ) { + break; + } + } + } + } + catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } - } - } - } - - #region Instance Fields - /// - /// The file filter currently in use. - /// - IScanFilter fileFilter_; - /// - /// The directory filter currently in use. - /// - IScanFilter directoryFilter_; - /// - /// Flag indicating if scanning should continue running. - /// - bool alive_; - #endregion - } + } + } + } + + #region Instance Fields + /// + /// The file filter currently in use. + /// + IScanFilter fileFilter_; + /// + /// The directory filter currently in use. + /// + IScanFilter directoryFilter_; + /// + /// Flag indicating if scanning should continue running. + /// + bool alive_; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Core/INameTransform.cs b/External/Tools/AppMan/ZipLib/Core/INameTransform.cs index 88c934f7d5..60ca0293cb 100644 --- a/External/Tools/AppMan/ZipLib/Core/INameTransform.cs +++ b/External/Tools/AppMan/ZipLib/Core/INameTransform.cs @@ -35,23 +35,23 @@ namespace ICSharpCode.SharpZipLib.Core { - /// - /// INameTransform defines how file system names are transformed for use with archives, or vice versa. - /// - public interface INameTransform - { - /// - /// Given a file name determine the transformed value. - /// - /// The name to transform. - /// The transformed file name. - string TransformFile(string name); - - /// - /// Given a directory name determine the transformed value. - /// - /// The name to transform. - /// The transformed directory name - string TransformDirectory(string name); - } + /// + /// INameTransform defines how file system names are transformed for use with archives, or vice versa. + /// + public interface INameTransform + { + /// + /// Given a file name determine the transformed value. + /// + /// The name to transform. + /// The transformed file name. + string TransformFile(string name); + + /// + /// Given a directory name determine the transformed value. + /// + /// The name to transform. + /// The transformed directory name + string TransformDirectory(string name); + } } diff --git a/External/Tools/AppMan/ZipLib/Core/IScanFilter.cs b/External/Tools/AppMan/ZipLib/Core/IScanFilter.cs index 64c99a8a3f..49ba689ba6 100644 --- a/External/Tools/AppMan/ZipLib/Core/IScanFilter.cs +++ b/External/Tools/AppMan/ZipLib/Core/IScanFilter.cs @@ -35,16 +35,16 @@ namespace ICSharpCode.SharpZipLib.Core { - /// - /// Scanning filters support filtering of names. - /// - public interface IScanFilter - { - /// - /// Test a name to see if it 'matches' the filter. - /// - /// The name to test. - /// Returns true if the name matches the filter, false if it does not match. - bool IsMatch(string name); - } + /// + /// Scanning filters support filtering of names. + /// + public interface IScanFilter + { + /// + /// Test a name to see if it 'matches' the filter. + /// + /// The name to test. + /// Returns true if the name matches the filter, false if it does not match. + bool IsMatch(string name); + } } diff --git a/External/Tools/AppMan/ZipLib/Core/NameFilter.cs b/External/Tools/AppMan/ZipLib/Core/NameFilter.cs index eea8fbee1d..ac14b1bd6e 100644 --- a/External/Tools/AppMan/ZipLib/Core/NameFilter.cs +++ b/External/Tools/AppMan/ZipLib/Core/NameFilter.cs @@ -34,7 +34,7 @@ // exception statement from your version. // HISTORY -// 2010-03-03 Z-1654 Fixed bug where escape characters were excluded in SplitQuoted() +// 2010-03-03 Z-1654 Fixed bug where escape characters were excluded in SplitQuoted() using System; using System.Collections; @@ -43,248 +43,248 @@ namespace ICSharpCode.SharpZipLib.Core { - /// - /// NameFilter is a string matching class which allows for both positive and negative - /// matching. - /// A filter is a sequence of independant regular expressions separated by semi-colons ';'. - /// To include a semi-colon it may be quoted as in \;. Each expression can be prefixed by a plus '+' sign or - /// a minus '-' sign to denote the expression is intended to include or exclude names. - /// If neither a plus or minus sign is found include is the default. - /// A given name is tested for inclusion before checking exclusions. Only names matching an include spec - /// and not matching an exclude spec are deemed to match the filter. - /// An empty filter matches any name. - /// - /// The following expression includes all name ending in '.dat' with the exception of 'dummy.dat' - /// "+\.dat$;-^dummy\.dat$" - /// - public class NameFilter : IScanFilter - { - #region Constructors - /// - /// Construct an instance based on the filter expression passed - /// - /// The filter expression. - public NameFilter(string filter) - { - filter_ = filter; - inclusions_ = new ArrayList(); - exclusions_ = new ArrayList(); - Compile(); - } - #endregion + /// + /// NameFilter is a string matching class which allows for both positive and negative + /// matching. + /// A filter is a sequence of independant regular expressions separated by semi-colons ';'. + /// To include a semi-colon it may be quoted as in \;. Each expression can be prefixed by a plus '+' sign or + /// a minus '-' sign to denote the expression is intended to include or exclude names. + /// If neither a plus or minus sign is found include is the default. + /// A given name is tested for inclusion before checking exclusions. Only names matching an include spec + /// and not matching an exclude spec are deemed to match the filter. + /// An empty filter matches any name. + /// + /// The following expression includes all name ending in '.dat' with the exception of 'dummy.dat' + /// "+\.dat$;-^dummy\.dat$" + /// + public class NameFilter : IScanFilter + { + #region Constructors + /// + /// Construct an instance based on the filter expression passed + /// + /// The filter expression. + public NameFilter(string filter) + { + filter_ = filter; + inclusions_ = new ArrayList(); + exclusions_ = new ArrayList(); + Compile(); + } + #endregion - /// - /// Test a string to see if it is a valid regular expression. - /// - /// The expression to test. - /// True if expression is a valid false otherwise. - public static bool IsValidExpression(string expression) - { - bool result = true; - try { - Regex exp = new Regex(expression, RegexOptions.IgnoreCase | RegexOptions.Singleline); - } - catch (ArgumentException) { - result = false; - } - return result; - } + /// + /// Test a string to see if it is a valid regular expression. + /// + /// The expression to test. + /// True if expression is a valid false otherwise. + public static bool IsValidExpression(string expression) + { + bool result = true; + try { + Regex exp = new Regex(expression, RegexOptions.IgnoreCase | RegexOptions.Singleline); + } + catch (ArgumentException) { + result = false; + } + return result; + } - /// - /// Test an expression to see if it is valid as a filter. - /// - /// The filter expression to test. - /// True if the expression is valid, false otherwise. - public static bool IsValidFilterExpression(string toTest) - { - if ( toTest == null ) { - throw new ArgumentNullException("toTest"); - } + /// + /// Test an expression to see if it is valid as a filter. + /// + /// The filter expression to test. + /// True if the expression is valid, false otherwise. + public static bool IsValidFilterExpression(string toTest) + { + if ( toTest == null ) { + throw new ArgumentNullException("toTest"); + } - bool result = true; + bool result = true; - try { - string[] items = SplitQuoted(toTest); - for (int i = 0; i < items.Length; ++i) { - if ((items[i] != null) && (items[i].Length > 0)) { - string toCompile; + try { + string[] items = SplitQuoted(toTest); + for (int i = 0; i < items.Length; ++i) { + if ((items[i] != null) && (items[i].Length > 0)) { + string toCompile; - if (items[i][0] == '+') { - toCompile = items[i].Substring(1, items[i].Length - 1); - } - else if (items[i][0] == '-') { - toCompile = items[i].Substring(1, items[i].Length - 1); - } - else { - toCompile = items[i]; - } + if (items[i][0] == '+') { + toCompile = items[i].Substring(1, items[i].Length - 1); + } + else if (items[i][0] == '-') { + toCompile = items[i].Substring(1, items[i].Length - 1); + } + else { + toCompile = items[i]; + } - Regex testRegex = new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Singleline); - } - } - } - catch (ArgumentException) { - result = false; - } + Regex testRegex = new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Singleline); + } + } + } + catch (ArgumentException) { + result = false; + } - return result; - } + return result; + } - /// - /// Split a string into its component pieces - /// - /// The original string - /// Returns an array of values containing the individual filter elements. - public static string[] SplitQuoted(string original) - { - char escape = '\\'; - char[] separators = { ';' }; + /// + /// Split a string into its component pieces + /// + /// The original string + /// Returns an array of values containing the individual filter elements. + public static string[] SplitQuoted(string original) + { + char escape = '\\'; + char[] separators = { ';' }; - ArrayList result = new ArrayList(); + ArrayList result = new ArrayList(); - if ((original != null) && (original.Length > 0)) { - int endIndex = -1; - StringBuilder b = new StringBuilder(); + if ((original != null) && (original.Length > 0)) { + int endIndex = -1; + StringBuilder b = new StringBuilder(); - while (endIndex < original.Length) { - endIndex += 1; - if (endIndex >= original.Length) { - result.Add(b.ToString()); - } - else if (original[endIndex] == escape) { - endIndex += 1; - if (endIndex >= original.Length) { + while (endIndex < original.Length) { + endIndex += 1; + if (endIndex >= original.Length) { + result.Add(b.ToString()); + } + else if (original[endIndex] == escape) { + endIndex += 1; + if (endIndex >= original.Length) { #if NETCF_1_0 - throw new ArgumentException("Missing terminating escape character"); + throw new ArgumentException("Missing terminating escape character"); #else - throw new ArgumentException("Missing terminating escape character", "original"); + throw new ArgumentException("Missing terminating escape character", "original"); #endif - } - // include escape if this is not an escaped separator - if (Array.IndexOf(separators, original[endIndex]) < 0) - b.Append(escape); + } + // include escape if this is not an escaped separator + if (Array.IndexOf(separators, original[endIndex]) < 0) + b.Append(escape); - b.Append(original[endIndex]); - } - else { - if (Array.IndexOf(separators, original[endIndex]) >= 0) { - result.Add(b.ToString()); - b.Length = 0; - } - else { - b.Append(original[endIndex]); - } - } - } - } + b.Append(original[endIndex]); + } + else { + if (Array.IndexOf(separators, original[endIndex]) >= 0) { + result.Add(b.ToString()); + b.Length = 0; + } + else { + b.Append(original[endIndex]); + } + } + } + } - return (string[])result.ToArray(typeof(string)); - } + return (string[])result.ToArray(typeof(string)); + } - /// - /// Convert this filter to its string equivalent. - /// - /// The string equivalent for this filter. - public override string ToString() - { - return filter_; - } + /// + /// Convert this filter to its string equivalent. + /// + /// The string equivalent for this filter. + public override string ToString() + { + return filter_; + } - /// - /// Test a value to see if it is included by the filter. - /// - /// The value to test. - /// True if the value is included, false otherwise. - public bool IsIncluded(string name) - { - bool result = false; - if ( inclusions_.Count == 0 ) { - result = true; - } - else { - foreach ( Regex r in inclusions_ ) { - if ( r.IsMatch(name) ) { - result = true; - break; - } - } - } - return result; - } + /// + /// Test a value to see if it is included by the filter. + /// + /// The value to test. + /// True if the value is included, false otherwise. + public bool IsIncluded(string name) + { + bool result = false; + if ( inclusions_.Count == 0 ) { + result = true; + } + else { + foreach ( Regex r in inclusions_ ) { + if ( r.IsMatch(name) ) { + result = true; + break; + } + } + } + return result; + } - /// - /// Test a value to see if it is excluded by the filter. - /// - /// The value to test. - /// True if the value is excluded, false otherwise. - public bool IsExcluded(string name) - { - bool result = false; - foreach ( Regex r in exclusions_ ) { - if ( r.IsMatch(name) ) { - result = true; - break; - } - } - return result; - } + /// + /// Test a value to see if it is excluded by the filter. + /// + /// The value to test. + /// True if the value is excluded, false otherwise. + public bool IsExcluded(string name) + { + bool result = false; + foreach ( Regex r in exclusions_ ) { + if ( r.IsMatch(name) ) { + result = true; + break; + } + } + return result; + } - #region IScanFilter Members - /// - /// Test a value to see if it matches the filter. - /// - /// The value to test. - /// True if the value matches, false otherwise. - public bool IsMatch(string name) - { - return (IsIncluded(name) && !IsExcluded(name)); - } - #endregion + #region IScanFilter Members + /// + /// Test a value to see if it matches the filter. + /// + /// The value to test. + /// True if the value matches, false otherwise. + public bool IsMatch(string name) + { + return (IsIncluded(name) && !IsExcluded(name)); + } + #endregion - /// - /// Compile this filter. - /// - void Compile() - { - // TODO: Check to see if combining RE's makes it faster/smaller. - // simple scheme would be to have one RE for inclusion and one for exclusion. - if ( filter_ == null ) { - return; - } + /// + /// Compile this filter. + /// + void Compile() + { + // TODO: Check to see if combining RE's makes it faster/smaller. + // simple scheme would be to have one RE for inclusion and one for exclusion. + if ( filter_ == null ) { + return; + } - string[] items = SplitQuoted(filter_); - for ( int i = 0; i < items.Length; ++i ) { - if ( (items[i] != null) && (items[i].Length > 0) ) { - bool include = (items[i][0] != '-'); - string toCompile; + string[] items = SplitQuoted(filter_); + for ( int i = 0; i < items.Length; ++i ) { + if ( (items[i] != null) && (items[i].Length > 0) ) { + bool include = (items[i][0] != '-'); + string toCompile; - if ( items[i][0] == '+' ) { - toCompile = items[i].Substring(1, items[i].Length - 1); - } - else if ( items[i][0] == '-' ) { - toCompile = items[i].Substring(1, items[i].Length - 1); - } - else { - toCompile = items[i]; - } + if ( items[i][0] == '+' ) { + toCompile = items[i].Substring(1, items[i].Length - 1); + } + else if ( items[i][0] == '-' ) { + toCompile = items[i].Substring(1, items[i].Length - 1); + } + else { + toCompile = items[i]; + } - // NOTE: Regular expressions can fail to compile here for a number of reasons that cause an exception - // these are left unhandled here as the caller is responsible for ensuring all is valid. - // several functions IsValidFilterExpression and IsValidExpression are provided for such checking - if ( include ) { - inclusions_.Add(new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline)); - } - else { - exclusions_.Add(new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline)); - } - } - } - } + // NOTE: Regular expressions can fail to compile here for a number of reasons that cause an exception + // these are left unhandled here as the caller is responsible for ensuring all is valid. + // several functions IsValidFilterExpression and IsValidExpression are provided for such checking + if ( include ) { + inclusions_.Add(new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline)); + } + else { + exclusions_.Add(new Regex(toCompile, RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline)); + } + } + } + } - #region Instance Fields - string filter_; - ArrayList inclusions_; - ArrayList exclusions_; - #endregion - } + #region Instance Fields + string filter_; + ArrayList inclusions_; + ArrayList exclusions_; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Core/PathFilter.cs b/External/Tools/AppMan/ZipLib/Core/PathFilter.cs index 03b8ff348a..9c66e0c554 100644 --- a/External/Tools/AppMan/ZipLib/Core/PathFilter.cs +++ b/External/Tools/AppMan/ZipLib/Core/PathFilter.cs @@ -38,297 +38,297 @@ namespace ICSharpCode.SharpZipLib.Core { - /// - /// PathFilter filters directories and files using a form of regular expressions - /// by full path name. - /// See NameFilter for more detail on filtering. - /// - public class PathFilter : IScanFilter - { - #region Constructors - /// - /// Initialise a new instance of . - /// - /// The filter expression to apply. - public PathFilter(string filter) - { - nameFilter_ = new NameFilter(filter); - } - #endregion + /// + /// PathFilter filters directories and files using a form of regular expressions + /// by full path name. + /// See NameFilter for more detail on filtering. + /// + public class PathFilter : IScanFilter + { + #region Constructors + /// + /// Initialise a new instance of . + /// + /// The filter expression to apply. + public PathFilter(string filter) + { + nameFilter_ = new NameFilter(filter); + } + #endregion - #region IScanFilter Members - /// - /// Test a name to see if it matches the filter. - /// - /// The name to test. - /// True if the name matches, false otherwise. - /// is used to get the full path before matching. - public virtual bool IsMatch(string name) - { - bool result = false; + #region IScanFilter Members + /// + /// Test a name to see if it matches the filter. + /// + /// The name to test. + /// True if the name matches, false otherwise. + /// is used to get the full path before matching. + public virtual bool IsMatch(string name) + { + bool result = false; - if ( name != null ) { - string cooked = (name.Length > 0) ? Path.GetFullPath(name) : ""; - result = nameFilter_.IsMatch(cooked); - } - return result; - } - #endregion + if ( name != null ) { + string cooked = (name.Length > 0) ? Path.GetFullPath(name) : ""; + result = nameFilter_.IsMatch(cooked); + } + return result; + } + #endregion - #region Instance Fields - NameFilter nameFilter_; - #endregion - } + #region Instance Fields + NameFilter nameFilter_; + #endregion + } - /// - /// ExtendedPathFilter filters based on name, file size, and the last write time of the file. - /// - /// Provides an example of how to customise filtering. - public class ExtendedPathFilter : PathFilter - { - #region Constructors - /// - /// Initialise a new instance of ExtendedPathFilter. - /// - /// The filter to apply. - /// The minimum file size to include. - /// The maximum file size to include. - public ExtendedPathFilter(string filter, - long minSize, long maxSize) - : base(filter) - { - MinSize = minSize; - MaxSize = maxSize; - } + /// + /// ExtendedPathFilter filters based on name, file size, and the last write time of the file. + /// + /// Provides an example of how to customise filtering. + public class ExtendedPathFilter : PathFilter + { + #region Constructors + /// + /// Initialise a new instance of ExtendedPathFilter. + /// + /// The filter to apply. + /// The minimum file size to include. + /// The maximum file size to include. + public ExtendedPathFilter(string filter, + long minSize, long maxSize) + : base(filter) + { + MinSize = minSize; + MaxSize = maxSize; + } - /// - /// Initialise a new instance of ExtendedPathFilter. - /// - /// The filter to apply. - /// The minimum to include. - /// The maximum to include. - public ExtendedPathFilter(string filter, - DateTime minDate, DateTime maxDate) - : base(filter) - { - MinDate = minDate; - MaxDate = maxDate; - } + /// + /// Initialise a new instance of ExtendedPathFilter. + /// + /// The filter to apply. + /// The minimum to include. + /// The maximum to include. + public ExtendedPathFilter(string filter, + DateTime minDate, DateTime maxDate) + : base(filter) + { + MinDate = minDate; + MaxDate = maxDate; + } - /// - /// Initialise a new instance of ExtendedPathFilter. - /// - /// The filter to apply. - /// The minimum file size to include. - /// The maximum file size to include. - /// The minimum to include. - /// The maximum to include. - public ExtendedPathFilter(string filter, - long minSize, long maxSize, - DateTime minDate, DateTime maxDate) - : base(filter) - { - MinSize = minSize; - MaxSize = maxSize; - MinDate = minDate; - MaxDate = maxDate; - } - #endregion + /// + /// Initialise a new instance of ExtendedPathFilter. + /// + /// The filter to apply. + /// The minimum file size to include. + /// The maximum file size to include. + /// The minimum to include. + /// The maximum to include. + public ExtendedPathFilter(string filter, + long minSize, long maxSize, + DateTime minDate, DateTime maxDate) + : base(filter) + { + MinSize = minSize; + MaxSize = maxSize; + MinDate = minDate; + MaxDate = maxDate; + } + #endregion - #region IScanFilter Members - /// - /// Test a filename to see if it matches the filter. - /// - /// The filename to test. - /// True if the filter matches, false otherwise. - /// The doesnt exist - public override bool IsMatch(string name) - { - bool result = base.IsMatch(name); + #region IScanFilter Members + /// + /// Test a filename to see if it matches the filter. + /// + /// The filename to test. + /// True if the filter matches, false otherwise. + /// The doesnt exist + public override bool IsMatch(string name) + { + bool result = base.IsMatch(name); - if ( result ) { - FileInfo fileInfo = new FileInfo(name); - result = - (MinSize <= fileInfo.Length) && - (MaxSize >= fileInfo.Length) && - (MinDate <= fileInfo.LastWriteTime) && - (MaxDate >= fileInfo.LastWriteTime) - ; - } - return result; - } - #endregion + if ( result ) { + FileInfo fileInfo = new FileInfo(name); + result = + (MinSize <= fileInfo.Length) && + (MaxSize >= fileInfo.Length) && + (MinDate <= fileInfo.LastWriteTime) && + (MaxDate >= fileInfo.LastWriteTime) + ; + } + return result; + } + #endregion - #region Properties - /// - /// Get/set the minimum size/length for a file that will match this filter. - /// - /// The default value is zero. - /// value is less than zero; greater than - public long MinSize - { - get { return minSize_; } - set - { - if ( (value < 0) || (maxSize_ < value) ) { - throw new ArgumentOutOfRangeException("value"); - } + #region Properties + /// + /// Get/set the minimum size/length for a file that will match this filter. + /// + /// The default value is zero. + /// value is less than zero; greater than + public long MinSize + { + get { return minSize_; } + set + { + if ( (value < 0) || (maxSize_ < value) ) { + throw new ArgumentOutOfRangeException("value"); + } - minSize_ = value; - } - } - - /// - /// Get/set the maximum size/length for a file that will match this filter. - /// - /// The default value is - /// value is less than zero or less than - public long MaxSize - { - get { return maxSize_; } - set - { - if ( (value < 0) || (minSize_ > value) ) { - throw new ArgumentOutOfRangeException("value"); - } + minSize_ = value; + } + } + + /// + /// Get/set the maximum size/length for a file that will match this filter. + /// + /// The default value is + /// value is less than zero or less than + public long MaxSize + { + get { return maxSize_; } + set + { + if ( (value < 0) || (minSize_ > value) ) { + throw new ArgumentOutOfRangeException("value"); + } - maxSize_ = value; - } - } + maxSize_ = value; + } + } - /// - /// Get/set the minimum value that will match for this filter. - /// - /// Files with a LastWrite time less than this value are excluded by the filter. - public DateTime MinDate - { - get - { - return minDate_; - } + /// + /// Get/set the minimum value that will match for this filter. + /// + /// Files with a LastWrite time less than this value are excluded by the filter. + public DateTime MinDate + { + get + { + return minDate_; + } - set - { - if ( value > maxDate_ ) { + set + { + if ( value > maxDate_ ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException("value"); #else - throw new ArgumentOutOfRangeException("value", "Exceeds MaxDate"); + throw new ArgumentOutOfRangeException("value", "Exceeds MaxDate"); #endif - } + } - minDate_ = value; - } - } + minDate_ = value; + } + } - /// - /// Get/set the maximum value that will match for this filter. - /// - /// Files with a LastWrite time greater than this value are excluded by the filter. - public DateTime MaxDate - { - get - { - return maxDate_; - } + /// + /// Get/set the maximum value that will match for this filter. + /// + /// Files with a LastWrite time greater than this value are excluded by the filter. + public DateTime MaxDate + { + get + { + return maxDate_; + } - set - { - if ( minDate_ > value ) { + set + { + if ( minDate_ > value ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException("value"); #else - throw new ArgumentOutOfRangeException("value", "Exceeds MinDate"); + throw new ArgumentOutOfRangeException("value", "Exceeds MinDate"); #endif - } + } - maxDate_ = value; - } - } - #endregion + maxDate_ = value; + } + } + #endregion - #region Instance Fields - long minSize_; - long maxSize_ = long.MaxValue; - DateTime minDate_ = DateTime.MinValue; - DateTime maxDate_ = DateTime.MaxValue; - #endregion - } + #region Instance Fields + long minSize_; + long maxSize_ = long.MaxValue; + DateTime minDate_ = DateTime.MinValue; + DateTime maxDate_ = DateTime.MaxValue; + #endregion + } - /// - /// NameAndSizeFilter filters based on name and file size. - /// - /// A sample showing how filters might be extended. - [Obsolete("Use ExtendedPathFilter instead")] - public class NameAndSizeFilter : PathFilter - { + /// + /// NameAndSizeFilter filters based on name and file size. + /// + /// A sample showing how filters might be extended. + [Obsolete("Use ExtendedPathFilter instead")] + public class NameAndSizeFilter : PathFilter + { - /// - /// Initialise a new instance of NameAndSizeFilter. - /// - /// The filter to apply. - /// The minimum file size to include. - /// The maximum file size to include. - public NameAndSizeFilter(string filter, long minSize, long maxSize) - : base(filter) - { - MinSize = minSize; - MaxSize = maxSize; - } - - /// - /// Test a filename to see if it matches the filter. - /// - /// The filename to test. - /// True if the filter matches, false otherwise. - public override bool IsMatch(string name) - { - bool result = base.IsMatch(name); + /// + /// Initialise a new instance of NameAndSizeFilter. + /// + /// The filter to apply. + /// The minimum file size to include. + /// The maximum file size to include. + public NameAndSizeFilter(string filter, long minSize, long maxSize) + : base(filter) + { + MinSize = minSize; + MaxSize = maxSize; + } + + /// + /// Test a filename to see if it matches the filter. + /// + /// The filename to test. + /// True if the filter matches, false otherwise. + public override bool IsMatch(string name) + { + bool result = base.IsMatch(name); - if ( result ) { - FileInfo fileInfo = new FileInfo(name); - long length = fileInfo.Length; - result = - (MinSize <= length) && - (MaxSize >= length); - } - return result; - } - - /// - /// Get/set the minimum size for a file that will match this filter. - /// - public long MinSize - { - get { return minSize_; } - set { - if ( (value < 0) || (maxSize_ < value) ) { - throw new ArgumentOutOfRangeException("value"); - } + if ( result ) { + FileInfo fileInfo = new FileInfo(name); + long length = fileInfo.Length; + result = + (MinSize <= length) && + (MaxSize >= length); + } + return result; + } + + /// + /// Get/set the minimum size for a file that will match this filter. + /// + public long MinSize + { + get { return minSize_; } + set { + if ( (value < 0) || (maxSize_ < value) ) { + throw new ArgumentOutOfRangeException("value"); + } - minSize_ = value; - } - } - - /// - /// Get/set the maximum size for a file that will match this filter. - /// - public long MaxSize - { - get { return maxSize_; } - set - { - if ( (value < 0) || (minSize_ > value) ) { - throw new ArgumentOutOfRangeException("value"); - } + minSize_ = value; + } + } + + /// + /// Get/set the maximum size for a file that will match this filter. + /// + public long MaxSize + { + get { return maxSize_; } + set + { + if ( (value < 0) || (minSize_ > value) ) { + throw new ArgumentOutOfRangeException("value"); + } - maxSize_ = value; - } - } + maxSize_ = value; + } + } - #region Instance Fields - long minSize_; - long maxSize_ = long.MaxValue; - #endregion - } + #region Instance Fields + long minSize_; + long maxSize_ = long.MaxValue; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Core/StreamUtils.cs b/External/Tools/AppMan/ZipLib/Core/StreamUtils.cs index 7abdce85b5..5216cbe1ab 100644 --- a/External/Tools/AppMan/ZipLib/Core/StreamUtils.cs +++ b/External/Tools/AppMan/ZipLib/Core/StreamUtils.cs @@ -38,209 +38,209 @@ namespace ICSharpCode.SharpZipLib.Core { - /// - /// Provides simple " utilities. - /// - public sealed class StreamUtils - { - /// - /// Read from a ensuring all the required data is read. - /// - /// The stream to read. - /// The buffer to fill. - /// - static public void ReadFully(Stream stream, byte[] buffer) - { - ReadFully(stream, buffer, 0, buffer.Length); - } - - /// - /// Read from a " ensuring all the required data is read. - /// - /// The stream to read data from. - /// The buffer to store data in. - /// The offset at which to begin storing data. - /// The number of bytes of data to store. - /// Required parameter is null - /// and or are invalid. - /// End of stream is encountered before all the data has been read. - static public void ReadFully(Stream stream, byte[] buffer, int offset, int count) - { - if ( stream == null ) { - throw new ArgumentNullException("stream"); - } - - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } - - // Offset can equal length when buffer and count are 0. - if ( (offset < 0) || (offset > buffer.Length) ) { - throw new ArgumentOutOfRangeException("offset"); - } - - if ( (count < 0) || (offset + count > buffer.Length) ) { - throw new ArgumentOutOfRangeException("count"); - } - - while ( count > 0 ) { - int readCount = stream.Read(buffer, offset, count); - if ( readCount <= 0 ) { - throw new EndOfStreamException(); - } - offset += readCount; - count -= readCount; - } - } - - /// - /// Copy the contents of one to another. - /// - /// The stream to source data from. - /// The stream to write data to. - /// The buffer to use during copying. - static public void Copy(Stream source, Stream destination, byte[] buffer) - { - if (source == null) { - throw new ArgumentNullException("source"); - } - - if (destination == null) { - throw new ArgumentNullException("destination"); - } - - if (buffer == null) { - throw new ArgumentNullException("buffer"); - } - - // Ensure a reasonable size of buffer is used without being prohibitive. - if (buffer.Length < 128) { - throw new ArgumentException("Buffer is too small", "buffer"); - } - - bool copying = true; - - while (copying) { - int bytesRead = source.Read(buffer, 0, buffer.Length); - if (bytesRead > 0) { - destination.Write(buffer, 0, bytesRead); - } - else { - destination.Flush(); - copying = false; - } - } - } - - /// - /// Copy the contents of one to another. - /// - /// The stream to source data from. - /// The stream to write data to. - /// The buffer to use during copying. - /// The progress handler delegate to use. - /// The minimum between progress updates. - /// The source for this event. - /// The name to use with the event. - /// This form is specialised for use within #Zip to support events during archive operations. - static public void Copy(Stream source, Stream destination, - byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name) - { - Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1); - } - - /// - /// Copy the contents of one to another. - /// - /// The stream to source data from. - /// The stream to write data to. - /// The buffer to use during copying. - /// The progress handler delegate to use. - /// The minimum between progress updates. - /// The source for this event. - /// The name to use with the event. - /// A predetermined fixed target value to use with progress updates. - /// If the value is negative the target is calculated by looking at the stream. - /// This form is specialised for use within #Zip to support events during archive operations. - static public void Copy(Stream source, Stream destination, - byte[] buffer, - ProgressHandler progressHandler, TimeSpan updateInterval, - object sender, string name, long fixedTarget) - { - if (source == null) { - throw new ArgumentNullException("source"); - } - - if (destination == null) { - throw new ArgumentNullException("destination"); - } - - if (buffer == null) { - throw new ArgumentNullException("buffer"); - } - - // Ensure a reasonable size of buffer is used without being prohibitive. - if (buffer.Length < 128) { - throw new ArgumentException("Buffer is too small", "buffer"); - } - - if (progressHandler == null) { - throw new ArgumentNullException("progressHandler"); - } - - bool copying = true; - - DateTime marker = DateTime.Now; - long processed = 0; - long target = 0; - - if (fixedTarget >= 0) { - target = fixedTarget; - } - else if (source.CanSeek) { - target = source.Length - source.Position; - } - - // Always fire 0% progress.. - ProgressEventArgs args = new ProgressEventArgs(name, processed, target); - progressHandler(sender, args); - - bool progressFired = true; - - while (copying) { - int bytesRead = source.Read(buffer, 0, buffer.Length); - if (bytesRead > 0) { - processed += bytesRead; - progressFired = false; - destination.Write(buffer, 0, bytesRead); - } - else { - destination.Flush(); - copying = false; - } - - if (DateTime.Now - marker > updateInterval) { - progressFired = true; - marker = DateTime.Now; - args = new ProgressEventArgs(name, processed, target); - progressHandler(sender, args); - - copying = args.ContinueRunning; - } - } - - if (!progressFired) { - args = new ProgressEventArgs(name, processed, target); - progressHandler(sender, args); - } - } - - /// - /// Initialise an instance of - /// - private StreamUtils() - { - // Do nothing. - } - } + /// + /// Provides simple " utilities. + /// + public sealed class StreamUtils + { + /// + /// Read from a ensuring all the required data is read. + /// + /// The stream to read. + /// The buffer to fill. + /// + static public void ReadFully(Stream stream, byte[] buffer) + { + ReadFully(stream, buffer, 0, buffer.Length); + } + + /// + /// Read from a " ensuring all the required data is read. + /// + /// The stream to read data from. + /// The buffer to store data in. + /// The offset at which to begin storing data. + /// The number of bytes of data to store. + /// Required parameter is null + /// and or are invalid. + /// End of stream is encountered before all the data has been read. + static public void ReadFully(Stream stream, byte[] buffer, int offset, int count) + { + if ( stream == null ) { + throw new ArgumentNullException("stream"); + } + + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } + + // Offset can equal length when buffer and count are 0. + if ( (offset < 0) || (offset > buffer.Length) ) { + throw new ArgumentOutOfRangeException("offset"); + } + + if ( (count < 0) || (offset + count > buffer.Length) ) { + throw new ArgumentOutOfRangeException("count"); + } + + while ( count > 0 ) { + int readCount = stream.Read(buffer, offset, count); + if ( readCount <= 0 ) { + throw new EndOfStreamException(); + } + offset += readCount; + count -= readCount; + } + } + + /// + /// Copy the contents of one to another. + /// + /// The stream to source data from. + /// The stream to write data to. + /// The buffer to use during copying. + static public void Copy(Stream source, Stream destination, byte[] buffer) + { + if (source == null) { + throw new ArgumentNullException("source"); + } + + if (destination == null) { + throw new ArgumentNullException("destination"); + } + + if (buffer == null) { + throw new ArgumentNullException("buffer"); + } + + // Ensure a reasonable size of buffer is used without being prohibitive. + if (buffer.Length < 128) { + throw new ArgumentException("Buffer is too small", "buffer"); + } + + bool copying = true; + + while (copying) { + int bytesRead = source.Read(buffer, 0, buffer.Length); + if (bytesRead > 0) { + destination.Write(buffer, 0, bytesRead); + } + else { + destination.Flush(); + copying = false; + } + } + } + + /// + /// Copy the contents of one to another. + /// + /// The stream to source data from. + /// The stream to write data to. + /// The buffer to use during copying. + /// The progress handler delegate to use. + /// The minimum between progress updates. + /// The source for this event. + /// The name to use with the event. + /// This form is specialised for use within #Zip to support events during archive operations. + static public void Copy(Stream source, Stream destination, + byte[] buffer, ProgressHandler progressHandler, TimeSpan updateInterval, object sender, string name) + { + Copy(source, destination, buffer, progressHandler, updateInterval, sender, name, -1); + } + + /// + /// Copy the contents of one to another. + /// + /// The stream to source data from. + /// The stream to write data to. + /// The buffer to use during copying. + /// The progress handler delegate to use. + /// The minimum between progress updates. + /// The source for this event. + /// The name to use with the event. + /// A predetermined fixed target value to use with progress updates. + /// If the value is negative the target is calculated by looking at the stream. + /// This form is specialised for use within #Zip to support events during archive operations. + static public void Copy(Stream source, Stream destination, + byte[] buffer, + ProgressHandler progressHandler, TimeSpan updateInterval, + object sender, string name, long fixedTarget) + { + if (source == null) { + throw new ArgumentNullException("source"); + } + + if (destination == null) { + throw new ArgumentNullException("destination"); + } + + if (buffer == null) { + throw new ArgumentNullException("buffer"); + } + + // Ensure a reasonable size of buffer is used without being prohibitive. + if (buffer.Length < 128) { + throw new ArgumentException("Buffer is too small", "buffer"); + } + + if (progressHandler == null) { + throw new ArgumentNullException("progressHandler"); + } + + bool copying = true; + + DateTime marker = DateTime.Now; + long processed = 0; + long target = 0; + + if (fixedTarget >= 0) { + target = fixedTarget; + } + else if (source.CanSeek) { + target = source.Length - source.Position; + } + + // Always fire 0% progress.. + ProgressEventArgs args = new ProgressEventArgs(name, processed, target); + progressHandler(sender, args); + + bool progressFired = true; + + while (copying) { + int bytesRead = source.Read(buffer, 0, buffer.Length); + if (bytesRead > 0) { + processed += bytesRead; + progressFired = false; + destination.Write(buffer, 0, bytesRead); + } + else { + destination.Flush(); + copying = false; + } + + if (DateTime.Now - marker > updateInterval) { + progressFired = true; + marker = DateTime.Now; + args = new ProgressEventArgs(name, processed, target); + progressHandler(sender, args); + + copying = args.ContinueRunning; + } + } + + if (!progressFired) { + args = new ProgressEventArgs(name, processed, target); + progressHandler(sender, args); + } + } + + /// + /// Initialise an instance of + /// + private StreamUtils() + { + // Do nothing. + } + } } diff --git a/External/Tools/AppMan/ZipLib/Core/WindowsPathUtils.cs b/External/Tools/AppMan/ZipLib/Core/WindowsPathUtils.cs index 209194506e..668a1e3937 100644 --- a/External/Tools/AppMan/ZipLib/Core/WindowsPathUtils.cs +++ b/External/Tools/AppMan/ZipLib/Core/WindowsPathUtils.cs @@ -35,60 +35,60 @@ namespace ICSharpCode.SharpZipLib.Core { - /// - /// WindowsPathUtils provides simple utilities for handling windows paths. - /// - public abstract class WindowsPathUtils - { - /// - /// Initializes a new instance of the class. - /// - internal WindowsPathUtils() - { - } - - /// - /// Remove any path root present in the path - /// - /// A containing path information. - /// The path with the root removed if it was present; path otherwise. - /// Unlike the class the path isnt otherwise checked for validity. - public static string DropPathRoot(string path) - { - string result = path; - - if ( (path != null) && (path.Length > 0) ) { - if ((path[0] == '\\') || (path[0] == '/')) { - // UNC name ? - if ((path.Length > 1) && ((path[1] == '\\') || (path[1] == '/'))) { - int index = 2; - int elements = 2; + /// + /// WindowsPathUtils provides simple utilities for handling windows paths. + /// + public abstract class WindowsPathUtils + { + /// + /// Initializes a new instance of the class. + /// + internal WindowsPathUtils() + { + } + + /// + /// Remove any path root present in the path + /// + /// A containing path information. + /// The path with the root removed if it was present; path otherwise. + /// Unlike the class the path isnt otherwise checked for validity. + public static string DropPathRoot(string path) + { + string result = path; + + if ( (path != null) && (path.Length > 0) ) { + if ((path[0] == '\\') || (path[0] == '/')) { + // UNC name ? + if ((path.Length > 1) && ((path[1] == '\\') || (path[1] == '/'))) { + int index = 2; + int elements = 2; - // Scan for two separate elements \\machine\share\restofpath - while ((index <= path.Length) && - (((path[index] != '\\') && (path[index] != '/')) || (--elements > 0))) { - index++; - } + // Scan for two separate elements \\machine\share\restofpath + while ((index <= path.Length) && + (((path[index] != '\\') && (path[index] != '/')) || (--elements > 0))) { + index++; + } - index++; + index++; - if (index < path.Length) { - result = path.Substring(index); - } - else { - result = ""; - } - } - } - else if ((path.Length > 1) && (path[1] == ':')) { - int dropCount = 2; - if ((path.Length > 2) && ((path[2] == '\\') || (path[2] == '/'))) { - dropCount = 3; - } - result = result.Remove(0, dropCount); - } - } - return result; - } - } + if (index < path.Length) { + result = path.Substring(index); + } + else { + result = ""; + } + } + } + else if ((path.Length > 1) && (path[1] == ':')) { + int dropCount = 2; + if ((path.Length > 2) && ((path[2] == '\\') || (path[2] == '/'))) { + dropCount = 3; + } + result = result.Remove(0, dropCount); + } + } + return result; + } + } } diff --git a/External/Tools/AppMan/ZipLib/Encryption/PkzipClassic.cs b/External/Tools/AppMan/ZipLib/Encryption/PkzipClassic.cs index 7bed67aceb..96cd1c278c 100644 --- a/External/Tools/AppMan/ZipLib/Encryption/PkzipClassic.cs +++ b/External/Tools/AppMan/ZipLib/Encryption/PkzipClassic.cs @@ -44,455 +44,455 @@ namespace ICSharpCode.SharpZipLib.Encryption { - /// - /// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives. - /// While it has been superceded by more recent and more powerful algorithms, its still in use and - /// is viable for preventing casual snooping - /// - public abstract class PkzipClassic : SymmetricAlgorithm - { - /// - /// Generates new encryption keys based on given seed - /// - /// The seed value to initialise keys with. - /// A new key value. - static public byte[] GenerateKeys(byte[] seed) - { - if ( seed == null ) { - throw new ArgumentNullException("seed"); - } - - if ( seed.Length == 0 ) { - throw new ArgumentException("Length is zero", "seed"); - } - - uint[] newKeys = new uint[] { - 0x12345678, - 0x23456789, - 0x34567890 - }; - - for (int i = 0; i < seed.Length; ++i) { - newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]); - newKeys[1] = newKeys[1] + (byte)newKeys[0]; - newKeys[1] = newKeys[1] * 134775813 + 1; - newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte)(newKeys[1] >> 24)); - } - - byte[] result = new byte[12]; - result[0] = (byte)(newKeys[0] & 0xff); - result[1] = (byte)((newKeys[0] >> 8) & 0xff); - result[2] = (byte)((newKeys[0] >> 16) & 0xff); - result[3] = (byte)((newKeys[0] >> 24) & 0xff); - result[4] = (byte)(newKeys[1] & 0xff); - result[5] = (byte)((newKeys[1] >> 8) & 0xff); - result[6] = (byte)((newKeys[1] >> 16) & 0xff); - result[7] = (byte)((newKeys[1] >> 24) & 0xff); - result[8] = (byte)(newKeys[2] & 0xff); - result[9] = (byte)((newKeys[2] >> 8) & 0xff); - result[10] = (byte)((newKeys[2] >> 16) & 0xff); - result[11] = (byte)((newKeys[2] >> 24) & 0xff); - return result; - } - } - - /// - /// PkzipClassicCryptoBase provides the low level facilities for encryption - /// and decryption using the PkzipClassic algorithm. - /// - class PkzipClassicCryptoBase - { - /// - /// Transform a single byte - /// - /// - /// The transformed value - /// - protected byte TransformByte() - { - uint temp = ((keys[2] & 0xFFFF) | 2); - return (byte)((temp * (temp ^ 1)) >> 8); - } - - /// - /// Set the key schedule for encryption/decryption. - /// - /// The data use to set the keys from. - protected void SetKeys(byte[] keyData) - { - if ( keyData == null ) { - throw new ArgumentNullException("keyData"); - } - - if ( keyData.Length != 12 ) { - throw new InvalidOperationException("Key length is not valid"); - } - - keys = new uint[3]; - keys[0] = (uint)((keyData[3] << 24) | (keyData[2] << 16) | (keyData[1] << 8) | keyData[0]); - keys[1] = (uint)((keyData[7] << 24) | (keyData[6] << 16) | (keyData[5] << 8) | keyData[4]); - keys[2] = (uint)((keyData[11] << 24) | (keyData[10] << 16) | (keyData[9] << 8) | keyData[8]); - } - - /// - /// Update encryption keys - /// - protected void UpdateKeys(byte ch) - { - keys[0] = Crc32.ComputeCrc32(keys[0], ch); - keys[1] = keys[1] + (byte)keys[0]; - keys[1] = keys[1] * 134775813 + 1; - keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24)); - } - - /// - /// Reset the internal state. - /// - protected void Reset() - { - keys[0] = 0; - keys[1] = 0; - keys[2] = 0; - } - - #region Instance Fields - uint[] keys; - #endregion - } - - /// - /// PkzipClassic CryptoTransform for encryption. - /// - class PkzipClassicEncryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform - { - /// - /// Initialise a new instance of - /// - /// The key block to use. - internal PkzipClassicEncryptCryptoTransform(byte[] keyBlock) - { - SetKeys(keyBlock); - } - - #region ICryptoTransform Members - - /// - /// Transforms the specified region of the specified byte array. - /// - /// The input for which to compute the transform. - /// The offset into the byte array from which to begin using data. - /// The number of bytes in the byte array to use as data. - /// The computed transform. - public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) - { - byte[] result = new byte[inputCount]; - TransformBlock(inputBuffer, inputOffset, inputCount, result, 0); - return result; - } - - /// - /// Transforms the specified region of the input byte array and copies - /// the resulting transform to the specified region of the output byte array. - /// - /// The input for which to compute the transform. - /// The offset into the input byte array from which to begin using data. - /// The number of bytes in the input byte array to use as data. - /// The output to which to write the transform. - /// The offset into the output byte array from which to begin writing data. - /// The number of bytes written. - public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) - { - for (int i = inputOffset; i < inputOffset + inputCount; ++i) { - byte oldbyte = inputBuffer[i]; - outputBuffer[outputOffset++] = (byte)(inputBuffer[i] ^ TransformByte()); - UpdateKeys(oldbyte); - } - return inputCount; - } - - /// - /// Gets a value indicating whether the current transform can be reused. - /// - public bool CanReuseTransform - { - get { - return true; - } - } - - /// - /// Gets the size of the input data blocks in bytes. - /// - public int InputBlockSize - { - get { - return 1; - } - } - - /// - /// Gets the size of the output data blocks in bytes. - /// - public int OutputBlockSize - { - get { - return 1; - } - } - - /// - /// Gets a value indicating whether multiple blocks can be transformed. - /// - public bool CanTransformMultipleBlocks - { - get { - return true; - } - } - - #endregion - - #region IDisposable Members - - /// - /// Cleanup internal state. - /// - public void Dispose() - { - Reset(); - } - - #endregion - } - - - /// - /// PkzipClassic CryptoTransform for decryption. - /// - class PkzipClassicDecryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform - { - /// - /// Initialise a new instance of . - /// - /// The key block to decrypt with. - internal PkzipClassicDecryptCryptoTransform(byte[] keyBlock) - { - SetKeys(keyBlock); - } - - #region ICryptoTransform Members - - /// - /// Transforms the specified region of the specified byte array. - /// - /// The input for which to compute the transform. - /// The offset into the byte array from which to begin using data. - /// The number of bytes in the byte array to use as data. - /// The computed transform. - public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) - { - byte[] result = new byte[inputCount]; - TransformBlock(inputBuffer, inputOffset, inputCount, result, 0); - return result; - } - - /// - /// Transforms the specified region of the input byte array and copies - /// the resulting transform to the specified region of the output byte array. - /// - /// The input for which to compute the transform. - /// The offset into the input byte array from which to begin using data. - /// The number of bytes in the input byte array to use as data. - /// The output to which to write the transform. - /// The offset into the output byte array from which to begin writing data. - /// The number of bytes written. - public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) - { - for (int i = inputOffset; i < inputOffset + inputCount; ++i) { - byte newByte = (byte)(inputBuffer[i] ^ TransformByte()); - outputBuffer[outputOffset++] = newByte; - UpdateKeys(newByte); - } - return inputCount; - } - - /// - /// Gets a value indicating whether the current transform can be reused. - /// - public bool CanReuseTransform - { - get { - return true; - } - } - - /// - /// Gets the size of the input data blocks in bytes. - /// - public int InputBlockSize - { - get { - return 1; - } - } - - /// - /// Gets the size of the output data blocks in bytes. - /// - public int OutputBlockSize - { - get { - return 1; - } - } - - /// - /// Gets a value indicating whether multiple blocks can be transformed. - /// - public bool CanTransformMultipleBlocks - { - get { - return true; - } - } - - #endregion - - #region IDisposable Members - - /// - /// Cleanup internal state. - /// - public void Dispose() - { - Reset(); - } - - #endregion - } - - /// - /// Defines a wrapper object to access the Pkzip algorithm. - /// This class cannot be inherited. - /// - public sealed class PkzipClassicManaged : PkzipClassic - { - /// - /// Get / set the applicable block size in bits. - /// - /// The only valid block size is 8. - public override int BlockSize - { - get { - return 8; - } - - set { - if (value != 8) { - throw new CryptographicException("Block size is invalid"); - } - } - } - - /// - /// Get an array of legal key sizes. - /// - public override KeySizes[] LegalKeySizes - { - get { - KeySizes[] keySizes = new KeySizes[1]; - keySizes[0] = new KeySizes(12 * 8, 12 * 8, 0); - return keySizes; - } - } - - /// - /// Generate an initial vector. - /// - public override void GenerateIV() - { - // Do nothing. - } - - /// - /// Get an array of legal block sizes. - /// - public override KeySizes[] LegalBlockSizes - { - get { - KeySizes[] keySizes = new KeySizes[1]; - keySizes[0] = new KeySizes(1 * 8, 1 * 8, 0); - return keySizes; - } - } - - /// - /// Get / set the key value applicable. - /// - public override byte[] Key - { - get { - if ( key_ == null ) { - GenerateKey(); - } - - return (byte[]) key_.Clone(); - } - - set { - if ( value == null ) { - throw new ArgumentNullException("value"); - } - - if ( value.Length != 12 ) { - throw new CryptographicException("Key size is illegal"); - } - - key_ = (byte[]) value.Clone(); - } - } - - /// - /// Generate a new random key. - /// - public override void GenerateKey() - { - key_ = new byte[12]; - Random rnd = new Random(); - rnd.NextBytes(key_); - } - - /// - /// Create an encryptor. - /// - /// The key to use for this encryptor. - /// Initialisation vector for the new encryptor. - /// Returns a new PkzipClassic encryptor - public override ICryptoTransform CreateEncryptor( - byte[] rgbKey, - byte[] rgbIV) - { - key_ = rgbKey; - return new PkzipClassicEncryptCryptoTransform(Key); - } - - /// - /// Create a decryptor. - /// - /// Keys to use for this new decryptor. - /// Initialisation vector for the new decryptor. - /// Returns a new decryptor. - public override ICryptoTransform CreateDecryptor( - byte[] rgbKey, - byte[] rgbIV) - { - key_ = rgbKey; - return new PkzipClassicDecryptCryptoTransform(Key); - } - - #region Instance Fields - byte[] key_; - #endregion - } + /// + /// PkzipClassic embodies the classic or original encryption facilities used in Pkzip archives. + /// While it has been superceded by more recent and more powerful algorithms, its still in use and + /// is viable for preventing casual snooping + /// + public abstract class PkzipClassic : SymmetricAlgorithm + { + /// + /// Generates new encryption keys based on given seed + /// + /// The seed value to initialise keys with. + /// A new key value. + static public byte[] GenerateKeys(byte[] seed) + { + if ( seed == null ) { + throw new ArgumentNullException("seed"); + } + + if ( seed.Length == 0 ) { + throw new ArgumentException("Length is zero", "seed"); + } + + uint[] newKeys = new uint[] { + 0x12345678, + 0x23456789, + 0x34567890 + }; + + for (int i = 0; i < seed.Length; ++i) { + newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]); + newKeys[1] = newKeys[1] + (byte)newKeys[0]; + newKeys[1] = newKeys[1] * 134775813 + 1; + newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte)(newKeys[1] >> 24)); + } + + byte[] result = new byte[12]; + result[0] = (byte)(newKeys[0] & 0xff); + result[1] = (byte)((newKeys[0] >> 8) & 0xff); + result[2] = (byte)((newKeys[0] >> 16) & 0xff); + result[3] = (byte)((newKeys[0] >> 24) & 0xff); + result[4] = (byte)(newKeys[1] & 0xff); + result[5] = (byte)((newKeys[1] >> 8) & 0xff); + result[6] = (byte)((newKeys[1] >> 16) & 0xff); + result[7] = (byte)((newKeys[1] >> 24) & 0xff); + result[8] = (byte)(newKeys[2] & 0xff); + result[9] = (byte)((newKeys[2] >> 8) & 0xff); + result[10] = (byte)((newKeys[2] >> 16) & 0xff); + result[11] = (byte)((newKeys[2] >> 24) & 0xff); + return result; + } + } + + /// + /// PkzipClassicCryptoBase provides the low level facilities for encryption + /// and decryption using the PkzipClassic algorithm. + /// + class PkzipClassicCryptoBase + { + /// + /// Transform a single byte + /// + /// + /// The transformed value + /// + protected byte TransformByte() + { + uint temp = ((keys[2] & 0xFFFF) | 2); + return (byte)((temp * (temp ^ 1)) >> 8); + } + + /// + /// Set the key schedule for encryption/decryption. + /// + /// The data use to set the keys from. + protected void SetKeys(byte[] keyData) + { + if ( keyData == null ) { + throw new ArgumentNullException("keyData"); + } + + if ( keyData.Length != 12 ) { + throw new InvalidOperationException("Key length is not valid"); + } + + keys = new uint[3]; + keys[0] = (uint)((keyData[3] << 24) | (keyData[2] << 16) | (keyData[1] << 8) | keyData[0]); + keys[1] = (uint)((keyData[7] << 24) | (keyData[6] << 16) | (keyData[5] << 8) | keyData[4]); + keys[2] = (uint)((keyData[11] << 24) | (keyData[10] << 16) | (keyData[9] << 8) | keyData[8]); + } + + /// + /// Update encryption keys + /// + protected void UpdateKeys(byte ch) + { + keys[0] = Crc32.ComputeCrc32(keys[0], ch); + keys[1] = keys[1] + (byte)keys[0]; + keys[1] = keys[1] * 134775813 + 1; + keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24)); + } + + /// + /// Reset the internal state. + /// + protected void Reset() + { + keys[0] = 0; + keys[1] = 0; + keys[2] = 0; + } + + #region Instance Fields + uint[] keys; + #endregion + } + + /// + /// PkzipClassic CryptoTransform for encryption. + /// + class PkzipClassicEncryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform + { + /// + /// Initialise a new instance of + /// + /// The key block to use. + internal PkzipClassicEncryptCryptoTransform(byte[] keyBlock) + { + SetKeys(keyBlock); + } + + #region ICryptoTransform Members + + /// + /// Transforms the specified region of the specified byte array. + /// + /// The input for which to compute the transform. + /// The offset into the byte array from which to begin using data. + /// The number of bytes in the byte array to use as data. + /// The computed transform. + public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) + { + byte[] result = new byte[inputCount]; + TransformBlock(inputBuffer, inputOffset, inputCount, result, 0); + return result; + } + + /// + /// Transforms the specified region of the input byte array and copies + /// the resulting transform to the specified region of the output byte array. + /// + /// The input for which to compute the transform. + /// The offset into the input byte array from which to begin using data. + /// The number of bytes in the input byte array to use as data. + /// The output to which to write the transform. + /// The offset into the output byte array from which to begin writing data. + /// The number of bytes written. + public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) + { + for (int i = inputOffset; i < inputOffset + inputCount; ++i) { + byte oldbyte = inputBuffer[i]; + outputBuffer[outputOffset++] = (byte)(inputBuffer[i] ^ TransformByte()); + UpdateKeys(oldbyte); + } + return inputCount; + } + + /// + /// Gets a value indicating whether the current transform can be reused. + /// + public bool CanReuseTransform + { + get { + return true; + } + } + + /// + /// Gets the size of the input data blocks in bytes. + /// + public int InputBlockSize + { + get { + return 1; + } + } + + /// + /// Gets the size of the output data blocks in bytes. + /// + public int OutputBlockSize + { + get { + return 1; + } + } + + /// + /// Gets a value indicating whether multiple blocks can be transformed. + /// + public bool CanTransformMultipleBlocks + { + get { + return true; + } + } + + #endregion + + #region IDisposable Members + + /// + /// Cleanup internal state. + /// + public void Dispose() + { + Reset(); + } + + #endregion + } + + + /// + /// PkzipClassic CryptoTransform for decryption. + /// + class PkzipClassicDecryptCryptoTransform : PkzipClassicCryptoBase, ICryptoTransform + { + /// + /// Initialise a new instance of . + /// + /// The key block to decrypt with. + internal PkzipClassicDecryptCryptoTransform(byte[] keyBlock) + { + SetKeys(keyBlock); + } + + #region ICryptoTransform Members + + /// + /// Transforms the specified region of the specified byte array. + /// + /// The input for which to compute the transform. + /// The offset into the byte array from which to begin using data. + /// The number of bytes in the byte array to use as data. + /// The computed transform. + public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) + { + byte[] result = new byte[inputCount]; + TransformBlock(inputBuffer, inputOffset, inputCount, result, 0); + return result; + } + + /// + /// Transforms the specified region of the input byte array and copies + /// the resulting transform to the specified region of the output byte array. + /// + /// The input for which to compute the transform. + /// The offset into the input byte array from which to begin using data. + /// The number of bytes in the input byte array to use as data. + /// The output to which to write the transform. + /// The offset into the output byte array from which to begin writing data. + /// The number of bytes written. + public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) + { + for (int i = inputOffset; i < inputOffset + inputCount; ++i) { + byte newByte = (byte)(inputBuffer[i] ^ TransformByte()); + outputBuffer[outputOffset++] = newByte; + UpdateKeys(newByte); + } + return inputCount; + } + + /// + /// Gets a value indicating whether the current transform can be reused. + /// + public bool CanReuseTransform + { + get { + return true; + } + } + + /// + /// Gets the size of the input data blocks in bytes. + /// + public int InputBlockSize + { + get { + return 1; + } + } + + /// + /// Gets the size of the output data blocks in bytes. + /// + public int OutputBlockSize + { + get { + return 1; + } + } + + /// + /// Gets a value indicating whether multiple blocks can be transformed. + /// + public bool CanTransformMultipleBlocks + { + get { + return true; + } + } + + #endregion + + #region IDisposable Members + + /// + /// Cleanup internal state. + /// + public void Dispose() + { + Reset(); + } + + #endregion + } + + /// + /// Defines a wrapper object to access the Pkzip algorithm. + /// This class cannot be inherited. + /// + public sealed class PkzipClassicManaged : PkzipClassic + { + /// + /// Get / set the applicable block size in bits. + /// + /// The only valid block size is 8. + public override int BlockSize + { + get { + return 8; + } + + set { + if (value != 8) { + throw new CryptographicException("Block size is invalid"); + } + } + } + + /// + /// Get an array of legal key sizes. + /// + public override KeySizes[] LegalKeySizes + { + get { + KeySizes[] keySizes = new KeySizes[1]; + keySizes[0] = new KeySizes(12 * 8, 12 * 8, 0); + return keySizes; + } + } + + /// + /// Generate an initial vector. + /// + public override void GenerateIV() + { + // Do nothing. + } + + /// + /// Get an array of legal block sizes. + /// + public override KeySizes[] LegalBlockSizes + { + get { + KeySizes[] keySizes = new KeySizes[1]; + keySizes[0] = new KeySizes(1 * 8, 1 * 8, 0); + return keySizes; + } + } + + /// + /// Get / set the key value applicable. + /// + public override byte[] Key + { + get { + if ( key_ == null ) { + GenerateKey(); + } + + return (byte[]) key_.Clone(); + } + + set { + if ( value == null ) { + throw new ArgumentNullException("value"); + } + + if ( value.Length != 12 ) { + throw new CryptographicException("Key size is illegal"); + } + + key_ = (byte[]) value.Clone(); + } + } + + /// + /// Generate a new random key. + /// + public override void GenerateKey() + { + key_ = new byte[12]; + Random rnd = new Random(); + rnd.NextBytes(key_); + } + + /// + /// Create an encryptor. + /// + /// The key to use for this encryptor. + /// Initialisation vector for the new encryptor. + /// Returns a new PkzipClassic encryptor + public override ICryptoTransform CreateEncryptor( + byte[] rgbKey, + byte[] rgbIV) + { + key_ = rgbKey; + return new PkzipClassicEncryptCryptoTransform(Key); + } + + /// + /// Create a decryptor. + /// + /// Keys to use for this new decryptor. + /// Initialisation vector for the new decryptor. + /// Returns a new decryptor. + public override ICryptoTransform CreateDecryptor( + byte[] rgbKey, + byte[] rgbIV) + { + key_ = rgbKey; + return new PkzipClassicDecryptCryptoTransform(Key); + } + + #region Instance Fields + byte[] key_; + #endregion + } } #endif diff --git a/External/Tools/AppMan/ZipLib/Encryption/ZipAESStream.cs b/External/Tools/AppMan/ZipLib/Encryption/ZipAESStream.cs index d57dc34468..4e3b167387 100644 --- a/External/Tools/AppMan/ZipLib/Encryption/ZipAESStream.cs +++ b/External/Tools/AppMan/ZipLib/Encryption/ZipAESStream.cs @@ -43,128 +43,128 @@ namespace ICSharpCode.SharpZipLib.Encryption { - // Based on information from http://www.winzip.com/aes_info.htm - // and http://www.gladman.me.uk/cryptography_technology/fileencrypt/ - - /// - /// Encrypts and decrypts AES ZIP - /// - internal class ZipAESStream : CryptoStream { - - /// - /// Constructor - /// - /// The stream on which to perform the cryptographic transformation. - /// Instance of ZipAESTransform - /// Read or Write - public ZipAESStream(Stream stream, ZipAESTransform transform, CryptoStreamMode mode) - : base(stream, transform, mode) { - - _stream = stream; - _transform = transform; - _slideBuffer = new byte[1024]; - - _blockAndAuth = CRYPTO_BLOCK_SIZE + AUTH_CODE_LENGTH; - - // mode: - // CryptoStreamMode.Read means we read from "stream" and pass decrypted to our Read() method. - // Write bypasses this stream and uses the Transform directly. - if (mode != CryptoStreamMode.Read) { - throw new Exception("ZipAESStream only for read"); - } - } - - // The final n bytes of the AES stream contain the Auth Code. - private const int AUTH_CODE_LENGTH = 10; - - private Stream _stream; - private ZipAESTransform _transform; - private byte[] _slideBuffer; - private int _slideBufStartPos; - private int _slideBufFreePos; - // Blocksize is always 16 here, even for AES-256 which has transform.InputBlockSize of 32. - private const int CRYPTO_BLOCK_SIZE = 16; - private int _blockAndAuth; - - /// - /// Reads a sequence of bytes from the current CryptoStream into buffer, - /// and advances the position within the stream by the number of bytes read. - /// - public override int Read(byte[] outBuffer, int offset, int count) { - int nBytes = 0; - while (nBytes < count) { - // Calculate buffer quantities vs read-ahead size, and check for sufficient free space - int byteCount = _slideBufFreePos - _slideBufStartPos; - - // Need to handle final block and Auth Code specially, but don't know total data length. - // Maintain a read-ahead equal to the length of (crypto block + Auth Code). - // When that runs out we can detect these final sections. - int lengthToRead = _blockAndAuth - byteCount; - if (_slideBuffer.Length - _slideBufFreePos < lengthToRead) { - // Shift the data to the beginning of the buffer - int iTo = 0; - for (int iFrom = _slideBufStartPos; iFrom < _slideBufFreePos; iFrom++, iTo++) { - _slideBuffer[iTo] = _slideBuffer[iFrom]; - } - _slideBufFreePos -= _slideBufStartPos; // Note the -= - _slideBufStartPos = 0; - } - int obtained = _stream.Read(_slideBuffer, _slideBufFreePos, lengthToRead); - _slideBufFreePos += obtained; - - // Recalculate how much data we now have - byteCount = _slideBufFreePos - _slideBufStartPos; - if (byteCount >= _blockAndAuth) { - // At least a 16 byte block and an auth code remains. - _transform.TransformBlock(_slideBuffer, - _slideBufStartPos, - CRYPTO_BLOCK_SIZE, - outBuffer, - offset); - nBytes += CRYPTO_BLOCK_SIZE; - offset += CRYPTO_BLOCK_SIZE; - _slideBufStartPos += CRYPTO_BLOCK_SIZE; - } else { - // Last round. - if (byteCount > AUTH_CODE_LENGTH) { - // At least one byte of data plus auth code - int finalBlock = byteCount - AUTH_CODE_LENGTH; - _transform.TransformBlock(_slideBuffer, - _slideBufStartPos, - finalBlock, - outBuffer, - offset); - - nBytes += finalBlock; - _slideBufStartPos += finalBlock; - } - else if (byteCount < AUTH_CODE_LENGTH) - throw new Exception("Internal error missed auth code"); // Coding bug - // Final block done. Check Auth code. - byte[] calcAuthCode = _transform.GetAuthCode(); - for (int i = 0; i < AUTH_CODE_LENGTH; i++) { - if (calcAuthCode[i] != _slideBuffer[_slideBufStartPos + i]) { - throw new Exception("AES Authentication Code does not match. This is a super-CRC check on the data in the file after compression and encryption. \r\n" - + "The file may be damaged."); - } - } - - break; // Reached the auth code - } - } - return nBytes; - } - - /// - /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. - /// - /// An array of bytes. This method copies count bytes from buffer to the current stream. - /// The byte offset in buffer at which to begin copying bytes to the current stream. - /// The number of bytes to be written to the current stream. - public override void Write(byte[] buffer, int offset, int count) { - // ZipAESStream is used for reading but not for writing. Writing uses the ZipAESTransform directly. - throw new NotImplementedException(); - } - } + // Based on information from http://www.winzip.com/aes_info.htm + // and http://www.gladman.me.uk/cryptography_technology/fileencrypt/ + + /// + /// Encrypts and decrypts AES ZIP + /// + internal class ZipAESStream : CryptoStream { + + /// + /// Constructor + /// + /// The stream on which to perform the cryptographic transformation. + /// Instance of ZipAESTransform + /// Read or Write + public ZipAESStream(Stream stream, ZipAESTransform transform, CryptoStreamMode mode) + : base(stream, transform, mode) { + + _stream = stream; + _transform = transform; + _slideBuffer = new byte[1024]; + + _blockAndAuth = CRYPTO_BLOCK_SIZE + AUTH_CODE_LENGTH; + + // mode: + // CryptoStreamMode.Read means we read from "stream" and pass decrypted to our Read() method. + // Write bypasses this stream and uses the Transform directly. + if (mode != CryptoStreamMode.Read) { + throw new Exception("ZipAESStream only for read"); + } + } + + // The final n bytes of the AES stream contain the Auth Code. + private const int AUTH_CODE_LENGTH = 10; + + private Stream _stream; + private ZipAESTransform _transform; + private byte[] _slideBuffer; + private int _slideBufStartPos; + private int _slideBufFreePos; + // Blocksize is always 16 here, even for AES-256 which has transform.InputBlockSize of 32. + private const int CRYPTO_BLOCK_SIZE = 16; + private int _blockAndAuth; + + /// + /// Reads a sequence of bytes from the current CryptoStream into buffer, + /// and advances the position within the stream by the number of bytes read. + /// + public override int Read(byte[] outBuffer, int offset, int count) { + int nBytes = 0; + while (nBytes < count) { + // Calculate buffer quantities vs read-ahead size, and check for sufficient free space + int byteCount = _slideBufFreePos - _slideBufStartPos; + + // Need to handle final block and Auth Code specially, but don't know total data length. + // Maintain a read-ahead equal to the length of (crypto block + Auth Code). + // When that runs out we can detect these final sections. + int lengthToRead = _blockAndAuth - byteCount; + if (_slideBuffer.Length - _slideBufFreePos < lengthToRead) { + // Shift the data to the beginning of the buffer + int iTo = 0; + for (int iFrom = _slideBufStartPos; iFrom < _slideBufFreePos; iFrom++, iTo++) { + _slideBuffer[iTo] = _slideBuffer[iFrom]; + } + _slideBufFreePos -= _slideBufStartPos; // Note the -= + _slideBufStartPos = 0; + } + int obtained = _stream.Read(_slideBuffer, _slideBufFreePos, lengthToRead); + _slideBufFreePos += obtained; + + // Recalculate how much data we now have + byteCount = _slideBufFreePos - _slideBufStartPos; + if (byteCount >= _blockAndAuth) { + // At least a 16 byte block and an auth code remains. + _transform.TransformBlock(_slideBuffer, + _slideBufStartPos, + CRYPTO_BLOCK_SIZE, + outBuffer, + offset); + nBytes += CRYPTO_BLOCK_SIZE; + offset += CRYPTO_BLOCK_SIZE; + _slideBufStartPos += CRYPTO_BLOCK_SIZE; + } else { + // Last round. + if (byteCount > AUTH_CODE_LENGTH) { + // At least one byte of data plus auth code + int finalBlock = byteCount - AUTH_CODE_LENGTH; + _transform.TransformBlock(_slideBuffer, + _slideBufStartPos, + finalBlock, + outBuffer, + offset); + + nBytes += finalBlock; + _slideBufStartPos += finalBlock; + } + else if (byteCount < AUTH_CODE_LENGTH) + throw new Exception("Internal error missed auth code"); // Coding bug + // Final block done. Check Auth code. + byte[] calcAuthCode = _transform.GetAuthCode(); + for (int i = 0; i < AUTH_CODE_LENGTH; i++) { + if (calcAuthCode[i] != _slideBuffer[_slideBufStartPos + i]) { + throw new Exception("AES Authentication Code does not match. This is a super-CRC check on the data in the file after compression and encryption. \r\n" + + "The file may be damaged."); + } + } + + break; // Reached the auth code + } + } + return nBytes; + } + + /// + /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. + /// + /// An array of bytes. This method copies count bytes from buffer to the current stream. + /// The byte offset in buffer at which to begin copying bytes to the current stream. + /// The number of bytes to be written to the current stream. + public override void Write(byte[] buffer, int offset, int count) { + // ZipAESStream is used for reading but not for writing. Writing uses the ZipAESTransform directly. + throw new NotImplementedException(); + } + } } #endif \ No newline at end of file diff --git a/External/Tools/AppMan/ZipLib/Encryption/ZipAESTransform.cs b/External/Tools/AppMan/ZipLib/Encryption/ZipAESTransform.cs index 134c1ebdf8..21bcc89ea4 100644 --- a/External/Tools/AppMan/ZipLib/Encryption/ZipAESTransform.cs +++ b/External/Tools/AppMan/ZipLib/Encryption/ZipAESTransform.cs @@ -43,177 +43,177 @@ namespace ICSharpCode.SharpZipLib.Encryption { - /// - /// Transforms stream using AES in CTR mode - /// - internal class ZipAESTransform : ICryptoTransform { - - private const int PWD_VER_LENGTH = 2; - - // WinZip use iteration count of 1000 for PBKDF2 key generation - private const int KEY_ROUNDS = 1000; - - // For 128-bit AES (16 bytes) the encryption is implemented as expected. - // For 256-bit AES (32 bytes) WinZip do full 256 bit AES of the nonce to create the encryption - // block but use only the first 16 bytes of it, and discard the second half. - private const int ENCRYPT_BLOCK = 16; - - private int _blockSize; - private ICryptoTransform _encryptor; - private readonly byte[] _counterNonce; - private byte[] _encryptBuffer; - private int _encrPos; - private byte[] _pwdVerifier; - private HMACSHA1 _hmacsha1; - private bool _finalised; - - private bool _writeMode; - - /// - /// Constructor. - /// - /// Password string - /// Random bytes, length depends on encryption strength. - /// 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes. - /// The encryption strength, in bytes eg 16 for 128 bits. - /// True when creating a zip, false when reading. For the AuthCode. - /// - public ZipAESTransform(string key, byte[] saltBytes, int blockSize, bool writeMode) { - - if (blockSize != 16 && blockSize != 32) // 24 valid for AES but not supported by Winzip - throw new Exception("Invalid blocksize " + blockSize + ". Must be 16 or 32."); - if (saltBytes.Length != blockSize / 2) - throw new Exception("Invalid salt len. Must be " + blockSize / 2 + " for blocksize " + blockSize); - // initialise the encryption buffer and buffer pos - _blockSize = blockSize; - _encryptBuffer = new byte[_blockSize]; - _encrPos = ENCRYPT_BLOCK; - - // Performs the equivalent of derive_key in Dr Brian Gladman's pwd2key.c - Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, saltBytes, KEY_ROUNDS); - RijndaelManaged rm = new RijndaelManaged(); - rm.Mode = CipherMode.ECB; // No feedback from cipher for CTR mode - _counterNonce = new byte[_blockSize]; - byte[] byteKey1 = pdb.GetBytes(_blockSize); - byte[] byteKey2 = pdb.GetBytes(_blockSize); - _encryptor = rm.CreateEncryptor(byteKey1, byteKey2); - _pwdVerifier = pdb.GetBytes(PWD_VER_LENGTH); - // - _hmacsha1 = new HMACSHA1(byteKey2); - _writeMode = writeMode; - } - - /// - /// Implement the ICryptoTransform method. - /// - public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { - - // Pass the data stream to the hash algorithm for generating the Auth Code. - // This does not change the inputBuffer. Do this before decryption for read mode. - if (!_writeMode) { - _hmacsha1.TransformBlock(inputBuffer, inputOffset, inputCount, inputBuffer, inputOffset); - } - // Encrypt with AES in CTR mode. Regards to Dr Brian Gladman for this. - int ix = 0; - while (ix < inputCount) { - if (_encrPos == ENCRYPT_BLOCK) { - /* increment encryption nonce */ - int j = 0; - while (++_counterNonce[j] == 0) { - ++j; - } - /* encrypt the nonce to form next xor buffer */ - _encryptor.TransformBlock(_counterNonce, 0, _blockSize, _encryptBuffer, 0); - _encrPos = 0; - } - outputBuffer[ix + outputOffset] = (byte)(inputBuffer[ix + inputOffset] ^ _encryptBuffer[_encrPos++]); - // - ix++; - } - if (_writeMode) { - // This does not change the buffer. - _hmacsha1.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset); - } - return inputCount; - } - - /// - /// Returns the 2 byte password verifier - /// - public byte[] PwdVerifier { - get { - return _pwdVerifier; - } - } - - /// - /// Returns the 10 byte AUTH CODE to be checked or appended immediately following the AES data stream. - /// - public byte[] GetAuthCode() { - // We usually don't get advance notice of final block. Hash requres a TransformFinal. - if (!_finalised) { - byte[] dummy = new byte[0]; - _hmacsha1.TransformFinalBlock(dummy, 0, 0); - _finalised = true; - } - return _hmacsha1.Hash; - } - - #region ICryptoTransform Members - - /// - /// Not implemented. - /// - public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { - - throw new NotImplementedException("ZipAESTransform.TransformFinalBlock"); - } - - /// - /// Gets the size of the input data blocks in bytes. - /// - public int InputBlockSize { - get { - return _blockSize; - } - } - - /// - /// Gets the size of the output data blocks in bytes. - /// - public int OutputBlockSize { - get { - return _blockSize; - } - } - - /// - /// Gets a value indicating whether multiple blocks can be transformed. - /// - public bool CanTransformMultipleBlocks { - get { - return true; - } - } - - /// - /// Gets a value indicating whether the current transform can be reused. - /// - public bool CanReuseTransform { - get { - return true; - } - } - - /// - /// Cleanup internal state. - /// - public void Dispose() { - _encryptor.Dispose(); - } - - #endregion - - } + /// + /// Transforms stream using AES in CTR mode + /// + internal class ZipAESTransform : ICryptoTransform { + + private const int PWD_VER_LENGTH = 2; + + // WinZip use iteration count of 1000 for PBKDF2 key generation + private const int KEY_ROUNDS = 1000; + + // For 128-bit AES (16 bytes) the encryption is implemented as expected. + // For 256-bit AES (32 bytes) WinZip do full 256 bit AES of the nonce to create the encryption + // block but use only the first 16 bytes of it, and discard the second half. + private const int ENCRYPT_BLOCK = 16; + + private int _blockSize; + private ICryptoTransform _encryptor; + private readonly byte[] _counterNonce; + private byte[] _encryptBuffer; + private int _encrPos; + private byte[] _pwdVerifier; + private HMACSHA1 _hmacsha1; + private bool _finalised; + + private bool _writeMode; + + /// + /// Constructor. + /// + /// Password string + /// Random bytes, length depends on encryption strength. + /// 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes. + /// The encryption strength, in bytes eg 16 for 128 bits. + /// True when creating a zip, false when reading. For the AuthCode. + /// + public ZipAESTransform(string key, byte[] saltBytes, int blockSize, bool writeMode) { + + if (blockSize != 16 && blockSize != 32) // 24 valid for AES but not supported by Winzip + throw new Exception("Invalid blocksize " + blockSize + ". Must be 16 or 32."); + if (saltBytes.Length != blockSize / 2) + throw new Exception("Invalid salt len. Must be " + blockSize / 2 + " for blocksize " + blockSize); + // initialise the encryption buffer and buffer pos + _blockSize = blockSize; + _encryptBuffer = new byte[_blockSize]; + _encrPos = ENCRYPT_BLOCK; + + // Performs the equivalent of derive_key in Dr Brian Gladman's pwd2key.c + Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(key, saltBytes, KEY_ROUNDS); + RijndaelManaged rm = new RijndaelManaged(); + rm.Mode = CipherMode.ECB; // No feedback from cipher for CTR mode + _counterNonce = new byte[_blockSize]; + byte[] byteKey1 = pdb.GetBytes(_blockSize); + byte[] byteKey2 = pdb.GetBytes(_blockSize); + _encryptor = rm.CreateEncryptor(byteKey1, byteKey2); + _pwdVerifier = pdb.GetBytes(PWD_VER_LENGTH); + // + _hmacsha1 = new HMACSHA1(byteKey2); + _writeMode = writeMode; + } + + /// + /// Implement the ICryptoTransform method. + /// + public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset) { + + // Pass the data stream to the hash algorithm for generating the Auth Code. + // This does not change the inputBuffer. Do this before decryption for read mode. + if (!_writeMode) { + _hmacsha1.TransformBlock(inputBuffer, inputOffset, inputCount, inputBuffer, inputOffset); + } + // Encrypt with AES in CTR mode. Regards to Dr Brian Gladman for this. + int ix = 0; + while (ix < inputCount) { + if (_encrPos == ENCRYPT_BLOCK) { + /* increment encryption nonce */ + int j = 0; + while (++_counterNonce[j] == 0) { + ++j; + } + /* encrypt the nonce to form next xor buffer */ + _encryptor.TransformBlock(_counterNonce, 0, _blockSize, _encryptBuffer, 0); + _encrPos = 0; + } + outputBuffer[ix + outputOffset] = (byte)(inputBuffer[ix + inputOffset] ^ _encryptBuffer[_encrPos++]); + // + ix++; + } + if (_writeMode) { + // This does not change the buffer. + _hmacsha1.TransformBlock(outputBuffer, outputOffset, inputCount, outputBuffer, outputOffset); + } + return inputCount; + } + + /// + /// Returns the 2 byte password verifier + /// + public byte[] PwdVerifier { + get { + return _pwdVerifier; + } + } + + /// + /// Returns the 10 byte AUTH CODE to be checked or appended immediately following the AES data stream. + /// + public byte[] GetAuthCode() { + // We usually don't get advance notice of final block. Hash requres a TransformFinal. + if (!_finalised) { + byte[] dummy = new byte[0]; + _hmacsha1.TransformFinalBlock(dummy, 0, 0); + _finalised = true; + } + return _hmacsha1.Hash; + } + + #region ICryptoTransform Members + + /// + /// Not implemented. + /// + public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { + + throw new NotImplementedException("ZipAESTransform.TransformFinalBlock"); + } + + /// + /// Gets the size of the input data blocks in bytes. + /// + public int InputBlockSize { + get { + return _blockSize; + } + } + + /// + /// Gets the size of the output data blocks in bytes. + /// + public int OutputBlockSize { + get { + return _blockSize; + } + } + + /// + /// Gets a value indicating whether multiple blocks can be transformed. + /// + public bool CanTransformMultipleBlocks { + get { + return true; + } + } + + /// + /// Gets a value indicating whether the current transform can be reused. + /// + public bool CanReuseTransform { + get { + return true; + } + } + + /// + /// Cleanup internal state. + /// + public void Dispose() { + _encryptor.Dispose(); + } + + #endregion + + } } #endif \ No newline at end of file diff --git a/External/Tools/AppMan/ZipLib/GZip/GZIPConstants.cs b/External/Tools/AppMan/ZipLib/GZip/GZIPConstants.cs index 1c0e389ab1..c44a70a6d0 100644 --- a/External/Tools/AppMan/ZipLib/GZip/GZIPConstants.cs +++ b/External/Tools/AppMan/ZipLib/GZip/GZIPConstants.cs @@ -38,60 +38,60 @@ namespace ICSharpCode.SharpZipLib.GZip { - - /// - /// This class contains constants used for gzip. - /// - sealed public class GZipConstants - { - /// - /// Magic number found at start of GZIP header - /// - public const int GZIP_MAGIC = 0x1F8B; - - /* The flag byte is divided into individual bits as follows: - - bit 0 FTEXT - bit 1 FHCRC - bit 2 FEXTRA - bit 3 FNAME - bit 4 FCOMMENT - bit 5 reserved - bit 6 reserved - bit 7 reserved - */ - - /// - /// Flag bit mask for text - /// - public const int FTEXT = 0x1; - - /// - /// Flag bitmask for Crc - /// - public const int FHCRC = 0x2; - - /// - /// Flag bit mask for extra - /// - public const int FEXTRA = 0x4; - - /// - /// flag bitmask for name - /// - public const int FNAME = 0x8; - - /// - /// flag bit mask indicating comment is present - /// - public const int FCOMMENT = 0x10; - - /// - /// Initialise default instance. - /// - /// Constructor is private to prevent instances being created. - GZipConstants() - { - } - } + + /// + /// This class contains constants used for gzip. + /// + sealed public class GZipConstants + { + /// + /// Magic number found at start of GZIP header + /// + public const int GZIP_MAGIC = 0x1F8B; + + /* The flag byte is divided into individual bits as follows: + + bit 0 FTEXT + bit 1 FHCRC + bit 2 FEXTRA + bit 3 FNAME + bit 4 FCOMMENT + bit 5 reserved + bit 6 reserved + bit 7 reserved + */ + + /// + /// Flag bit mask for text + /// + public const int FTEXT = 0x1; + + /// + /// Flag bitmask for Crc + /// + public const int FHCRC = 0x2; + + /// + /// Flag bit mask for extra + /// + public const int FEXTRA = 0x4; + + /// + /// flag bitmask for name + /// + public const int FNAME = 0x8; + + /// + /// flag bit mask indicating comment is present + /// + public const int FCOMMENT = 0x10; + + /// + /// Initialise default instance. + /// + /// Constructor is private to prevent instances being created. + GZipConstants() + { + } + } } diff --git a/External/Tools/AppMan/ZipLib/GZip/GZipException.cs b/External/Tools/AppMan/ZipLib/GZip/GZipException.cs index 7f42931e82..f7bf1b9421 100644 --- a/External/Tools/AppMan/ZipLib/GZip/GZipException.cs +++ b/External/Tools/AppMan/ZipLib/GZip/GZipException.cs @@ -41,51 +41,51 @@ namespace ICSharpCode.SharpZipLib.GZip { - /// - /// GZipException represents a Gzip specific exception - /// + /// + /// GZipException represents a Gzip specific exception + /// #if !NETCF_1_0 && !NETCF_2_0 - [Serializable] -#endif - public class GZipException : SharpZipBaseException - { + [Serializable] +#endif + public class GZipException : SharpZipBaseException + { #if !NETCF_1_0 && !NETCF_2_0 - /// - /// Deserialization constructor - /// - /// for this constructor - /// for this constructor - protected GZipException(SerializationInfo info, StreamingContext context) - : base(info, context) + /// + /// Deserialization constructor + /// + /// for this constructor + /// for this constructor + protected GZipException(SerializationInfo info, StreamingContext context) + : base(info, context) - { - } + { + } #endif - /// - /// Initialise a new instance of GZipException - /// - public GZipException() - { - } - - /// - /// Initialise a new instance of GZipException with its message string. - /// - /// A that describes the error. - public GZipException(string message) - : base(message) - { - } - - /// - /// Initialise a new instance of . - /// - /// A that describes the error. - /// The that caused this exception. - public GZipException(string message, Exception innerException) - : base (message, innerException) - { - } - } + /// + /// Initialise a new instance of GZipException + /// + public GZipException() + { + } + + /// + /// Initialise a new instance of GZipException with its message string. + /// + /// A that describes the error. + public GZipException(string message) + : base(message) + { + } + + /// + /// Initialise a new instance of . + /// + /// A that describes the error. + /// The that caused this exception. + public GZipException(string message, Exception innerException) + : base (message, innerException) + { + } + } } diff --git a/External/Tools/AppMan/ZipLib/GZip/GzipInputStream.cs b/External/Tools/AppMan/ZipLib/GZip/GzipInputStream.cs index 4cbad945a4..bee5f9eeb8 100644 --- a/External/Tools/AppMan/ZipLib/GZip/GzipInputStream.cs +++ b/External/Tools/AppMan/ZipLib/GZip/GzipInputStream.cs @@ -37,7 +37,7 @@ // exception statement from your version. // HISTORY -// 11-08-2009 GeoffHart T9121 Added Multi-member gzip support +// 11-08-2009 GeoffHart T9121 Added Multi-member gzip support using System; using System.IO; @@ -48,337 +48,337 @@ namespace ICSharpCode.SharpZipLib.GZip { - - /// - /// This filter stream is used to decompress a "GZIP" format stream. - /// The "GZIP" format is described baseInputStream RFC 1952. - /// - /// author of the original java version : John Leuner - /// - /// This sample shows how to unzip a gzipped file - /// - /// using System; - /// using System.IO; - /// - /// using ICSharpCode.SharpZipLib.Core; - /// using ICSharpCode.SharpZipLib.GZip; - /// - /// class MainClass - /// { - /// public static void Main(string[] args) - /// { - /// using (Stream inStream = new GZipInputStream(File.OpenRead(args[0]))) - /// using (FileStream outStream = File.Create(Path.GetFileNameWithoutExtension(args[0]))) { - /// byte[] buffer = new byte[4096]; - /// StreamUtils.Copy(inStream, outStream, buffer); - /// } - /// } - /// } - /// - /// - public class GZipInputStream : InflaterInputStream - { - #region Instance Fields - /// - /// CRC-32 value for uncompressed data - /// + + /// + /// This filter stream is used to decompress a "GZIP" format stream. + /// The "GZIP" format is described baseInputStream RFC 1952. + /// + /// author of the original java version : John Leuner + /// + /// This sample shows how to unzip a gzipped file + /// + /// using System; + /// using System.IO; + /// + /// using ICSharpCode.SharpZipLib.Core; + /// using ICSharpCode.SharpZipLib.GZip; + /// + /// class MainClass + /// { + /// public static void Main(string[] args) + /// { + /// using (Stream inStream = new GZipInputStream(File.OpenRead(args[0]))) + /// using (FileStream outStream = File.Create(Path.GetFileNameWithoutExtension(args[0]))) { + /// byte[] buffer = new byte[4096]; + /// StreamUtils.Copy(inStream, outStream, buffer); + /// } + /// } + /// } + /// + /// + public class GZipInputStream : InflaterInputStream + { + #region Instance Fields + /// + /// CRC-32 value for uncompressed data + /// protected Crc32 crc; - + /// /// Flag to indicate if we've read the GZIP header yet for the current member (block of compressed data). /// This is tracked per-block as the file is parsed. /// - bool readGZIPHeader; - #endregion - - #region Constructors - /// - /// Creates a GZipInputStream with the default buffer size - /// - /// - /// The stream to read compressed data from (baseInputStream GZIP format) - /// - public GZipInputStream(Stream baseInputStream) - : this(baseInputStream, 4096) - { - } - - /// - /// Creates a GZIPInputStream with the specified buffer size - /// - /// - /// The stream to read compressed data from (baseInputStream GZIP format) - /// - /// - /// Size of the buffer to use - /// - public GZipInputStream(Stream baseInputStream, int size) - : base(baseInputStream, new Inflater(true), size) - { - } - #endregion - - #region Stream overrides - /// - /// Reads uncompressed data into an array of bytes - /// - /// - /// The buffer to read uncompressed data into - /// - /// - /// The offset indicating where the data should be placed - /// - /// - /// The number of uncompressed bytes to be read - /// - /// Returns the number of bytes actually read. - public override int Read(byte[] buffer, int offset, int count) - { - // A GZIP file can contain multiple blocks of compressed data, although this is quite rare. - // A compressed block could potentially be empty, so we need to loop until we reach EOF or - // we find data. - while (true) { - - // If we haven't read the header for this block, read it - if (! readGZIPHeader) { - - // Try to read header. If there is no header (0 bytes available), this is EOF. If there is - // an incomplete header, this will throw an exception. - if (! ReadHeader()) { - return 0; - } - } - - // Try to read compressed data - int bytesRead = base.Read(buffer, offset, count); - if (bytesRead > 0) { - crc.Update(buffer, offset, bytesRead); - } - - // If this is the end of stream, read the footer - if (inf.IsFinished) { - ReadFooter(); - } - - if (bytesRead > 0) { - return bytesRead; - } - } - } - #endregion - - #region Support routines - bool ReadHeader() - { - // Initialize CRC for this block - crc = new Crc32(); - - // Make sure there is data in file. We can't rely on ReadLeByte() to fill the buffer, as this could be EOF, - // which is fine, but ReadLeByte() throws an exception if it doesn't find data, so we do this part ourselves. - if (inputBuffer.Available <= 0) { - inputBuffer.Fill(); - if (inputBuffer.Available <= 0) { - // No header, EOF. - return false; - } - } - - // 1. Check the two magic bytes - Crc32 headCRC = new Crc32(); - int magic = inputBuffer.ReadLeByte(); - - if (magic < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - - headCRC.Update(magic); - if (magic != (GZipConstants.GZIP_MAGIC >> 8)) { - throw new GZipException("Error GZIP header, first magic byte doesn't match"); - } - - //magic = baseInputStream.ReadByte(); - magic = inputBuffer.ReadLeByte(); - - if (magic < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - - if (magic != (GZipConstants.GZIP_MAGIC & 0xFF)) { - throw new GZipException("Error GZIP header, second magic byte doesn't match"); - } - - headCRC.Update(magic); - - // 2. Check the compression type (must be 8) - int compressionType = inputBuffer.ReadLeByte(); - - if ( compressionType < 0 ) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - - if ( compressionType != 8 ) { - throw new GZipException("Error GZIP header, data not in deflate format"); - } - headCRC.Update(compressionType); - - // 3. Check the flags - int flags = inputBuffer.ReadLeByte(); - if (flags < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(flags); - - /* This flag byte is divided into individual bits as follows: - - bit 0 FTEXT - bit 1 FHCRC - bit 2 FEXTRA - bit 3 FNAME - bit 4 FCOMMENT - bit 5 reserved - bit 6 reserved - bit 7 reserved - */ - - // 3.1 Check the reserved bits are zero - - if ((flags & 0xE0) != 0) { - throw new GZipException("Reserved flag bits in GZIP header != 0"); - } - - // 4.-6. Skip the modification time, extra flags, and OS type - for (int i=0; i< 6; i++) { - int readByte = inputBuffer.ReadLeByte(); - if (readByte < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(readByte); - } - - // 7. Read extra field - if ((flags & GZipConstants.FEXTRA) != 0) { - // Skip subfield id - for (int i=0; i< 2; i++) { - int readByte = inputBuffer.ReadLeByte(); - if (readByte < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(readByte); - } - - if (inputBuffer.ReadLeByte() < 0 || inputBuffer.ReadLeByte() < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - - int len1, len2; - len1 = inputBuffer.ReadLeByte(); - len2 = inputBuffer.ReadLeByte(); - if ((len1 < 0) || (len2 < 0)) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(len1); - headCRC.Update(len2); - - int extraLen = (len1 << 8) | len2; - for (int i = 0; i < extraLen;i++) { - int readByte = inputBuffer.ReadLeByte(); - if (readByte < 0) - { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(readByte); - } - } - - // 8. Read file name - if ((flags & GZipConstants.FNAME) != 0) { - int readByte; - while ( (readByte = inputBuffer.ReadLeByte()) > 0) { - headCRC.Update(readByte); - } - - if (readByte < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - headCRC.Update(readByte); - } - - // 9. Read comment - if ((flags & GZipConstants.FCOMMENT) != 0) { - int readByte; - while ( (readByte = inputBuffer.ReadLeByte()) > 0) { - headCRC.Update(readByte); - } - - if (readByte < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - - headCRC.Update(readByte); - } - - // 10. Read header CRC - if ((flags & GZipConstants.FHCRC) != 0) { - int tempByte; - int crcval = inputBuffer.ReadLeByte(); - if (crcval < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - - tempByte = inputBuffer.ReadLeByte(); - if (tempByte < 0) { - throw new EndOfStreamException("EOS reading GZIP header"); - } - - crcval = (crcval << 8) | tempByte; - if (crcval != ((int) headCRC.Value & 0xffff)) { - throw new GZipException("Header CRC value mismatch"); - } - } - - readGZIPHeader = true; - return true; - } - - void ReadFooter() - { - byte[] footer = new byte[8]; - - // End of stream; reclaim all bytes from inf, read the final byte count, and reset the inflator - long bytesRead = inf.TotalOut & 0xffffffff; - inputBuffer.Available += inf.RemainingInput; - inf.Reset(); - - // Read footer from inputBuffer - int needed = 8; - while (needed > 0) { - int count = inputBuffer.ReadClearTextBuffer(footer, 8 - needed, needed); - if (count <= 0) { - throw new EndOfStreamException("EOS reading GZIP footer"); - } - needed -= count; // Jewel Jan 16 - } - - // Calculate CRC - int crcval = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8) | ((footer[2] & 0xff) << 16) | (footer[3] << 24); - if (crcval != (int) crc.Value) { - throw new GZipException("GZIP crc sum mismatch, theirs \"" + crcval + "\" and ours \"" + (int) crc.Value); - } - - // NOTE The total here is the original total modulo 2 ^ 32. - uint total = - (uint)((uint)footer[4] & 0xff) | - (uint)(((uint)footer[5] & 0xff) << 8) | - (uint)(((uint)footer[6] & 0xff) << 16) | - (uint)((uint)footer[7] << 24); - - if (bytesRead != total) { - throw new GZipException("Number of bytes mismatch in footer"); - } - - // Mark header read as false so if another header exists, we'll continue reading through the file - readGZIPHeader = false; - } - #endregion - } + bool readGZIPHeader; + #endregion + + #region Constructors + /// + /// Creates a GZipInputStream with the default buffer size + /// + /// + /// The stream to read compressed data from (baseInputStream GZIP format) + /// + public GZipInputStream(Stream baseInputStream) + : this(baseInputStream, 4096) + { + } + + /// + /// Creates a GZIPInputStream with the specified buffer size + /// + /// + /// The stream to read compressed data from (baseInputStream GZIP format) + /// + /// + /// Size of the buffer to use + /// + public GZipInputStream(Stream baseInputStream, int size) + : base(baseInputStream, new Inflater(true), size) + { + } + #endregion + + #region Stream overrides + /// + /// Reads uncompressed data into an array of bytes + /// + /// + /// The buffer to read uncompressed data into + /// + /// + /// The offset indicating where the data should be placed + /// + /// + /// The number of uncompressed bytes to be read + /// + /// Returns the number of bytes actually read. + public override int Read(byte[] buffer, int offset, int count) + { + // A GZIP file can contain multiple blocks of compressed data, although this is quite rare. + // A compressed block could potentially be empty, so we need to loop until we reach EOF or + // we find data. + while (true) { + + // If we haven't read the header for this block, read it + if (! readGZIPHeader) { + + // Try to read header. If there is no header (0 bytes available), this is EOF. If there is + // an incomplete header, this will throw an exception. + if (! ReadHeader()) { + return 0; + } + } + + // Try to read compressed data + int bytesRead = base.Read(buffer, offset, count); + if (bytesRead > 0) { + crc.Update(buffer, offset, bytesRead); + } + + // If this is the end of stream, read the footer + if (inf.IsFinished) { + ReadFooter(); + } + + if (bytesRead > 0) { + return bytesRead; + } + } + } + #endregion + + #region Support routines + bool ReadHeader() + { + // Initialize CRC for this block + crc = new Crc32(); + + // Make sure there is data in file. We can't rely on ReadLeByte() to fill the buffer, as this could be EOF, + // which is fine, but ReadLeByte() throws an exception if it doesn't find data, so we do this part ourselves. + if (inputBuffer.Available <= 0) { + inputBuffer.Fill(); + if (inputBuffer.Available <= 0) { + // No header, EOF. + return false; + } + } + + // 1. Check the two magic bytes + Crc32 headCRC = new Crc32(); + int magic = inputBuffer.ReadLeByte(); + + if (magic < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + + headCRC.Update(magic); + if (magic != (GZipConstants.GZIP_MAGIC >> 8)) { + throw new GZipException("Error GZIP header, first magic byte doesn't match"); + } + + //magic = baseInputStream.ReadByte(); + magic = inputBuffer.ReadLeByte(); + + if (magic < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + + if (magic != (GZipConstants.GZIP_MAGIC & 0xFF)) { + throw new GZipException("Error GZIP header, second magic byte doesn't match"); + } + + headCRC.Update(magic); + + // 2. Check the compression type (must be 8) + int compressionType = inputBuffer.ReadLeByte(); + + if ( compressionType < 0 ) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + + if ( compressionType != 8 ) { + throw new GZipException("Error GZIP header, data not in deflate format"); + } + headCRC.Update(compressionType); + + // 3. Check the flags + int flags = inputBuffer.ReadLeByte(); + if (flags < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + headCRC.Update(flags); + + /* This flag byte is divided into individual bits as follows: + + bit 0 FTEXT + bit 1 FHCRC + bit 2 FEXTRA + bit 3 FNAME + bit 4 FCOMMENT + bit 5 reserved + bit 6 reserved + bit 7 reserved + */ + + // 3.1 Check the reserved bits are zero + + if ((flags & 0xE0) != 0) { + throw new GZipException("Reserved flag bits in GZIP header != 0"); + } + + // 4.-6. Skip the modification time, extra flags, and OS type + for (int i=0; i< 6; i++) { + int readByte = inputBuffer.ReadLeByte(); + if (readByte < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + headCRC.Update(readByte); + } + + // 7. Read extra field + if ((flags & GZipConstants.FEXTRA) != 0) { + // Skip subfield id + for (int i=0; i< 2; i++) { + int readByte = inputBuffer.ReadLeByte(); + if (readByte < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + headCRC.Update(readByte); + } + + if (inputBuffer.ReadLeByte() < 0 || inputBuffer.ReadLeByte() < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + + int len1, len2; + len1 = inputBuffer.ReadLeByte(); + len2 = inputBuffer.ReadLeByte(); + if ((len1 < 0) || (len2 < 0)) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + headCRC.Update(len1); + headCRC.Update(len2); + + int extraLen = (len1 << 8) | len2; + for (int i = 0; i < extraLen;i++) { + int readByte = inputBuffer.ReadLeByte(); + if (readByte < 0) + { + throw new EndOfStreamException("EOS reading GZIP header"); + } + headCRC.Update(readByte); + } + } + + // 8. Read file name + if ((flags & GZipConstants.FNAME) != 0) { + int readByte; + while ( (readByte = inputBuffer.ReadLeByte()) > 0) { + headCRC.Update(readByte); + } + + if (readByte < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + headCRC.Update(readByte); + } + + // 9. Read comment + if ((flags & GZipConstants.FCOMMENT) != 0) { + int readByte; + while ( (readByte = inputBuffer.ReadLeByte()) > 0) { + headCRC.Update(readByte); + } + + if (readByte < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + + headCRC.Update(readByte); + } + + // 10. Read header CRC + if ((flags & GZipConstants.FHCRC) != 0) { + int tempByte; + int crcval = inputBuffer.ReadLeByte(); + if (crcval < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + + tempByte = inputBuffer.ReadLeByte(); + if (tempByte < 0) { + throw new EndOfStreamException("EOS reading GZIP header"); + } + + crcval = (crcval << 8) | tempByte; + if (crcval != ((int) headCRC.Value & 0xffff)) { + throw new GZipException("Header CRC value mismatch"); + } + } + + readGZIPHeader = true; + return true; + } + + void ReadFooter() + { + byte[] footer = new byte[8]; + + // End of stream; reclaim all bytes from inf, read the final byte count, and reset the inflator + long bytesRead = inf.TotalOut & 0xffffffff; + inputBuffer.Available += inf.RemainingInput; + inf.Reset(); + + // Read footer from inputBuffer + int needed = 8; + while (needed > 0) { + int count = inputBuffer.ReadClearTextBuffer(footer, 8 - needed, needed); + if (count <= 0) { + throw new EndOfStreamException("EOS reading GZIP footer"); + } + needed -= count; // Jewel Jan 16 + } + + // Calculate CRC + int crcval = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8) | ((footer[2] & 0xff) << 16) | (footer[3] << 24); + if (crcval != (int) crc.Value) { + throw new GZipException("GZIP crc sum mismatch, theirs \"" + crcval + "\" and ours \"" + (int) crc.Value); + } + + // NOTE The total here is the original total modulo 2 ^ 32. + uint total = + (uint)((uint)footer[4] & 0xff) | + (uint)(((uint)footer[5] & 0xff) << 8) | + (uint)(((uint)footer[6] & 0xff) << 16) | + (uint)((uint)footer[7] << 24); + + if (bytesRead != total) { + throw new GZipException("Number of bytes mismatch in footer"); + } + + // Mark header read as false so if another header exists, we'll continue reading through the file + readGZIPHeader = false; + } + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/GZip/GzipOutputStream.cs b/External/Tools/AppMan/ZipLib/GZip/GzipOutputStream.cs index 0db2e4b384..3376d618f1 100644 --- a/External/Tools/AppMan/ZipLib/GZip/GzipOutputStream.cs +++ b/External/Tools/AppMan/ZipLib/GZip/GzipOutputStream.cs @@ -45,37 +45,37 @@ namespace ICSharpCode.SharpZipLib.GZip { - - /// - /// This filter stream is used to compress a stream into a "GZIP" stream. - /// The "GZIP" format is described in RFC 1952. - /// - /// author of the original java version : John Leuner - /// - /// This sample shows how to gzip a file - /// - /// using System; - /// using System.IO; - /// - /// using ICSharpCode.SharpZipLib.GZip; - /// using ICSharpCode.SharpZipLib.Core; - /// - /// class MainClass - /// { - /// public static void Main(string[] args) - /// { - /// using (Stream s = new GZipOutputStream(File.Create(args[0] + ".gz"))) - /// using (FileStream fs = File.OpenRead(args[0])) { - /// byte[] writeData = new byte[4096]; - /// Streamutils.Copy(s, fs, writeData); - /// } - /// } - /// } - /// } - /// - /// - public class GZipOutputStream : DeflaterOutputStream - { + + /// + /// This filter stream is used to compress a stream into a "GZIP" stream. + /// The "GZIP" format is described in RFC 1952. + /// + /// author of the original java version : John Leuner + /// + /// This sample shows how to gzip a file + /// + /// using System; + /// using System.IO; + /// + /// using ICSharpCode.SharpZipLib.GZip; + /// using ICSharpCode.SharpZipLib.Core; + /// + /// class MainClass + /// { + /// public static void Main(string[] args) + /// { + /// using (Stream s = new GZipOutputStream(File.Create(args[0] + ".gz"))) + /// using (FileStream fs = File.OpenRead(args[0])) { + /// byte[] writeData = new byte[4096]; + /// Streamutils.Copy(s, fs, writeData); + /// } + /// } + /// } + /// } + /// + /// + public class GZipOutputStream : DeflaterOutputStream + { enum OutputState { Header, @@ -84,120 +84,120 @@ enum OutputState Closed, }; - #region Instance Fields - /// - /// CRC-32 value for uncompressed data - /// - protected Crc32 crc = new Crc32(); + #region Instance Fields + /// + /// CRC-32 value for uncompressed data + /// + protected Crc32 crc = new Crc32(); OutputState state_ = OutputState.Header; - #endregion + #endregion - #region Constructors - /// - /// Creates a GzipOutputStream with the default buffer size - /// - /// - /// The stream to read data (to be compressed) from - /// - public GZipOutputStream(Stream baseOutputStream) - : this(baseOutputStream, 4096) - { - } - - /// - /// Creates a GZipOutputStream with the specified buffer size - /// - /// - /// The stream to read data (to be compressed) from - /// - /// - /// Size of the buffer to use - /// - public GZipOutputStream(Stream baseOutputStream, int size) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), size) - { - } - #endregion - - #region Public API - /// - /// Sets the active compression level (1-9). The new level will be activated - /// immediately. - /// - /// The compression level to set. - /// - /// Level specified is not supported. - /// - /// - public void SetLevel(int level) - { - if (level < Deflater.BEST_SPEED) { - throw new ArgumentOutOfRangeException("level"); - } - deflater_.SetLevel(level); - } - - /// - /// Get the current compression level. - /// - /// The current compression level. - public int GetLevel() - { - return deflater_.GetLevel(); - } - #endregion - - #region Stream overrides - /// - /// Write given buffer to output updating crc - /// - /// Buffer to write - /// Offset of first byte in buf to write - /// Number of bytes to write - public override void Write(byte[] buffer, int offset, int count) - { - if ( state_ == OutputState.Header ) { - WriteHeader(); - } + #region Constructors + /// + /// Creates a GzipOutputStream with the default buffer size + /// + /// + /// The stream to read data (to be compressed) from + /// + public GZipOutputStream(Stream baseOutputStream) + : this(baseOutputStream, 4096) + { + } + + /// + /// Creates a GZipOutputStream with the specified buffer size + /// + /// + /// The stream to read data (to be compressed) from + /// + /// + /// Size of the buffer to use + /// + public GZipOutputStream(Stream baseOutputStream, int size) : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true), size) + { + } + #endregion + + #region Public API + /// + /// Sets the active compression level (1-9). The new level will be activated + /// immediately. + /// + /// The compression level to set. + /// + /// Level specified is not supported. + /// + /// + public void SetLevel(int level) + { + if (level < Deflater.BEST_SPEED) { + throw new ArgumentOutOfRangeException("level"); + } + deflater_.SetLevel(level); + } + + /// + /// Get the current compression level. + /// + /// The current compression level. + public int GetLevel() + { + return deflater_.GetLevel(); + } + #endregion + + #region Stream overrides + /// + /// Write given buffer to output updating crc + /// + /// Buffer to write + /// Offset of first byte in buf to write + /// Number of bytes to write + public override void Write(byte[] buffer, int offset, int count) + { + if ( state_ == OutputState.Header ) { + WriteHeader(); + } if( state_!=OutputState.Footer ) { throw new InvalidOperationException("Write not permitted in current state"); } - crc.Update(buffer, offset, count); - base.Write(buffer, offset, count); - } - - /// - /// Writes remaining compressed output data to the output stream - /// and closes it. - /// - public override void Close() - { - try { - Finish(); - } - finally { + crc.Update(buffer, offset, count); + base.Write(buffer, offset, count); + } + + /// + /// Writes remaining compressed output data to the output stream + /// and closes it. + /// + public override void Close() + { + try { + Finish(); + } + finally { if ( state_ != OutputState.Closed ) { state_ = OutputState.Closed; - if( IsStreamOwner ) { - baseOutputStream_.Close(); - } + if( IsStreamOwner ) { + baseOutputStream_.Close(); + } } - } - } - #endregion - - #region DeflaterOutputStream overrides - /// - /// Finish compression and write any footer information required to stream - /// - public override void Finish() - { - // If no data has been written a header should be added. - if ( state_ == OutputState.Header ) { - WriteHeader(); - } + } + } + #endregion + + #region DeflaterOutputStream overrides + /// + /// Finish compression and write any footer information required to stream + /// + public override void Finish() + { + // If no data has been written a header should be added. + if ( state_ == OutputState.Header ) { + WriteHeader(); + } if( state_ == OutputState.Footer) { @@ -212,50 +212,50 @@ public override void Finish() unchecked { gzipFooter=new byte[] { - (byte) crcval, (byte) (crcval >> 8), - (byte) (crcval >> 16), (byte) (crcval >> 24), - - (byte) totalin, (byte) (totalin >> 8), - (byte) (totalin >> 16), (byte) (totalin >> 24) - }; + (byte) crcval, (byte) (crcval >> 8), + (byte) (crcval >> 16), (byte) (crcval >> 24), + + (byte) totalin, (byte) (totalin >> 8), + (byte) (totalin >> 16), (byte) (totalin >> 24) + }; } baseOutputStream_.Write(gzipFooter, 0, gzipFooter.Length); } - } - #endregion - - #region Support Routines - void WriteHeader() - { - if ( state_ == OutputState.Header ) - { + } + #endregion + + #region Support Routines + void WriteHeader() + { + if ( state_ == OutputState.Header ) + { state_=OutputState.Footer; - int mod_time = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals - byte[] gzipHeader = { - // The two magic bytes - (byte) (GZipConstants.GZIP_MAGIC >> 8), (byte) (GZipConstants.GZIP_MAGIC & 0xff), + int mod_time = (int)((DateTime.Now.Ticks - new DateTime(1970, 1, 1).Ticks) / 10000000L); // Ticks give back 100ns intervals + byte[] gzipHeader = { + // The two magic bytes + (byte) (GZipConstants.GZIP_MAGIC >> 8), (byte) (GZipConstants.GZIP_MAGIC & 0xff), - // The compression type - (byte) Deflater.DEFLATED, + // The compression type + (byte) Deflater.DEFLATED, - // The flags (not set) - 0, + // The flags (not set) + 0, - // The modification time - (byte) mod_time, (byte) (mod_time >> 8), - (byte) (mod_time >> 16), (byte) (mod_time >> 24), + // The modification time + (byte) mod_time, (byte) (mod_time >> 8), + (byte) (mod_time >> 16), (byte) (mod_time >> 24), - // The extra flags - 0, + // The extra flags + 0, - // The OS type (unknown) - (byte) 255 - }; - baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length); - } - } - #endregion - } + // The OS type (unknown) + (byte) 255 + }; + baseOutputStream_.Write(gzipHeader, 0, gzipHeader.Length); + } + } + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Lzw/LzwInputStream.cs b/External/Tools/AppMan/ZipLib/Lzw/LzwInputStream.cs index 94b8b66e25..a1aea68f68 100644 --- a/External/Tools/AppMan/ZipLib/Lzw/LzwInputStream.cs +++ b/External/Tools/AppMan/ZipLib/Lzw/LzwInputStream.cs @@ -63,18 +63,18 @@ namespace ICSharpCode.SharpZipLib.LZW /// /// class MainClass /// { - /// public static void Main(string[] args) - /// { - /// using (Stream inStream = new LzwInputStream(File.OpenRead(args[0]))) - /// using (FileStream outStream = File.Create(Path.GetFileNameWithoutExtension(args[0]))) { - /// byte[] buffer = new byte[4096]; - /// StreamUtils.Copy(inStream, outStream, buffer); + /// public static void Main(string[] args) + /// { + /// using (Stream inStream = new LzwInputStream(File.OpenRead(args[0]))) + /// using (FileStream outStream = File.Create(Path.GetFileNameWithoutExtension(args[0]))) { + /// byte[] buffer = new byte[4096]; + /// StreamUtils.Copy(inStream, outStream, buffer); /// // OR /// inStream.Read(buffer, 0, buffer.Length); /// // now do something with the buffer - /// } - /// } - /// } + /// } + /// } + /// } ///
    /// public class LzwInputStream : Stream @@ -133,8 +133,8 @@ public override int Read(byte[] buffer, int offset, int count) { int start = offset; /* Using local copies of various variables speeds things up by as - * much as 30% in Java! Performance not tested in C#. - */ + * much as 30% in Java! Performance not tested in C#. + */ int[] lTabPrefix = tabPrefix; byte[] lTabSuffix = tabSuffix; byte[] lStack = stack; diff --git a/External/Tools/AppMan/ZipLib/SharpZipBaseException.cs b/External/Tools/AppMan/ZipLib/SharpZipBaseException.cs index 7a5d136f17..43b989fabe 100644 --- a/External/Tools/AppMan/ZipLib/SharpZipBaseException.cs +++ b/External/Tools/AppMan/ZipLib/SharpZipBaseException.cs @@ -41,54 +41,54 @@ namespace ICSharpCode.SharpZipLib { - /// - /// SharpZipBaseException is the base exception class for the SharpZipLibrary. - /// All library exceptions are derived from this. - /// - /// NOTE: Not all exceptions thrown will be derived from this class. - /// A variety of other exceptions are possible for example + /// + /// SharpZipBaseException is the base exception class for the SharpZipLibrary. + /// All library exceptions are derived from this. + /// + /// NOTE: Not all exceptions thrown will be derived from this class. + /// A variety of other exceptions are possible for example #if !NETCF_1_0 && !NETCF_2_0 - [Serializable] + [Serializable] #endif - public class SharpZipBaseException : ApplicationException - { + public class SharpZipBaseException : ApplicationException + { #if !NETCF_1_0 && !NETCF_2_0 - /// - /// Deserialization constructor - /// - /// for this constructor - /// for this constructor - protected SharpZipBaseException(SerializationInfo info, StreamingContext context ) - : base( info, context ) - { - } + /// + /// Deserialization constructor + /// + /// for this constructor + /// for this constructor + protected SharpZipBaseException(SerializationInfo info, StreamingContext context ) + : base( info, context ) + { + } #endif - - /// - /// Initializes a new instance of the SharpZipBaseException class. - /// - public SharpZipBaseException() - { - } - - /// - /// Initializes a new instance of the SharpZipBaseException class with a specified error message. - /// - /// A message describing the exception. - public SharpZipBaseException(string message) - : base(message) - { - } + + /// + /// Initializes a new instance of the SharpZipBaseException class. + /// + public SharpZipBaseException() + { + } + + /// + /// Initializes a new instance of the SharpZipBaseException class with a specified error message. + /// + /// A message describing the exception. + public SharpZipBaseException(string message) + : base(message) + { + } - /// - /// Initializes a new instance of the SharpZipBaseException class with a specified - /// error message and a reference to the inner exception that is the cause of this exception. - /// - /// A message describing the exception. - /// The inner exception - public SharpZipBaseException(string message, Exception innerException) - : base(message, innerException) - { - } - } + /// + /// Initializes a new instance of the SharpZipBaseException class with a specified + /// error message and a reference to the inner exception that is the cause of this exception. + /// + /// A message describing the exception. + /// The inner exception + public SharpZipBaseException(string message, Exception innerException) + : base(message, innerException) + { + } + } } diff --git a/External/Tools/AppMan/ZipLib/Tar/InvalidHeaderException.cs b/External/Tools/AppMan/ZipLib/Tar/InvalidHeaderException.cs index bac9343afd..226e80c5bd 100644 --- a/External/Tools/AppMan/ZipLib/Tar/InvalidHeaderException.cs +++ b/External/Tools/AppMan/ZipLib/Tar/InvalidHeaderException.cs @@ -40,56 +40,56 @@ #endif namespace ICSharpCode.SharpZipLib.Tar { - - /// - /// This exception is used to indicate that there is a problem - /// with a TAR archive header. - /// + + /// + /// This exception is used to indicate that there is a problem + /// with a TAR archive header. + /// #if !NETCF_1_0 && !NETCF_2_0 - [Serializable] + [Serializable] #endif - public class InvalidHeaderException : TarException - { + public class InvalidHeaderException : TarException + { #if !NETCF_1_0 && !NETCF_2_0 - /// - /// Deserialization constructor - /// - /// for this constructor - /// for this constructor - protected InvalidHeaderException(SerializationInfo information, StreamingContext context) - : base(information, context) + /// + /// Deserialization constructor + /// + /// for this constructor + /// for this constructor + protected InvalidHeaderException(SerializationInfo information, StreamingContext context) + : base(information, context) - { - } + { + } #endif - /// - /// Initialise a new instance of the InvalidHeaderException class. - /// - public InvalidHeaderException() - { - } + /// + /// Initialise a new instance of the InvalidHeaderException class. + /// + public InvalidHeaderException() + { + } - /// - /// Initialises a new instance of the InvalidHeaderException class with a specified message. - /// - /// Message describing the exception cause. - public InvalidHeaderException(string message) - : base(message) - { - } + /// + /// Initialises a new instance of the InvalidHeaderException class with a specified message. + /// + /// Message describing the exception cause. + public InvalidHeaderException(string message) + : base(message) + { + } - /// - /// Initialise a new instance of InvalidHeaderException - /// - /// Message describing the problem. - /// The exception that is the cause of the current exception. - public InvalidHeaderException(string message, Exception exception) - : base(message, exception) - { - } - } + /// + /// Initialise a new instance of InvalidHeaderException + /// + /// Message describing the problem. + /// The exception that is the cause of the current exception. + public InvalidHeaderException(string message, Exception exception) + : base(message, exception) + { + } + } } /* The original Java file had this header: diff --git a/External/Tools/AppMan/ZipLib/Tar/TarArchive.cs b/External/Tools/AppMan/ZipLib/Tar/TarArchive.cs index 5a5510b063..b5236ec764 100644 --- a/External/Tools/AppMan/ZipLib/Tar/TarArchive.cs +++ b/External/Tools/AppMan/ZipLib/Tar/TarArchive.cs @@ -34,7 +34,7 @@ // exception statement from your version. // HISTORY -// 28-01-2010 DavidPierson Added IsStreamOwner +// 28-01-2010 DavidPierson Added IsStreamOwner using System; using System.IO; @@ -42,735 +42,735 @@ namespace ICSharpCode.SharpZipLib.Tar { - /// - /// Used to advise clients of 'events' while processing archives - /// - public delegate void ProgressMessageHandler(TarArchive archive, TarEntry entry, string message); + /// + /// Used to advise clients of 'events' while processing archives + /// + public delegate void ProgressMessageHandler(TarArchive archive, TarEntry entry, string message); - /// - /// The TarArchive class implements the concept of a - /// 'Tape Archive'. A tar archive is a series of entries, each of - /// which represents a file system object. Each entry in - /// the archive consists of a header block followed by 0 or more data blocks. - /// Directory entries consist only of the header block, and are followed by entries - /// for the directory's contents. File entries consist of a - /// header followed by the number of blocks needed to - /// contain the file's contents. All entries are written on - /// block boundaries. Blocks are 512 bytes long. - /// - /// TarArchives are instantiated in either read or write mode, - /// based upon whether they are instantiated with an InputStream - /// or an OutputStream. Once instantiated TarArchives read/write - /// mode can not be changed. - /// - /// There is currently no support for random access to tar archives. - /// However, it seems that subclassing TarArchive, and using the - /// TarBuffer.CurrentRecord and TarBuffer.CurrentBlock - /// properties, this would be rather trivial. - /// - public class TarArchive : IDisposable - { - /// - /// Client hook allowing detailed information to be reported during processing - /// - public event ProgressMessageHandler ProgressMessageEvent; - - /// - /// Raises the ProgressMessage event - /// - /// The TarEntry for this event - /// message for this event. Null is no message - protected virtual void OnProgressMessageEvent(TarEntry entry, string message) - { - ProgressMessageHandler handler = ProgressMessageEvent; - if (handler != null) { - handler(this, entry, message); - } - } - - #region Constructors - /// - /// Constructor for a default . - /// - protected TarArchive() - { - } - - /// - /// Initalise a TarArchive for input. - /// - /// The to use for input. - protected TarArchive(TarInputStream stream) - { - if ( stream == null ) { - throw new ArgumentNullException("stream"); - } - - tarIn = stream; - } - - /// - /// Initialise a TarArchive for output. - /// - /// The to use for output. - protected TarArchive(TarOutputStream stream) - { - if ( stream == null ) { - throw new ArgumentNullException("stream"); - } - - tarOut = stream; - } - #endregion - - #region Static factory methods - /// - /// The InputStream based constructors create a TarArchive for the - /// purposes of extracting or listing a tar archive. Thus, use - /// these constructors when you wish to extract files from or list - /// the contents of an existing tar archive. - /// - /// The stream to retrieve archive data from. - /// Returns a new suitable for reading from. - public static TarArchive CreateInputTarArchive(Stream inputStream) - { - if ( inputStream == null ) { - throw new ArgumentNullException("inputStream"); - } + /// + /// The TarArchive class implements the concept of a + /// 'Tape Archive'. A tar archive is a series of entries, each of + /// which represents a file system object. Each entry in + /// the archive consists of a header block followed by 0 or more data blocks. + /// Directory entries consist only of the header block, and are followed by entries + /// for the directory's contents. File entries consist of a + /// header followed by the number of blocks needed to + /// contain the file's contents. All entries are written on + /// block boundaries. Blocks are 512 bytes long. + /// + /// TarArchives are instantiated in either read or write mode, + /// based upon whether they are instantiated with an InputStream + /// or an OutputStream. Once instantiated TarArchives read/write + /// mode can not be changed. + /// + /// There is currently no support for random access to tar archives. + /// However, it seems that subclassing TarArchive, and using the + /// TarBuffer.CurrentRecord and TarBuffer.CurrentBlock + /// properties, this would be rather trivial. + /// + public class TarArchive : IDisposable + { + /// + /// Client hook allowing detailed information to be reported during processing + /// + public event ProgressMessageHandler ProgressMessageEvent; + + /// + /// Raises the ProgressMessage event + /// + /// The TarEntry for this event + /// message for this event. Null is no message + protected virtual void OnProgressMessageEvent(TarEntry entry, string message) + { + ProgressMessageHandler handler = ProgressMessageEvent; + if (handler != null) { + handler(this, entry, message); + } + } + + #region Constructors + /// + /// Constructor for a default . + /// + protected TarArchive() + { + } + + /// + /// Initalise a TarArchive for input. + /// + /// The to use for input. + protected TarArchive(TarInputStream stream) + { + if ( stream == null ) { + throw new ArgumentNullException("stream"); + } + + tarIn = stream; + } + + /// + /// Initialise a TarArchive for output. + /// + /// The to use for output. + protected TarArchive(TarOutputStream stream) + { + if ( stream == null ) { + throw new ArgumentNullException("stream"); + } + + tarOut = stream; + } + #endregion + + #region Static factory methods + /// + /// The InputStream based constructors create a TarArchive for the + /// purposes of extracting or listing a tar archive. Thus, use + /// these constructors when you wish to extract files from or list + /// the contents of an existing tar archive. + /// + /// The stream to retrieve archive data from. + /// Returns a new suitable for reading from. + public static TarArchive CreateInputTarArchive(Stream inputStream) + { + if ( inputStream == null ) { + throw new ArgumentNullException("inputStream"); + } - TarInputStream tarStream = inputStream as TarInputStream; + TarInputStream tarStream = inputStream as TarInputStream; - TarArchive result; - if ( tarStream != null ) { - result = new TarArchive(tarStream); - } - else { - result = CreateInputTarArchive(inputStream, TarBuffer.DefaultBlockFactor); - } - return result; - } - - /// - /// Create TarArchive for reading setting block factor - /// - /// A stream containing the tar archive contents - /// The blocking factor to apply - /// Returns a suitable for reading. - public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFactor) - { - if ( inputStream == null ) { - throw new ArgumentNullException("inputStream"); - } + TarArchive result; + if ( tarStream != null ) { + result = new TarArchive(tarStream); + } + else { + result = CreateInputTarArchive(inputStream, TarBuffer.DefaultBlockFactor); + } + return result; + } + + /// + /// Create TarArchive for reading setting block factor + /// + /// A stream containing the tar archive contents + /// The blocking factor to apply + /// Returns a suitable for reading. + public static TarArchive CreateInputTarArchive(Stream inputStream, int blockFactor) + { + if ( inputStream == null ) { + throw new ArgumentNullException("inputStream"); + } - if ( inputStream is TarInputStream ) { - throw new ArgumentException("TarInputStream not valid"); - } - - return new TarArchive(new TarInputStream(inputStream, blockFactor)); - } - - /// - /// Create a TarArchive for writing to, using the default blocking factor - /// - /// The to write to - /// Returns a suitable for writing. - public static TarArchive CreateOutputTarArchive(Stream outputStream) - { - if ( outputStream == null ) { - throw new ArgumentNullException("outputStream"); - } - + if ( inputStream is TarInputStream ) { + throw new ArgumentException("TarInputStream not valid"); + } + + return new TarArchive(new TarInputStream(inputStream, blockFactor)); + } + + /// + /// Create a TarArchive for writing to, using the default blocking factor + /// + /// The to write to + /// Returns a suitable for writing. + public static TarArchive CreateOutputTarArchive(Stream outputStream) + { + if ( outputStream == null ) { + throw new ArgumentNullException("outputStream"); + } + TarOutputStream tarStream = outputStream as TarOutputStream; - TarArchive result; - if ( tarStream != null ) { - result = new TarArchive(tarStream); - } - else { - result = CreateOutputTarArchive(outputStream, TarBuffer.DefaultBlockFactor); - } - return result; - } + TarArchive result; + if ( tarStream != null ) { + result = new TarArchive(tarStream); + } + else { + result = CreateOutputTarArchive(outputStream, TarBuffer.DefaultBlockFactor); + } + return result; + } - /// - /// Create a tar archive for writing. - /// - /// The stream to write to - /// The blocking factor to use for buffering. - /// Returns a suitable for writing. - public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFactor) - { - if ( outputStream == null ) { - throw new ArgumentNullException("outputStream"); - } + /// + /// Create a tar archive for writing. + /// + /// The stream to write to + /// The blocking factor to use for buffering. + /// Returns a suitable for writing. + public static TarArchive CreateOutputTarArchive(Stream outputStream, int blockFactor) + { + if ( outputStream == null ) { + throw new ArgumentNullException("outputStream"); + } - if ( outputStream is TarOutputStream ) { - throw new ArgumentException("TarOutputStream is not valid"); - } + if ( outputStream is TarOutputStream ) { + throw new ArgumentException("TarOutputStream is not valid"); + } - return new TarArchive(new TarOutputStream(outputStream, blockFactor)); - } - #endregion - - /// - /// Set the flag that determines whether existing files are - /// kept, or overwritten during extraction. - /// - /// - /// If true, do not overwrite existing files. - /// - public void SetKeepOldFiles(bool keepExistingFiles) - { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - keepOldFiles = keepExistingFiles; - } - - /// - /// Get/set the ascii file translation flag. If ascii file translation - /// is true, then the file is checked to see if it a binary file or not. - /// If the flag is true and the test indicates it is ascii text - /// file, it will be translated. The translation converts the local - /// operating system's concept of line ends into the UNIX line end, - /// '\n', which is the defacto standard for a TAR archive. This makes - /// text files compatible with UNIX. - /// - public bool AsciiTranslate - { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - return asciiTranslate; - } - - set { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - asciiTranslate = value; - } - - } - - /// - /// Set the ascii file translation flag. - /// - /// - /// If true, translate ascii text files. - /// - [Obsolete("Use the AsciiTranslate property")] - public void SetAsciiTranslation(bool translateAsciiFiles) - { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - asciiTranslate = translateAsciiFiles; - } + return new TarArchive(new TarOutputStream(outputStream, blockFactor)); + } + #endregion + + /// + /// Set the flag that determines whether existing files are + /// kept, or overwritten during extraction. + /// + /// + /// If true, do not overwrite existing files. + /// + public void SetKeepOldFiles(bool keepExistingFiles) + { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + keepOldFiles = keepExistingFiles; + } + + /// + /// Get/set the ascii file translation flag. If ascii file translation + /// is true, then the file is checked to see if it a binary file or not. + /// If the flag is true and the test indicates it is ascii text + /// file, it will be translated. The translation converts the local + /// operating system's concept of line ends into the UNIX line end, + /// '\n', which is the defacto standard for a TAR archive. This makes + /// text files compatible with UNIX. + /// + public bool AsciiTranslate + { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + return asciiTranslate; + } + + set { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + asciiTranslate = value; + } + + } + + /// + /// Set the ascii file translation flag. + /// + /// + /// If true, translate ascii text files. + /// + [Obsolete("Use the AsciiTranslate property")] + public void SetAsciiTranslation(bool translateAsciiFiles) + { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + asciiTranslate = translateAsciiFiles; + } - /// - /// PathPrefix is added to entry names as they are written if the value is not null. - /// A slash character is appended after PathPrefix - /// - public string PathPrefix - { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - return pathPrefix; - } - - set { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - pathPrefix = value; - } - - } - - /// - /// RootPath is removed from entry names if it is found at the - /// beginning of the name. - /// - public string RootPath - { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - return rootPath; - } + /// + /// PathPrefix is added to entry names as they are written if the value is not null. + /// A slash character is appended after PathPrefix + /// + public string PathPrefix + { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + return pathPrefix; + } + + set { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + pathPrefix = value; + } + + } + + /// + /// RootPath is removed from entry names if it is found at the + /// beginning of the name. + /// + public string RootPath + { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + return rootPath; + } - set { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - rootPath = value; - } - } - - /// - /// Set user and group information that will be used to fill in the - /// tar archive's entry headers. This information is based on that available - /// for the linux operating system, which is not always available on other - /// operating systems. TarArchive allows the programmer to specify values - /// to be used in their place. - /// is set to true by this call. - /// - /// - /// The user id to use in the headers. - /// - /// - /// The user name to use in the headers. - /// - /// - /// The group id to use in the headers. - /// - /// - /// The group name to use in the headers. - /// - public void SetUserInfo(int userId, string userName, int groupId, string groupName) - { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - this.userId = userId; - this.userName = userName; - this.groupId = groupId; - this.groupName = groupName; - applyUserInfoOverrides = true; - } - - /// - /// Get or set a value indicating if overrides defined by SetUserInfo should be applied. - /// - /// If overrides are not applied then the values as set in each header will be used. - public bool ApplyUserInfoOverrides - { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - return applyUserInfoOverrides; - } + set { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + rootPath = value; + } + } + + /// + /// Set user and group information that will be used to fill in the + /// tar archive's entry headers. This information is based on that available + /// for the linux operating system, which is not always available on other + /// operating systems. TarArchive allows the programmer to specify values + /// to be used in their place. + /// is set to true by this call. + /// + /// + /// The user id to use in the headers. + /// + /// + /// The user name to use in the headers. + /// + /// + /// The group id to use in the headers. + /// + /// + /// The group name to use in the headers. + /// + public void SetUserInfo(int userId, string userName, int groupId, string groupName) + { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + this.userId = userId; + this.userName = userName; + this.groupId = groupId; + this.groupName = groupName; + applyUserInfoOverrides = true; + } + + /// + /// Get or set a value indicating if overrides defined by SetUserInfo should be applied. + /// + /// If overrides are not applied then the values as set in each header will be used. + public bool ApplyUserInfoOverrides + { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + return applyUserInfoOverrides; + } - set { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - applyUserInfoOverrides = value; - } - } + set { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + applyUserInfoOverrides = value; + } + } - /// - /// Get the archive user id. - /// See ApplyUserInfoOverrides for detail - /// on how to allow setting values on a per entry basis. - /// - /// - /// The current user id. - /// - public int UserId { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - return userId; - } - } - - /// - /// Get the archive user name. - /// See ApplyUserInfoOverrides for detail - /// on how to allow setting values on a per entry basis. - /// - /// - /// The current user name. - /// - public string UserName { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - return userName; - } - } - - /// - /// Get the archive group id. - /// See ApplyUserInfoOverrides for detail - /// on how to allow setting values on a per entry basis. - /// - /// - /// The current group id. - /// - public int GroupId { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - return groupId; - } - } - - /// - /// Get the archive group name. - /// See ApplyUserInfoOverrides for detail - /// on how to allow setting values on a per entry basis. - /// - /// - /// The current group name. - /// - public string GroupName { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - return groupName; - } - } - - /// - /// Get the archive's record size. Tar archives are composed of - /// a series of RECORDS each containing a number of BLOCKS. - /// This allowed tar archives to match the IO characteristics of - /// the physical device being used. Archives are expected - /// to be properly "blocked". - /// - /// - /// The record size this archive is using. - /// - public int RecordSize { - get { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - if (tarIn != null) { - return tarIn.RecordSize; - } else if (tarOut != null) { - return tarOut.RecordSize; - } - return TarBuffer.DefaultRecordSize; - } - } - - /// - /// Sets the IsStreamOwner property on the underlying stream. - /// Set this to false to prevent the Close of the TarArchive from closing the stream. - /// - public bool IsStreamOwner { - set { - if (tarIn != null) { - tarIn.IsStreamOwner = value; - } else { - tarOut.IsStreamOwner = value; - } - } - } + /// + /// Get the archive user id. + /// See ApplyUserInfoOverrides for detail + /// on how to allow setting values on a per entry basis. + /// + /// + /// The current user id. + /// + public int UserId { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + return userId; + } + } + + /// + /// Get the archive user name. + /// See ApplyUserInfoOverrides for detail + /// on how to allow setting values on a per entry basis. + /// + /// + /// The current user name. + /// + public string UserName { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + return userName; + } + } + + /// + /// Get the archive group id. + /// See ApplyUserInfoOverrides for detail + /// on how to allow setting values on a per entry basis. + /// + /// + /// The current group id. + /// + public int GroupId { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + return groupId; + } + } + + /// + /// Get the archive group name. + /// See ApplyUserInfoOverrides for detail + /// on how to allow setting values on a per entry basis. + /// + /// + /// The current group name. + /// + public string GroupName { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + return groupName; + } + } + + /// + /// Get the archive's record size. Tar archives are composed of + /// a series of RECORDS each containing a number of BLOCKS. + /// This allowed tar archives to match the IO characteristics of + /// the physical device being used. Archives are expected + /// to be properly "blocked". + /// + /// + /// The record size this archive is using. + /// + public int RecordSize { + get { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + if (tarIn != null) { + return tarIn.RecordSize; + } else if (tarOut != null) { + return tarOut.RecordSize; + } + return TarBuffer.DefaultRecordSize; + } + } + + /// + /// Sets the IsStreamOwner property on the underlying stream. + /// Set this to false to prevent the Close of the TarArchive from closing the stream. + /// + public bool IsStreamOwner { + set { + if (tarIn != null) { + tarIn.IsStreamOwner = value; + } else { + tarOut.IsStreamOwner = value; + } + } + } - /// - /// Close the archive. - /// - [Obsolete("Use Close instead")] - public void CloseArchive() - { - Close(); - } - - /// - /// Perform the "list" command for the archive contents. - /// - /// NOTE That this method uses the progress event to actually list - /// the contents. If the progress display event is not set, nothing will be listed! - /// - public void ListContents() - { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - while (true) { - TarEntry entry = tarIn.GetNextEntry(); - - if (entry == null) { - break; - } - OnProgressMessageEvent(entry, null); - } - } - - /// - /// Perform the "extract" command and extract the contents of the archive. - /// - /// - /// The destination directory into which to extract. - /// - public void ExtractContents(string destinationDirectory) - { - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - while (true) { - TarEntry entry = tarIn.GetNextEntry(); - - if (entry == null) { - break; - } - - ExtractEntry(destinationDirectory, entry); - } - } - - /// - /// Extract an entry from the archive. This method assumes that the - /// tarIn stream has been properly set with a call to GetNextEntry(). - /// - /// - /// The destination directory into which to extract. - /// - /// - /// The TarEntry returned by tarIn.GetNextEntry(). - /// - void ExtractEntry(string destDir, TarEntry entry) - { - OnProgressMessageEvent(entry, null); - - string name = entry.Name; - - if (Path.IsPathRooted(name)) { - // NOTE: - // for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt - name = name.Substring(Path.GetPathRoot(name).Length); - } - - name = name.Replace('/', Path.DirectorySeparatorChar); - - string destFile = Path.Combine(destDir, name); - - if (entry.IsDirectory) { - EnsureDirectoryExists(destFile); - } else { - string parentDirectory = Path.GetDirectoryName(destFile); - EnsureDirectoryExists(parentDirectory); - - bool process = true; - FileInfo fileInfo = new FileInfo(destFile); - if (fileInfo.Exists) { - if (keepOldFiles) { - OnProgressMessageEvent(entry, "Destination file already exists"); - process = false; - } else if ((fileInfo.Attributes & FileAttributes.ReadOnly) != 0) { - OnProgressMessageEvent(entry, "Destination file already exists, and is read-only"); - process = false; - } - } - - if (process) { - bool asciiTrans = false; - - Stream outputStream = File.Create(destFile); - if (this.asciiTranslate) { - asciiTrans = !IsBinary(destFile); - } - - StreamWriter outw = null; - if (asciiTrans) { - outw = new StreamWriter(outputStream); - } - - byte[] rdbuf = new byte[32 * 1024]; - - while (true) { - int numRead = tarIn.Read(rdbuf, 0, rdbuf.Length); - - if (numRead <= 0) { - break; - } - - if (asciiTrans) { - for (int off = 0, b = 0; b < numRead; ++b) { - if (rdbuf[b] == 10) { - string s = Encoding.ASCII.GetString(rdbuf, off, (b - off)); - outw.WriteLine(s); - off = b + 1; - } - } - } else { - outputStream.Write(rdbuf, 0, numRead); - } - } - - if (asciiTrans) { - outw.Close(); - } else { - outputStream.Close(); - } - } - } - } + /// + /// Close the archive. + /// + [Obsolete("Use Close instead")] + public void CloseArchive() + { + Close(); + } + + /// + /// Perform the "list" command for the archive contents. + /// + /// NOTE That this method uses the progress event to actually list + /// the contents. If the progress display event is not set, nothing will be listed! + /// + public void ListContents() + { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + while (true) { + TarEntry entry = tarIn.GetNextEntry(); + + if (entry == null) { + break; + } + OnProgressMessageEvent(entry, null); + } + } + + /// + /// Perform the "extract" command and extract the contents of the archive. + /// + /// + /// The destination directory into which to extract. + /// + public void ExtractContents(string destinationDirectory) + { + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + while (true) { + TarEntry entry = tarIn.GetNextEntry(); + + if (entry == null) { + break; + } + + ExtractEntry(destinationDirectory, entry); + } + } + + /// + /// Extract an entry from the archive. This method assumes that the + /// tarIn stream has been properly set with a call to GetNextEntry(). + /// + /// + /// The destination directory into which to extract. + /// + /// + /// The TarEntry returned by tarIn.GetNextEntry(). + /// + void ExtractEntry(string destDir, TarEntry entry) + { + OnProgressMessageEvent(entry, null); + + string name = entry.Name; + + if (Path.IsPathRooted(name)) { + // NOTE: + // for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt + name = name.Substring(Path.GetPathRoot(name).Length); + } + + name = name.Replace('/', Path.DirectorySeparatorChar); + + string destFile = Path.Combine(destDir, name); + + if (entry.IsDirectory) { + EnsureDirectoryExists(destFile); + } else { + string parentDirectory = Path.GetDirectoryName(destFile); + EnsureDirectoryExists(parentDirectory); + + bool process = true; + FileInfo fileInfo = new FileInfo(destFile); + if (fileInfo.Exists) { + if (keepOldFiles) { + OnProgressMessageEvent(entry, "Destination file already exists"); + process = false; + } else if ((fileInfo.Attributes & FileAttributes.ReadOnly) != 0) { + OnProgressMessageEvent(entry, "Destination file already exists, and is read-only"); + process = false; + } + } + + if (process) { + bool asciiTrans = false; + + Stream outputStream = File.Create(destFile); + if (this.asciiTranslate) { + asciiTrans = !IsBinary(destFile); + } + + StreamWriter outw = null; + if (asciiTrans) { + outw = new StreamWriter(outputStream); + } + + byte[] rdbuf = new byte[32 * 1024]; + + while (true) { + int numRead = tarIn.Read(rdbuf, 0, rdbuf.Length); + + if (numRead <= 0) { + break; + } + + if (asciiTrans) { + for (int off = 0, b = 0; b < numRead; ++b) { + if (rdbuf[b] == 10) { + string s = Encoding.ASCII.GetString(rdbuf, off, (b - off)); + outw.WriteLine(s); + off = b + 1; + } + } + } else { + outputStream.Write(rdbuf, 0, numRead); + } + } + + if (asciiTrans) { + outw.Close(); + } else { + outputStream.Close(); + } + } + } + } - /// - /// Write an entry to the archive. This method will call the putNextEntry - /// and then write the contents of the entry, and finally call closeEntry() - /// for entries that are files. For directories, it will call putNextEntry(), - /// and then, if the recurse flag is true, process each entry that is a - /// child of the directory. - /// - /// - /// The TarEntry representing the entry to write to the archive. - /// - /// - /// If true, process the children of directory entries. - /// - public void WriteEntry(TarEntry sourceEntry, bool recurse) - { - if ( sourceEntry == null ) { - throw new ArgumentNullException("sourceEntry"); - } - - if ( isDisposed ) { - throw new ObjectDisposedException("TarArchive"); - } - - try - { - if ( recurse ) { - TarHeader.SetValueDefaults(sourceEntry.UserId, sourceEntry.UserName, - sourceEntry.GroupId, sourceEntry.GroupName); - } - WriteEntryCore(sourceEntry, recurse); - } - finally - { - if ( recurse ) { - TarHeader.RestoreSetValues(); - } - } - } - - /// - /// Write an entry to the archive. This method will call the putNextEntry - /// and then write the contents of the entry, and finally call closeEntry() - /// for entries that are files. For directories, it will call putNextEntry(), - /// and then, if the recurse flag is true, process each entry that is a - /// child of the directory. - /// - /// - /// The TarEntry representing the entry to write to the archive. - /// - /// - /// If true, process the children of directory entries. - /// - void WriteEntryCore(TarEntry sourceEntry, bool recurse) - { - string tempFileName = null; - string entryFilename = sourceEntry.File; - - TarEntry entry = (TarEntry)sourceEntry.Clone(); + /// + /// Write an entry to the archive. This method will call the putNextEntry + /// and then write the contents of the entry, and finally call closeEntry() + /// for entries that are files. For directories, it will call putNextEntry(), + /// and then, if the recurse flag is true, process each entry that is a + /// child of the directory. + /// + /// + /// The TarEntry representing the entry to write to the archive. + /// + /// + /// If true, process the children of directory entries. + /// + public void WriteEntry(TarEntry sourceEntry, bool recurse) + { + if ( sourceEntry == null ) { + throw new ArgumentNullException("sourceEntry"); + } + + if ( isDisposed ) { + throw new ObjectDisposedException("TarArchive"); + } + + try + { + if ( recurse ) { + TarHeader.SetValueDefaults(sourceEntry.UserId, sourceEntry.UserName, + sourceEntry.GroupId, sourceEntry.GroupName); + } + WriteEntryCore(sourceEntry, recurse); + } + finally + { + if ( recurse ) { + TarHeader.RestoreSetValues(); + } + } + } + + /// + /// Write an entry to the archive. This method will call the putNextEntry + /// and then write the contents of the entry, and finally call closeEntry() + /// for entries that are files. For directories, it will call putNextEntry(), + /// and then, if the recurse flag is true, process each entry that is a + /// child of the directory. + /// + /// + /// The TarEntry representing the entry to write to the archive. + /// + /// + /// If true, process the children of directory entries. + /// + void WriteEntryCore(TarEntry sourceEntry, bool recurse) + { + string tempFileName = null; + string entryFilename = sourceEntry.File; + + TarEntry entry = (TarEntry)sourceEntry.Clone(); - if ( applyUserInfoOverrides ) { - entry.GroupId = groupId; - entry.GroupName = groupName; - entry.UserId = userId; - entry.UserName = userName; - } - - OnProgressMessageEvent(entry, null); - - if (asciiTranslate && !entry.IsDirectory) { + if ( applyUserInfoOverrides ) { + entry.GroupId = groupId; + entry.GroupName = groupName; + entry.UserId = userId; + entry.UserName = userName; + } + + OnProgressMessageEvent(entry, null); + + if (asciiTranslate && !entry.IsDirectory) { - if (!IsBinary(entryFilename)) { - tempFileName = Path.GetTempFileName(); - - using (StreamReader inStream = File.OpenText(entryFilename)) { - using (Stream outStream = File.Create(tempFileName)) { - - while (true) { - string line = inStream.ReadLine(); - if (line == null) { - break; - } - byte[] data = Encoding.ASCII.GetBytes(line); - outStream.Write(data, 0, data.Length); - outStream.WriteByte((byte)'\n'); - } - - outStream.Flush(); - } - } - - entry.Size = new FileInfo(tempFileName).Length; - entryFilename = tempFileName; - } - } - - string newName = null; - - if (rootPath != null) { - if (entry.Name.StartsWith(rootPath)) { - newName = entry.Name.Substring(rootPath.Length + 1 ); - } - } - - if (pathPrefix != null) { - newName = (newName == null) ? pathPrefix + "/" + entry.Name : pathPrefix + "/" + newName; - } - - if (newName != null) { - entry.Name = newName; - } - - tarOut.PutNextEntry(entry); - - if (entry.IsDirectory) { - if (recurse) { - TarEntry[] list = entry.GetDirectoryEntries(); - for (int i = 0; i < list.Length; ++i) { - WriteEntryCore(list[i], recurse); - } - } - } - else { - using (Stream inputStream = File.OpenRead(entryFilename)) { - byte[] localBuffer = new byte[32 * 1024]; - while (true) { - int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); - - if (numRead <=0) { - break; - } - - tarOut.Write(localBuffer, 0, numRead); - } - } - - if ( (tempFileName != null) && (tempFileName.Length > 0) ) { - File.Delete(tempFileName); - } - - tarOut.CloseEntry(); - } - } + if (!IsBinary(entryFilename)) { + tempFileName = Path.GetTempFileName(); + + using (StreamReader inStream = File.OpenText(entryFilename)) { + using (Stream outStream = File.Create(tempFileName)) { + + while (true) { + string line = inStream.ReadLine(); + if (line == null) { + break; + } + byte[] data = Encoding.ASCII.GetBytes(line); + outStream.Write(data, 0, data.Length); + outStream.WriteByte((byte)'\n'); + } + + outStream.Flush(); + } + } + + entry.Size = new FileInfo(tempFileName).Length; + entryFilename = tempFileName; + } + } + + string newName = null; + + if (rootPath != null) { + if (entry.Name.StartsWith(rootPath)) { + newName = entry.Name.Substring(rootPath.Length + 1 ); + } + } + + if (pathPrefix != null) { + newName = (newName == null) ? pathPrefix + "/" + entry.Name : pathPrefix + "/" + newName; + } + + if (newName != null) { + entry.Name = newName; + } + + tarOut.PutNextEntry(entry); + + if (entry.IsDirectory) { + if (recurse) { + TarEntry[] list = entry.GetDirectoryEntries(); + for (int i = 0; i < list.Length; ++i) { + WriteEntryCore(list[i], recurse); + } + } + } + else { + using (Stream inputStream = File.OpenRead(entryFilename)) { + byte[] localBuffer = new byte[32 * 1024]; + while (true) { + int numRead = inputStream.Read(localBuffer, 0, localBuffer.Length); + + if (numRead <=0) { + break; + } + + tarOut.Write(localBuffer, 0, numRead); + } + } + + if ( (tempFileName != null) && (tempFileName.Length > 0) ) { + File.Delete(tempFileName); + } + + tarOut.CloseEntry(); + } + } /// /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. @@ -781,114 +781,114 @@ public void Dispose() GC.SuppressFinalize(this); } - /// - /// Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. - /// - /// true to release both managed and unmanaged resources; - /// false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) - { - if ( !isDisposed ) { - isDisposed = true; - if ( disposing ) { - if ( tarOut != null ) { - tarOut.Flush(); - tarOut.Close(); - } - - if ( tarIn != null ) { - tarIn.Close(); - } - } - } - } - - /// - /// Closes the archive and releases any associated resources. - /// - public virtual void Close() - { - Dispose(true); - } - - /// - /// Ensures that resources are freed and other cleanup operations are performed - /// when the garbage collector reclaims the . - /// - ~TarArchive() - { - Dispose(false); - } - - static void EnsureDirectoryExists(string directoryName) - { - if (!Directory.Exists(directoryName)) { - try { - Directory.CreateDirectory(directoryName); - } - catch (Exception e) { - throw new TarException("Exception creating directory '" + directoryName + "', " + e.Message, e); - } - } - } - - // TODO: TarArchive - Is there a better way to test for a text file? - // It no longer reads entire files into memory but is still a weak test! - // This assumes that byte values 0-7, 14-31 or 255 are binary - // and that all non text files contain one of these values - static bool IsBinary(string filename) - { - using (FileStream fs = File.OpenRead(filename)) - { - int sampleSize = Math.Min(4096, (int)fs.Length); - byte[] content = new byte[sampleSize]; - - int bytesRead = fs.Read(content, 0, sampleSize); - - for (int i = 0; i < bytesRead; ++i) { - byte b = content[i]; - if ( (b < 8) || ((b > 13) && (b < 32)) || (b == 255) ) { - return true; - } - } - } - return false; - } - - #region Instance Fields - bool keepOldFiles; - bool asciiTranslate; - - int userId; - string userName = string.Empty; - int groupId; - string groupName = string.Empty; - - string rootPath; - string pathPrefix; - - bool applyUserInfoOverrides; - - TarInputStream tarIn; - TarOutputStream tarOut; - bool isDisposed; - #endregion - } + /// + /// Releases the unmanaged resources used by the FileStream and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; + /// false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if ( !isDisposed ) { + isDisposed = true; + if ( disposing ) { + if ( tarOut != null ) { + tarOut.Flush(); + tarOut.Close(); + } + + if ( tarIn != null ) { + tarIn.Close(); + } + } + } + } + + /// + /// Closes the archive and releases any associated resources. + /// + public virtual void Close() + { + Dispose(true); + } + + /// + /// Ensures that resources are freed and other cleanup operations are performed + /// when the garbage collector reclaims the . + /// + ~TarArchive() + { + Dispose(false); + } + + static void EnsureDirectoryExists(string directoryName) + { + if (!Directory.Exists(directoryName)) { + try { + Directory.CreateDirectory(directoryName); + } + catch (Exception e) { + throw new TarException("Exception creating directory '" + directoryName + "', " + e.Message, e); + } + } + } + + // TODO: TarArchive - Is there a better way to test for a text file? + // It no longer reads entire files into memory but is still a weak test! + // This assumes that byte values 0-7, 14-31 or 255 are binary + // and that all non text files contain one of these values + static bool IsBinary(string filename) + { + using (FileStream fs = File.OpenRead(filename)) + { + int sampleSize = Math.Min(4096, (int)fs.Length); + byte[] content = new byte[sampleSize]; + + int bytesRead = fs.Read(content, 0, sampleSize); + + for (int i = 0; i < bytesRead; ++i) { + byte b = content[i]; + if ( (b < 8) || ((b > 13) && (b < 32)) || (b == 255) ) { + return true; + } + } + } + return false; + } + + #region Instance Fields + bool keepOldFiles; + bool asciiTranslate; + + int userId; + string userName = string.Empty; + int groupId; + string groupName = string.Empty; + + string rootPath; + string pathPrefix; + + bool applyUserInfoOverrides; + + TarInputStream tarIn; + TarOutputStream tarOut; + bool isDisposed; + #endregion + } } /* The original Java file had this header: - ** Authored by Timothy Gerard Endres - ** - ** - ** This work has been placed into the public domain. - ** You may use this work in any way and for any purpose you wish. - ** - ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, - ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR - ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY - ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR - ** REDISTRIBUTION OF THIS SOFTWARE. - ** - */ + ** Authored by Timothy Gerard Endres + ** + ** + ** This work has been placed into the public domain. + ** You may use this work in any way and for any purpose you wish. + ** + ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, + ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR + ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY + ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR + ** REDISTRIBUTION OF THIS SOFTWARE. + ** + */ diff --git a/External/Tools/AppMan/ZipLib/Tar/TarBuffer.cs b/External/Tools/AppMan/ZipLib/Tar/TarBuffer.cs index 40b8d93182..6e3eb6ded8 100644 --- a/External/Tools/AppMan/ZipLib/Tar/TarBuffer.cs +++ b/External/Tools/AppMan/ZipLib/Tar/TarBuffer.cs @@ -37,21 +37,21 @@ namespace ICSharpCode.SharpZipLib.Tar { - - /// - /// The TarBuffer class implements the tar archive concept - /// of a buffered input stream. This concept goes back to the - /// days of blocked tape drives and special io devices. In the - /// C# universe, the only real function that this class - /// performs is to ensure that files have the correct "record" - /// size, or other tars will complain. - ///

    - /// You should never have a need to access this class directly. - /// TarBuffers are created by Tar IO Streams. - ///

    - ///
    - public class TarBuffer - { + + /// + /// The TarBuffer class implements the tar archive concept + /// of a buffered input stream. This concept goes back to the + /// days of blocked tape drives and special io devices. In the + /// C# universe, the only real function that this class + /// performs is to ensure that files have the correct "record" + /// size, or other tars will complain. + ///

    + /// You should never have a need to access this class directly. + /// TarBuffers are created by Tar IO Streams. + ///

    + ///
    + public class TarBuffer + { /* A quote from GNU tar man file on blocking and records A `tar' archive file contains a series of blocks. Each block @@ -75,345 +75,345 @@ record of N blocks is written with a single 'write ()' or which contains garbage records after a zero block. */ - #region Constants - /// - /// The size of a block in a tar archive in bytes. - /// - /// This is 512 bytes. - public const int BlockSize = 512; - - /// - /// The number of blocks in a default record. - /// - /// - /// The default value is 20 blocks per record. - /// - public const int DefaultBlockFactor = 20; - - /// - /// The size in bytes of a default record. - /// - /// - /// The default size is 10KB. - /// - public const int DefaultRecordSize = BlockSize * DefaultBlockFactor; - #endregion - - /// - /// Get the record size for this buffer - /// - /// The record size in bytes. - /// This is equal to the multiplied by the - public int RecordSize - { - get { - return recordSize; - } - } - - /// - /// Get the TAR Buffer's record size. - /// - /// The record size in bytes. - /// This is equal to the multiplied by the - [Obsolete("Use RecordSize property instead")] - public int GetRecordSize() - { - return recordSize; - } - - /// - /// Get the Blocking factor for the buffer - /// - /// This is the number of blocks in each record. - public int BlockFactor { - get { - return blockFactor; - } - } - - /// - /// Get the TAR Buffer's block factor - /// - /// The block factor; the number of blocks per record. - [Obsolete("Use BlockFactor property instead")] - public int GetBlockFactor() - { - return blockFactor; - } - - /// - /// Construct a default TarBuffer - /// - protected TarBuffer() - { - } - - /// - /// Create TarBuffer for reading with default BlockFactor - /// - /// Stream to buffer - /// A new suitable for input. - public static TarBuffer CreateInputTarBuffer(Stream inputStream) - { - if ( inputStream == null ) - { - throw new ArgumentNullException("inputStream"); - } - - return CreateInputTarBuffer(inputStream, DefaultBlockFactor); - } - - /// - /// Construct TarBuffer for reading inputStream setting BlockFactor - /// - /// Stream to buffer - /// Blocking factor to apply - /// A new suitable for input. - public static TarBuffer CreateInputTarBuffer(Stream inputStream, int blockFactor) - { - if ( inputStream == null ) - { - throw new ArgumentNullException("inputStream"); - } - - if ( blockFactor <= 0 ) - { + #region Constants + /// + /// The size of a block in a tar archive in bytes. + /// + /// This is 512 bytes. + public const int BlockSize = 512; + + /// + /// The number of blocks in a default record. + /// + /// + /// The default value is 20 blocks per record. + /// + public const int DefaultBlockFactor = 20; + + /// + /// The size in bytes of a default record. + /// + /// + /// The default size is 10KB. + /// + public const int DefaultRecordSize = BlockSize * DefaultBlockFactor; + #endregion + + /// + /// Get the record size for this buffer + /// + /// The record size in bytes. + /// This is equal to the multiplied by the + public int RecordSize + { + get { + return recordSize; + } + } + + /// + /// Get the TAR Buffer's record size. + /// + /// The record size in bytes. + /// This is equal to the multiplied by the + [Obsolete("Use RecordSize property instead")] + public int GetRecordSize() + { + return recordSize; + } + + /// + /// Get the Blocking factor for the buffer + /// + /// This is the number of blocks in each record. + public int BlockFactor { + get { + return blockFactor; + } + } + + /// + /// Get the TAR Buffer's block factor + /// + /// The block factor; the number of blocks per record. + [Obsolete("Use BlockFactor property instead")] + public int GetBlockFactor() + { + return blockFactor; + } + + /// + /// Construct a default TarBuffer + /// + protected TarBuffer() + { + } + + /// + /// Create TarBuffer for reading with default BlockFactor + /// + /// Stream to buffer + /// A new suitable for input. + public static TarBuffer CreateInputTarBuffer(Stream inputStream) + { + if ( inputStream == null ) + { + throw new ArgumentNullException("inputStream"); + } + + return CreateInputTarBuffer(inputStream, DefaultBlockFactor); + } + + /// + /// Construct TarBuffer for reading inputStream setting BlockFactor + /// + /// Stream to buffer + /// Blocking factor to apply + /// A new suitable for input. + public static TarBuffer CreateInputTarBuffer(Stream inputStream, int blockFactor) + { + if ( inputStream == null ) + { + throw new ArgumentNullException("inputStream"); + } + + if ( blockFactor <= 0 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("blockFactor"); + throw new ArgumentOutOfRangeException("blockFactor"); #else - throw new ArgumentOutOfRangeException("blockFactor", "Factor cannot be negative"); -#endif - } - - TarBuffer tarBuffer = new TarBuffer(); - tarBuffer.inputStream = inputStream; - tarBuffer.outputStream = null; - tarBuffer.Initialize(blockFactor); - - return tarBuffer; - } - - /// - /// Construct TarBuffer for writing with default BlockFactor - /// - /// output stream for buffer - /// A new suitable for output. - public static TarBuffer CreateOutputTarBuffer(Stream outputStream) - { - if ( outputStream == null ) - { - throw new ArgumentNullException("outputStream"); - } - - return CreateOutputTarBuffer(outputStream, DefaultBlockFactor); - } - - /// - /// Construct TarBuffer for writing Tar output to streams. - /// - /// Output stream to write to. - /// Blocking factor to apply - /// A new suitable for output. - public static TarBuffer CreateOutputTarBuffer(Stream outputStream, int blockFactor) - { - if ( outputStream == null ) - { - throw new ArgumentNullException("outputStream"); - } - - if ( blockFactor <= 0 ) - { + throw new ArgumentOutOfRangeException("blockFactor", "Factor cannot be negative"); +#endif + } + + TarBuffer tarBuffer = new TarBuffer(); + tarBuffer.inputStream = inputStream; + tarBuffer.outputStream = null; + tarBuffer.Initialize(blockFactor); + + return tarBuffer; + } + + /// + /// Construct TarBuffer for writing with default BlockFactor + /// + /// output stream for buffer + /// A new suitable for output. + public static TarBuffer CreateOutputTarBuffer(Stream outputStream) + { + if ( outputStream == null ) + { + throw new ArgumentNullException("outputStream"); + } + + return CreateOutputTarBuffer(outputStream, DefaultBlockFactor); + } + + /// + /// Construct TarBuffer for writing Tar output to streams. + /// + /// Output stream to write to. + /// Blocking factor to apply + /// A new suitable for output. + public static TarBuffer CreateOutputTarBuffer(Stream outputStream, int blockFactor) + { + if ( outputStream == null ) + { + throw new ArgumentNullException("outputStream"); + } + + if ( blockFactor <= 0 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("blockFactor"); + throw new ArgumentOutOfRangeException("blockFactor"); #else - throw new ArgumentOutOfRangeException("blockFactor", "Factor cannot be negative"); -#endif - } - - TarBuffer tarBuffer = new TarBuffer(); - tarBuffer.inputStream = null; - tarBuffer.outputStream = outputStream; - tarBuffer.Initialize(blockFactor); - - return tarBuffer; - } - - /// - /// Initialization common to all constructors. - /// - void Initialize(int archiveBlockFactor) - { - blockFactor = archiveBlockFactor; - recordSize = archiveBlockFactor * BlockSize; - recordBuffer = new byte[RecordSize]; - - if (inputStream != null) { - currentRecordIndex = -1; - currentBlockIndex = BlockFactor; - } - else { - currentRecordIndex = 0; - currentBlockIndex = 0; - } - } - - /// - /// Determine if an archive block indicates End of Archive. End of - /// archive is indicated by a block that consists entirely of null bytes. - /// All remaining blocks for the record should also be null's - /// However some older tars only do a couple of null blocks (Old GNU tar for one) - /// and also partial records - /// - /// The data block to check. - /// Returns true if the block is an EOF block; false otherwise. - [Obsolete("Use IsEndOfArchiveBlock instead")] - public bool IsEOFBlock(byte[] block) - { - if ( block == null ) { - throw new ArgumentNullException("block"); - } - - if ( block.Length != BlockSize ) - { - throw new ArgumentException("block length is invalid"); - } - - for (int i = 0; i < BlockSize; ++i) { - if (block[i] != 0) { - return false; - } - } - - return true; - } - - - /// - /// Determine if an archive block indicates the End of an Archive has been reached. - /// End of archive is indicated by a block that consists entirely of null bytes. - /// All remaining blocks for the record should also be null's - /// However some older tars only do a couple of null blocks (Old GNU tar for one) - /// and also partial records - /// - /// The data block to check. - /// Returns true if the block is an EOF block; false otherwise. - public static bool IsEndOfArchiveBlock(byte[] block) - { - if ( block == null ) { - throw new ArgumentNullException("block"); - } - - if ( block.Length != BlockSize ) { - throw new ArgumentException("block length is invalid"); - } - - for ( int i = 0; i < BlockSize; ++i ) { - if ( block[i] != 0 ) { - return false; - } - } - - return true; - } - - /// - /// Skip over a block on the input stream. - /// - public void SkipBlock() - { - if (inputStream == null) { - throw new TarException("no input stream defined"); - } - - if (currentBlockIndex >= BlockFactor) { - if (!ReadRecord()) { - throw new TarException("Failed to read a record"); - } - } - - currentBlockIndex++; - } - - /// - /// Read a block from the input stream. - /// - /// - /// The block of data read. - /// - public byte[] ReadBlock() - { - if (inputStream == null) { - throw new TarException("TarBuffer.ReadBlock - no input stream defined"); - } - - if (currentBlockIndex >= BlockFactor) { - if (!ReadRecord()) { - throw new TarException("Failed to read a record"); - } - } - - byte[] result = new byte[BlockSize]; - - Array.Copy(recordBuffer, (currentBlockIndex * BlockSize), result, 0, BlockSize ); - currentBlockIndex++; - return result; - } - - /// - /// Read a record from data stream. - /// - /// - /// false if End-Of-File, else true. - /// - bool ReadRecord() - { - if (inputStream == null) { - throw new TarException("no input stream stream defined"); - } - - currentBlockIndex = 0; - - int offset = 0; - int bytesNeeded = RecordSize; - - while (bytesNeeded > 0) { - long numBytes = inputStream.Read(recordBuffer, offset, bytesNeeded); - - // - // NOTE - // We have found EOF, and the record is not full! - // - // This is a broken archive. It does not follow the standard - // blocking algorithm. However, because we are generous, and - // it requires little effort, we will simply ignore the error - // and continue as if the entire record were read. This does - // not appear to break anything upstream. We used to return - // false in this case. - // - // Thanks to 'Yohann.Roussel@alcatel.fr' for this fix. - // - if (numBytes <= 0) { - break; - } - - offset += (int)numBytes; - bytesNeeded -= (int)numBytes; - } - - currentRecordIndex++; - return true; - } - - /// - /// Get the current block number, within the current record, zero based. - /// + throw new ArgumentOutOfRangeException("blockFactor", "Factor cannot be negative"); +#endif + } + + TarBuffer tarBuffer = new TarBuffer(); + tarBuffer.inputStream = null; + tarBuffer.outputStream = outputStream; + tarBuffer.Initialize(blockFactor); + + return tarBuffer; + } + + /// + /// Initialization common to all constructors. + /// + void Initialize(int archiveBlockFactor) + { + blockFactor = archiveBlockFactor; + recordSize = archiveBlockFactor * BlockSize; + recordBuffer = new byte[RecordSize]; + + if (inputStream != null) { + currentRecordIndex = -1; + currentBlockIndex = BlockFactor; + } + else { + currentRecordIndex = 0; + currentBlockIndex = 0; + } + } + + /// + /// Determine if an archive block indicates End of Archive. End of + /// archive is indicated by a block that consists entirely of null bytes. + /// All remaining blocks for the record should also be null's + /// However some older tars only do a couple of null blocks (Old GNU tar for one) + /// and also partial records + /// + /// The data block to check. + /// Returns true if the block is an EOF block; false otherwise. + [Obsolete("Use IsEndOfArchiveBlock instead")] + public bool IsEOFBlock(byte[] block) + { + if ( block == null ) { + throw new ArgumentNullException("block"); + } + + if ( block.Length != BlockSize ) + { + throw new ArgumentException("block length is invalid"); + } + + for (int i = 0; i < BlockSize; ++i) { + if (block[i] != 0) { + return false; + } + } + + return true; + } + + + /// + /// Determine if an archive block indicates the End of an Archive has been reached. + /// End of archive is indicated by a block that consists entirely of null bytes. + /// All remaining blocks for the record should also be null's + /// However some older tars only do a couple of null blocks (Old GNU tar for one) + /// and also partial records + /// + /// The data block to check. + /// Returns true if the block is an EOF block; false otherwise. + public static bool IsEndOfArchiveBlock(byte[] block) + { + if ( block == null ) { + throw new ArgumentNullException("block"); + } + + if ( block.Length != BlockSize ) { + throw new ArgumentException("block length is invalid"); + } + + for ( int i = 0; i < BlockSize; ++i ) { + if ( block[i] != 0 ) { + return false; + } + } + + return true; + } + + /// + /// Skip over a block on the input stream. + /// + public void SkipBlock() + { + if (inputStream == null) { + throw new TarException("no input stream defined"); + } + + if (currentBlockIndex >= BlockFactor) { + if (!ReadRecord()) { + throw new TarException("Failed to read a record"); + } + } + + currentBlockIndex++; + } + + /// + /// Read a block from the input stream. + /// + /// + /// The block of data read. + /// + public byte[] ReadBlock() + { + if (inputStream == null) { + throw new TarException("TarBuffer.ReadBlock - no input stream defined"); + } + + if (currentBlockIndex >= BlockFactor) { + if (!ReadRecord()) { + throw new TarException("Failed to read a record"); + } + } + + byte[] result = new byte[BlockSize]; + + Array.Copy(recordBuffer, (currentBlockIndex * BlockSize), result, 0, BlockSize ); + currentBlockIndex++; + return result; + } + + /// + /// Read a record from data stream. + /// + /// + /// false if End-Of-File, else true. + /// + bool ReadRecord() + { + if (inputStream == null) { + throw new TarException("no input stream stream defined"); + } + + currentBlockIndex = 0; + + int offset = 0; + int bytesNeeded = RecordSize; + + while (bytesNeeded > 0) { + long numBytes = inputStream.Read(recordBuffer, offset, bytesNeeded); + + // + // NOTE + // We have found EOF, and the record is not full! + // + // This is a broken archive. It does not follow the standard + // blocking algorithm. However, because we are generous, and + // it requires little effort, we will simply ignore the error + // and continue as if the entire record were read. This does + // not appear to break anything upstream. We used to return + // false in this case. + // + // Thanks to 'Yohann.Roussel@alcatel.fr' for this fix. + // + if (numBytes <= 0) { + break; + } + + offset += (int)numBytes; + bytesNeeded -= (int)numBytes; + } + + currentRecordIndex++; + return true; + } + + /// + /// Get the current block number, within the current record, zero based. + /// /// Block numbers are zero based values /// - public int CurrentBlock - { - get { return currentBlockIndex; } - } + public int CurrentBlock + { + get { return currentBlockIndex; } + } /// /// Get/set flag indicating ownership of the underlying stream. @@ -425,200 +425,200 @@ public bool IsStreamOwner set { isStreamOwner_ = value; } } - /// - /// Get the current block number, within the current record, zero based. - /// - /// - /// The current zero based block number. - /// - /// - /// The absolute block number = (record number * block factor) + block number. - /// - [Obsolete("Use CurrentBlock property instead")] - public int GetCurrentBlockNum() - { - return currentBlockIndex; - } - - /// - /// Get the current record number. - /// - /// - /// The current zero based record number. - /// - public int CurrentRecord - { - get { return currentRecordIndex; } - } - - /// - /// Get the current record number. - /// - /// - /// The current zero based record number. - /// - [Obsolete("Use CurrentRecord property instead")] - public int GetCurrentRecordNum() - { - return currentRecordIndex; - } - - /// - /// Write a block of data to the archive. - /// - /// - /// The data to write to the archive. - /// - public void WriteBlock(byte[] block) - { - if ( block == null ) { - throw new ArgumentNullException("block"); - } - - if (outputStream == null) { - throw new TarException("TarBuffer.WriteBlock - no output stream defined"); - } - - if (block.Length != BlockSize) { - string errorText = string.Format("TarBuffer.WriteBlock - block to write has length '{0}' which is not the block size of '{1}'", - block.Length, BlockSize ); - throw new TarException(errorText); - } - - if (currentBlockIndex >= BlockFactor) { - WriteRecord(); - } - - Array.Copy(block, 0, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); - currentBlockIndex++; - } - - /// - /// Write an archive record to the archive, where the record may be - /// inside of a larger array buffer. The buffer must be "offset plus - /// record size" long. - /// - /// - /// The buffer containing the record data to write. - /// - /// - /// The offset of the record data within buffer. - /// - public void WriteBlock(byte[] buffer, int offset) - { - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } - - if (outputStream == null) { - throw new TarException("TarBuffer.WriteBlock - no output stream stream defined"); - } - - if ( (offset < 0) || (offset >= buffer.Length) ) - { - throw new ArgumentOutOfRangeException("offset"); - } - - if ((offset + BlockSize) > buffer.Length) { - string errorText = string.Format("TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'", - buffer.Length, offset, recordSize); - throw new TarException(errorText); - } - - if (currentBlockIndex >= BlockFactor) { - WriteRecord(); - } - - Array.Copy(buffer, offset, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); - - currentBlockIndex++; - } - - /// - /// Write a TarBuffer record to the archive. - /// - void WriteRecord() - { - if (outputStream == null) { - throw new TarException("TarBuffer.WriteRecord no output stream defined"); - } - - outputStream.Write(recordBuffer, 0, RecordSize); - outputStream.Flush(); - - currentBlockIndex = 0; - currentRecordIndex++; - } - - /// - /// WriteFinalRecord writes the current record buffer to output any unwritten data is present. - /// + /// + /// Get the current block number, within the current record, zero based. + /// + /// + /// The current zero based block number. + /// + /// + /// The absolute block number = (record number * block factor) + block number. + /// + [Obsolete("Use CurrentBlock property instead")] + public int GetCurrentBlockNum() + { + return currentBlockIndex; + } + + /// + /// Get the current record number. + /// + /// + /// The current zero based record number. + /// + public int CurrentRecord + { + get { return currentRecordIndex; } + } + + /// + /// Get the current record number. + /// + /// + /// The current zero based record number. + /// + [Obsolete("Use CurrentRecord property instead")] + public int GetCurrentRecordNum() + { + return currentRecordIndex; + } + + /// + /// Write a block of data to the archive. + /// + /// + /// The data to write to the archive. + /// + public void WriteBlock(byte[] block) + { + if ( block == null ) { + throw new ArgumentNullException("block"); + } + + if (outputStream == null) { + throw new TarException("TarBuffer.WriteBlock - no output stream defined"); + } + + if (block.Length != BlockSize) { + string errorText = string.Format("TarBuffer.WriteBlock - block to write has length '{0}' which is not the block size of '{1}'", + block.Length, BlockSize ); + throw new TarException(errorText); + } + + if (currentBlockIndex >= BlockFactor) { + WriteRecord(); + } + + Array.Copy(block, 0, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); + currentBlockIndex++; + } + + /// + /// Write an archive record to the archive, where the record may be + /// inside of a larger array buffer. The buffer must be "offset plus + /// record size" long. + /// + /// + /// The buffer containing the record data to write. + /// + /// + /// The offset of the record data within buffer. + /// + public void WriteBlock(byte[] buffer, int offset) + { + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } + + if (outputStream == null) { + throw new TarException("TarBuffer.WriteBlock - no output stream stream defined"); + } + + if ( (offset < 0) || (offset >= buffer.Length) ) + { + throw new ArgumentOutOfRangeException("offset"); + } + + if ((offset + BlockSize) > buffer.Length) { + string errorText = string.Format("TarBuffer.WriteBlock - record has length '{0}' with offset '{1}' which is less than the record size of '{2}'", + buffer.Length, offset, recordSize); + throw new TarException(errorText); + } + + if (currentBlockIndex >= BlockFactor) { + WriteRecord(); + } + + Array.Copy(buffer, offset, recordBuffer, (currentBlockIndex * BlockSize), BlockSize); + + currentBlockIndex++; + } + + /// + /// Write a TarBuffer record to the archive. + /// + void WriteRecord() + { + if (outputStream == null) { + throw new TarException("TarBuffer.WriteRecord no output stream defined"); + } + + outputStream.Write(recordBuffer, 0, RecordSize); + outputStream.Flush(); + + currentBlockIndex = 0; + currentRecordIndex++; + } + + /// + /// WriteFinalRecord writes the current record buffer to output any unwritten data is present. + /// /// Any trailing bytes are set to zero which is by definition correct behaviour /// for the end of a tar stream. - void WriteFinalRecord() - { - if (outputStream == null) { - throw new TarException("TarBuffer.WriteFinalRecord no output stream defined"); - } - - if (currentBlockIndex > 0) { - int dataBytes = currentBlockIndex * BlockSize; - Array.Clear(recordBuffer, dataBytes, RecordSize - dataBytes); - WriteRecord(); - } - - outputStream.Flush(); - } - - /// - /// Close the TarBuffer. If this is an output buffer, also flush the - /// current block before closing. - /// - public void Close() - { - if (outputStream != null) { - WriteFinalRecord(); + void WriteFinalRecord() + { + if (outputStream == null) { + throw new TarException("TarBuffer.WriteFinalRecord no output stream defined"); + } + + if (currentBlockIndex > 0) { + int dataBytes = currentBlockIndex * BlockSize; + Array.Clear(recordBuffer, dataBytes, RecordSize - dataBytes); + WriteRecord(); + } + + outputStream.Flush(); + } + + /// + /// Close the TarBuffer. If this is an output buffer, also flush the + /// current block before closing. + /// + public void Close() + { + if (outputStream != null) { + WriteFinalRecord(); if (isStreamOwner_) { outputStream.Close(); } - outputStream = null; - } - else if (inputStream != null) { + outputStream = null; + } + else if (inputStream != null) { if (isStreamOwner_) { inputStream.Close(); } - inputStream = null; - } - } - - #region Instance Fields - Stream inputStream; - Stream outputStream; - - byte[] recordBuffer; - int currentBlockIndex; - int currentRecordIndex; - - int recordSize = DefaultRecordSize; - int blockFactor = DefaultBlockFactor; + inputStream = null; + } + } + + #region Instance Fields + Stream inputStream; + Stream outputStream; + + byte[] recordBuffer; + int currentBlockIndex; + int currentRecordIndex; + + int recordSize = DefaultRecordSize; + int blockFactor = DefaultBlockFactor; bool isStreamOwner_ = true; - #endregion - } + #endregion + } } /* The original Java file had this header: - * - ** Authored by Timothy Gerard Endres - ** - ** - ** This work has been placed into the public domain. - ** You may use this work in any way and for any purpose you wish. - ** - ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, - ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR - ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY - ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR - ** REDISTRIBUTION OF THIS SOFTWARE. - ** - */ + * + ** Authored by Timothy Gerard Endres + ** + ** + ** This work has been placed into the public domain. + ** You may use this work in any way and for any purpose you wish. + ** + ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, + ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR + ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY + ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR + ** REDISTRIBUTION OF THIS SOFTWARE. + ** + */ diff --git a/External/Tools/AppMan/ZipLib/Tar/TarEntry.cs b/External/Tools/AppMan/ZipLib/Tar/TarEntry.cs index a733e32b1d..6edc096fc1 100644 --- a/External/Tools/AppMan/ZipLib/Tar/TarEntry.cs +++ b/External/Tools/AppMan/ZipLib/Tar/TarEntry.cs @@ -38,522 +38,522 @@ namespace ICSharpCode.SharpZipLib.Tar { - /// - /// This class represents an entry in a Tar archive. It consists - /// of the entry's header, as well as the entry's File. Entries - /// can be instantiated in one of three ways, depending on how - /// they are to be used. - ///

    - /// TarEntries that are created from the header bytes read from - /// an archive are instantiated with the TarEntry( byte[] ) - /// constructor. These entries will be used when extracting from - /// or listing the contents of an archive. These entries have their - /// header filled in using the header bytes. They also set the File - /// to null, since they reference an archive entry not a file.

    - ///

    - /// TarEntries that are created from files that are to be written - /// into an archive are instantiated with the CreateEntryFromFile(string) - /// pseudo constructor. These entries have their header filled in using - /// the File's information. They also keep a reference to the File - /// for convenience when writing entries.

    - ///

    - /// Finally, TarEntries can be constructed from nothing but a name. - /// This allows the programmer to construct the entry by hand, for - /// instance when only an InputStream is available for writing to - /// the archive, and the header information is constructed from - /// other information. In this case the header fields are set to - /// defaults and the File is set to null.

    - /// - ///
    - public class TarEntry : ICloneable - { - #region Constructors - /// - /// Initialise a default instance of . - /// - private TarEntry() - { - header = new TarHeader(); - } - - /// - /// Construct an entry from an archive's header bytes. File is set - /// to null. - /// - /// - /// The header bytes from a tar archive entry. - /// - public TarEntry(byte[] headerBuffer) - { - header = new TarHeader(); - header.ParseBuffer(headerBuffer); - } - - /// - /// Construct a TarEntry using the header provided - /// - /// Header details for entry - public TarEntry(TarHeader header) - { - if ( header == null ) - { - throw new ArgumentNullException("header"); - } + /// + /// This class represents an entry in a Tar archive. It consists + /// of the entry's header, as well as the entry's File. Entries + /// can be instantiated in one of three ways, depending on how + /// they are to be used. + ///

    + /// TarEntries that are created from the header bytes read from + /// an archive are instantiated with the TarEntry( byte[] ) + /// constructor. These entries will be used when extracting from + /// or listing the contents of an archive. These entries have their + /// header filled in using the header bytes. They also set the File + /// to null, since they reference an archive entry not a file.

    + ///

    + /// TarEntries that are created from files that are to be written + /// into an archive are instantiated with the CreateEntryFromFile(string) + /// pseudo constructor. These entries have their header filled in using + /// the File's information. They also keep a reference to the File + /// for convenience when writing entries.

    + ///

    + /// Finally, TarEntries can be constructed from nothing but a name. + /// This allows the programmer to construct the entry by hand, for + /// instance when only an InputStream is available for writing to + /// the archive, and the header information is constructed from + /// other information. In this case the header fields are set to + /// defaults and the File is set to null.

    + /// + ///
    + public class TarEntry : ICloneable + { + #region Constructors + /// + /// Initialise a default instance of . + /// + private TarEntry() + { + header = new TarHeader(); + } + + /// + /// Construct an entry from an archive's header bytes. File is set + /// to null. + /// + /// + /// The header bytes from a tar archive entry. + /// + public TarEntry(byte[] headerBuffer) + { + header = new TarHeader(); + header.ParseBuffer(headerBuffer); + } + + /// + /// Construct a TarEntry using the header provided + /// + /// Header details for entry + public TarEntry(TarHeader header) + { + if ( header == null ) + { + throw new ArgumentNullException("header"); + } - this.header = (TarHeader)header.Clone(); - } - #endregion + this.header = (TarHeader)header.Clone(); + } + #endregion - #region ICloneable Members - /// - /// Clone this tar entry. - /// - /// Returns a clone of this entry. - public object Clone() - { - TarEntry entry = new TarEntry(); - entry.file = file; - entry.header = (TarHeader)header.Clone(); - entry.Name = Name; - return entry; - } - #endregion + #region ICloneable Members + /// + /// Clone this tar entry. + /// + /// Returns a clone of this entry. + public object Clone() + { + TarEntry entry = new TarEntry(); + entry.file = file; + entry.header = (TarHeader)header.Clone(); + entry.Name = Name; + return entry; + } + #endregion - /// - /// Construct an entry with only a name. - /// This allows the programmer to construct the entry's header "by hand". - /// - /// The name to use for the entry - /// Returns the newly created - public static TarEntry CreateTarEntry(string name) - { - TarEntry entry = new TarEntry(); - TarEntry.NameTarHeader(entry.header, name); - return entry; - } - - /// - /// Construct an entry for a file. File is set to file, and the - /// header is constructed from information from the file. - /// - /// The file name that the entry represents. - /// Returns the newly created - public static TarEntry CreateEntryFromFile(string fileName) - { - TarEntry entry = new TarEntry(); - entry.GetFileTarHeader(entry.header, fileName); - return entry; - } - - /// - /// Determine if the two entries are equal. Equality is determined - /// by the header names being equal. - /// - /// The to compare with the current Object. - /// - /// True if the entries are equal; false if not. - /// - public override bool Equals(object obj) - { - TarEntry localEntry = obj as TarEntry; + /// + /// Construct an entry with only a name. + /// This allows the programmer to construct the entry's header "by hand". + /// + /// The name to use for the entry + /// Returns the newly created + public static TarEntry CreateTarEntry(string name) + { + TarEntry entry = new TarEntry(); + TarEntry.NameTarHeader(entry.header, name); + return entry; + } + + /// + /// Construct an entry for a file. File is set to file, and the + /// header is constructed from information from the file. + /// + /// The file name that the entry represents. + /// Returns the newly created + public static TarEntry CreateEntryFromFile(string fileName) + { + TarEntry entry = new TarEntry(); + entry.GetFileTarHeader(entry.header, fileName); + return entry; + } + + /// + /// Determine if the two entries are equal. Equality is determined + /// by the header names being equal. + /// + /// The to compare with the current Object. + /// + /// True if the entries are equal; false if not. + /// + public override bool Equals(object obj) + { + TarEntry localEntry = obj as TarEntry; - if ( localEntry != null ) - { - return Name.Equals(localEntry.Name); - } - return false; - } - - /// - /// Derive a Hash value for the current - /// - /// A Hash code for the current - public override int GetHashCode() - { - return Name.GetHashCode(); - } - - /// - /// Determine if the given entry is a descendant of this entry. - /// Descendancy is determined by the name of the descendant - /// starting with this entry's name. - /// - /// - /// Entry to be checked as a descendent of this. - /// - /// - /// True if entry is a descendant of this. - /// - public bool IsDescendent(TarEntry toTest) - { - if ( toTest == null ) { - throw new ArgumentNullException("toTest"); - } + if ( localEntry != null ) + { + return Name.Equals(localEntry.Name); + } + return false; + } + + /// + /// Derive a Hash value for the current + /// + /// A Hash code for the current + public override int GetHashCode() + { + return Name.GetHashCode(); + } + + /// + /// Determine if the given entry is a descendant of this entry. + /// Descendancy is determined by the name of the descendant + /// starting with this entry's name. + /// + /// + /// Entry to be checked as a descendent of this. + /// + /// + /// True if entry is a descendant of this. + /// + public bool IsDescendent(TarEntry toTest) + { + if ( toTest == null ) { + throw new ArgumentNullException("toTest"); + } - return toTest.Name.StartsWith(Name); - } - - /// - /// Get this entry's header. - /// - /// - /// This entry's TarHeader. - /// - public TarHeader TarHeader - { - get { - return header; - } - } - - /// - /// Get/Set this entry's name. - /// - public string Name - { - get { - return header.Name; - } - set { - header.Name = value; - } - } - - /// - /// Get/set this entry's user id. - /// - public int UserId - { - get { - return header.UserId; - } - set { - header.UserId = value; - } - } - - /// - /// Get/set this entry's group id. - /// - public int GroupId - { - get { - return header.GroupId; - } - set { - header.GroupId = value; - } - } - - /// - /// Get/set this entry's user name. - /// - public string UserName - { - get { - return header.UserName; - } - set { - header.UserName = value; - } - } - - /// - /// Get/set this entry's group name. - /// - public string GroupName - { - get { - return header.GroupName; - } - set { - header.GroupName = value; - } - } - - /// - /// Convenience method to set this entry's group and user ids. - /// - /// - /// This entry's new user id. - /// - /// - /// This entry's new group id. - /// - public void SetIds(int userId, int groupId) - { - UserId = userId; - GroupId = groupId; - } - - /// - /// Convenience method to set this entry's group and user names. - /// - /// - /// This entry's new user name. - /// - /// - /// This entry's new group name. - /// - public void SetNames(string userName, string groupName) - { - UserName = userName; - GroupName = groupName; - } + return toTest.Name.StartsWith(Name); + } + + /// + /// Get this entry's header. + /// + /// + /// This entry's TarHeader. + /// + public TarHeader TarHeader + { + get { + return header; + } + } + + /// + /// Get/Set this entry's name. + /// + public string Name + { + get { + return header.Name; + } + set { + header.Name = value; + } + } + + /// + /// Get/set this entry's user id. + /// + public int UserId + { + get { + return header.UserId; + } + set { + header.UserId = value; + } + } + + /// + /// Get/set this entry's group id. + /// + public int GroupId + { + get { + return header.GroupId; + } + set { + header.GroupId = value; + } + } + + /// + /// Get/set this entry's user name. + /// + public string UserName + { + get { + return header.UserName; + } + set { + header.UserName = value; + } + } + + /// + /// Get/set this entry's group name. + /// + public string GroupName + { + get { + return header.GroupName; + } + set { + header.GroupName = value; + } + } + + /// + /// Convenience method to set this entry's group and user ids. + /// + /// + /// This entry's new user id. + /// + /// + /// This entry's new group id. + /// + public void SetIds(int userId, int groupId) + { + UserId = userId; + GroupId = groupId; + } + + /// + /// Convenience method to set this entry's group and user names. + /// + /// + /// This entry's new user name. + /// + /// + /// This entry's new group name. + /// + public void SetNames(string userName, string groupName) + { + UserName = userName; + GroupName = groupName; + } - /// - /// Get/Set the modification time for this entry - /// - public DateTime ModTime { - get { - return header.ModTime; - } - set { - header.ModTime = value; - } - } - - /// - /// Get this entry's file. - /// - /// - /// This entry's file. - /// - public string File { - get { - return file; - } - } - - /// - /// Get/set this entry's recorded file size. - /// - public long Size { - get { - return header.Size; - } - set { - header.Size = value; - } - } - - /// - /// Return true if this entry represents a directory, false otherwise - /// - /// - /// True if this entry is a directory. - /// - public bool IsDirectory { - get { - if (file != null) { - return Directory.Exists(file); - } - - if (header != null) { - if ((header.TypeFlag == TarHeader.LF_DIR) || Name.EndsWith( "/" )) { - return true; - } - } - return false; - } - } - - /// - /// Fill in a TarHeader with information from a File. - /// - /// - /// The TarHeader to fill in. - /// - /// - /// The file from which to get the header information. - /// - public void GetFileTarHeader(TarHeader header, string file) - { - if ( header == null ) { - throw new ArgumentNullException("header"); - } + /// + /// Get/Set the modification time for this entry + /// + public DateTime ModTime { + get { + return header.ModTime; + } + set { + header.ModTime = value; + } + } + + /// + /// Get this entry's file. + /// + /// + /// This entry's file. + /// + public string File { + get { + return file; + } + } + + /// + /// Get/set this entry's recorded file size. + /// + public long Size { + get { + return header.Size; + } + set { + header.Size = value; + } + } + + /// + /// Return true if this entry represents a directory, false otherwise + /// + /// + /// True if this entry is a directory. + /// + public bool IsDirectory { + get { + if (file != null) { + return Directory.Exists(file); + } + + if (header != null) { + if ((header.TypeFlag == TarHeader.LF_DIR) || Name.EndsWith( "/" )) { + return true; + } + } + return false; + } + } + + /// + /// Fill in a TarHeader with information from a File. + /// + /// + /// The TarHeader to fill in. + /// + /// + /// The file from which to get the header information. + /// + public void GetFileTarHeader(TarHeader header, string file) + { + if ( header == null ) { + throw new ArgumentNullException("header"); + } - if ( file == null ) { - throw new ArgumentNullException("file"); - } + if ( file == null ) { + throw new ArgumentNullException("file"); + } - this.file = file; + this.file = file; - // bugfix from torhovl from #D forum: - string name = file; + // bugfix from torhovl from #D forum: + string name = file; #if !NETCF_1_0 && !NETCF_2_0 - // 23-Jan-2004 GnuTar allows device names in path where the name is not local to the current directory - if (name.IndexOf(Environment.CurrentDirectory) == 0) { - name = name.Substring(Environment.CurrentDirectory.Length); - } + // 23-Jan-2004 GnuTar allows device names in path where the name is not local to the current directory + if (name.IndexOf(Environment.CurrentDirectory) == 0) { + name = name.Substring(Environment.CurrentDirectory.Length); + } #endif - + /* - if (Path.DirectorySeparatorChar == '\\') - { - // check if the OS is Windows - // Strip off drive letters! - if (name.Length > 2) - { - char ch1 = name[0]; - char ch2 = name[1]; - - if (ch2 == ':' && Char.IsLetter(ch1)) - { - name = name.Substring(2); - } - } - } + if (Path.DirectorySeparatorChar == '\\') + { + // check if the OS is Windows + // Strip off drive letters! + if (name.Length > 2) + { + char ch1 = name[0]; + char ch2 = name[1]; + + if (ch2 == ':' && Char.IsLetter(ch1)) + { + name = name.Substring(2); + } + } + } */ - name = name.Replace(Path.DirectorySeparatorChar, '/'); + name = name.Replace(Path.DirectorySeparatorChar, '/'); - // No absolute pathnames - // Windows (and Posix?) paths can start with UNC style "\\NetworkDrive\", - // so we loop on starting /'s. - while (name.StartsWith("/")) { - name = name.Substring(1); - } + // No absolute pathnames + // Windows (and Posix?) paths can start with UNC style "\\NetworkDrive\", + // so we loop on starting /'s. + while (name.StartsWith("/")) { + name = name.Substring(1); + } - header.LinkName = String.Empty; - header.Name = name; - - if (Directory.Exists(file)) { - header.Mode = 1003; // Magic number for security access for a UNIX filesystem - header.TypeFlag = TarHeader.LF_DIR; - if ( (header.Name.Length == 0) || header.Name[header.Name.Length - 1] != '/') { - header.Name = header.Name + "/"; - } - - header.Size = 0; - } else { - header.Mode = 33216; // Magic number for security access for a UNIX filesystem - header.TypeFlag = TarHeader.LF_NORMAL; - header.Size = new FileInfo(file.Replace('/', Path.DirectorySeparatorChar)).Length; - } + header.LinkName = String.Empty; + header.Name = name; + + if (Directory.Exists(file)) { + header.Mode = 1003; // Magic number for security access for a UNIX filesystem + header.TypeFlag = TarHeader.LF_DIR; + if ( (header.Name.Length == 0) || header.Name[header.Name.Length - 1] != '/') { + header.Name = header.Name + "/"; + } + + header.Size = 0; + } else { + header.Mode = 33216; // Magic number for security access for a UNIX filesystem + header.TypeFlag = TarHeader.LF_NORMAL; + header.Size = new FileInfo(file.Replace('/', Path.DirectorySeparatorChar)).Length; + } - header.ModTime = System.IO.File.GetLastWriteTime(file.Replace('/', Path.DirectorySeparatorChar)).ToUniversalTime(); - header.DevMajor = 0; - header.DevMinor = 0; - } - - /// - /// Get entries for all files present in this entries directory. - /// If this entry doesnt represent a directory zero entries are returned. - /// - /// - /// An array of TarEntry's for this entry's children. - /// - public TarEntry[] GetDirectoryEntries() - { - if ( (file == null) || !Directory.Exists(file)) { - return new TarEntry[0]; - } - - string[] list = Directory.GetFileSystemEntries(file); - TarEntry[] result = new TarEntry[list.Length]; + header.ModTime = System.IO.File.GetLastWriteTime(file.Replace('/', Path.DirectorySeparatorChar)).ToUniversalTime(); + header.DevMajor = 0; + header.DevMinor = 0; + } + + /// + /// Get entries for all files present in this entries directory. + /// If this entry doesnt represent a directory zero entries are returned. + /// + /// + /// An array of TarEntry's for this entry's children. + /// + public TarEntry[] GetDirectoryEntries() + { + if ( (file == null) || !Directory.Exists(file)) { + return new TarEntry[0]; + } + + string[] list = Directory.GetFileSystemEntries(file); + TarEntry[] result = new TarEntry[list.Length]; - for (int i = 0; i < list.Length; ++i) { - result[i] = TarEntry.CreateEntryFromFile(list[i]); - } - - return result; - } - - /// - /// Write an entry's header information to a header buffer. - /// - /// - /// The tar entry header buffer to fill in. - /// - public void WriteEntryHeader(byte[] outBuffer) - { - header.WriteHeader(outBuffer); - } - - /// - /// Convenience method that will modify an entry's name directly - /// in place in an entry header buffer byte array. - /// - /// - /// The buffer containing the entry header to modify. - /// - /// - /// The new name to place into the header buffer. - /// - static public void AdjustEntryName(byte[] buffer, string newName) - { - TarHeader.GetNameBytes(newName, buffer, 0, TarHeader.NAMELEN); - } - - /// - /// Fill in a TarHeader given only the entry's name. - /// - /// - /// The TarHeader to fill in. - /// - /// - /// The tar entry name. - /// - static public void NameTarHeader(TarHeader header, string name) - { - if ( header == null ) { - throw new ArgumentNullException("header"); - } + for (int i = 0; i < list.Length; ++i) { + result[i] = TarEntry.CreateEntryFromFile(list[i]); + } + + return result; + } + + /// + /// Write an entry's header information to a header buffer. + /// + /// + /// The tar entry header buffer to fill in. + /// + public void WriteEntryHeader(byte[] outBuffer) + { + header.WriteHeader(outBuffer); + } + + /// + /// Convenience method that will modify an entry's name directly + /// in place in an entry header buffer byte array. + /// + /// + /// The buffer containing the entry header to modify. + /// + /// + /// The new name to place into the header buffer. + /// + static public void AdjustEntryName(byte[] buffer, string newName) + { + TarHeader.GetNameBytes(newName, buffer, 0, TarHeader.NAMELEN); + } + + /// + /// Fill in a TarHeader given only the entry's name. + /// + /// + /// The TarHeader to fill in. + /// + /// + /// The tar entry name. + /// + static public void NameTarHeader(TarHeader header, string name) + { + if ( header == null ) { + throw new ArgumentNullException("header"); + } - if ( name == null ) { - throw new ArgumentNullException("name"); - } + if ( name == null ) { + throw new ArgumentNullException("name"); + } - bool isDir = name.EndsWith("/"); - - header.Name = name; - header.Mode = isDir ? 1003 : 33216; - header.UserId = 0; - header.GroupId = 0; - header.Size = 0; - - header.ModTime = DateTime.UtcNow; - - header.TypeFlag = isDir ? TarHeader.LF_DIR : TarHeader.LF_NORMAL; - - header.LinkName = String.Empty; - header.UserName = String.Empty; - header.GroupName = String.Empty; - - header.DevMajor = 0; - header.DevMinor = 0; - } + bool isDir = name.EndsWith("/"); + + header.Name = name; + header.Mode = isDir ? 1003 : 33216; + header.UserId = 0; + header.GroupId = 0; + header.Size = 0; + + header.ModTime = DateTime.UtcNow; + + header.TypeFlag = isDir ? TarHeader.LF_DIR : TarHeader.LF_NORMAL; + + header.LinkName = String.Empty; + header.UserName = String.Empty; + header.GroupName = String.Empty; + + header.DevMajor = 0; + header.DevMinor = 0; + } - #region Instance Fields - /// - /// The name of the file this entry represents or null if the entry is not based on a file. - /// - string file; - - /// - /// The entry's header information. - /// - TarHeader header; - #endregion - } + #region Instance Fields + /// + /// The name of the file this entry represents or null if the entry is not based on a file. + /// + string file; + + /// + /// The entry's header information. + /// + TarHeader header; + #endregion + } } /* The original Java file had this header: - * - ** Authored by Timothy Gerard Endres - ** - ** - ** This work has been placed into the public domain. - ** You may use this work in any way and for any purpose you wish. - ** - ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, - ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR - ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY - ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR - ** REDISTRIBUTION OF THIS SOFTWARE. - ** - */ + * + ** Authored by Timothy Gerard Endres + ** + ** + ** This work has been placed into the public domain. + ** You may use this work in any way and for any purpose you wish. + ** + ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, + ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR + ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY + ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR + ** REDISTRIBUTION OF THIS SOFTWARE. + ** + */ diff --git a/External/Tools/AppMan/ZipLib/Tar/TarException.cs b/External/Tools/AppMan/ZipLib/Tar/TarException.cs index 84a6ebab4b..d485a5a3ae 100644 --- a/External/Tools/AppMan/ZipLib/Tar/TarException.cs +++ b/External/Tools/AppMan/ZipLib/Tar/TarException.cs @@ -40,52 +40,52 @@ #endif namespace ICSharpCode.SharpZipLib.Tar { - - /// - /// TarExceptions are used for exceptions specific to tar classes and code. - /// + + /// + /// TarExceptions are used for exceptions specific to tar classes and code. + /// #if !NETCF_1_0 && !NETCF_2_0 - [Serializable] + [Serializable] #endif - public class TarException : SharpZipBaseException - { + public class TarException : SharpZipBaseException + { #if !NETCF_1_0 && !NETCF_2_0 - /// - /// Deserialization constructor - /// - /// for this constructor - /// for this constructor - protected TarException(SerializationInfo info, StreamingContext context) - : base(info, context) + /// + /// Deserialization constructor + /// + /// for this constructor + /// for this constructor + protected TarException(SerializationInfo info, StreamingContext context) + : base(info, context) - { - } + { + } #endif - /// - /// Initialises a new instance of the TarException class. - /// - public TarException() - { - } - - /// - /// Initialises a new instance of the TarException class with a specified message. - /// - /// The message that describes the error. - public TarException(string message) - : base(message) - { - } + /// + /// Initialises a new instance of the TarException class. + /// + public TarException() + { + } + + /// + /// Initialises a new instance of the TarException class with a specified message. + /// + /// The message that describes the error. + public TarException(string message) + : base(message) + { + } - /// - /// - /// - /// A message describing the error. - /// The exception that is the cause of the current exception. - public TarException(string message, Exception exception) - : base(message, exception) - { - } - } + /// + /// + /// + /// A message describing the error. + /// The exception that is the cause of the current exception. + public TarException(string message, Exception exception) + : base(message, exception) + { + } + } } diff --git a/External/Tools/AppMan/ZipLib/Tar/TarHeader.cs b/External/Tools/AppMan/ZipLib/Tar/TarHeader.cs index fc49f16c09..c50efdfb14 100644 --- a/External/Tools/AppMan/ZipLib/Tar/TarHeader.cs +++ b/External/Tools/AppMan/ZipLib/Tar/TarHeader.cs @@ -45,23 +45,23 @@ This is the ustar (Posix 1003.1) header. struct header { - char t_name[100]; // 0 Filename - char t_mode[8]; // 100 Permissions - char t_uid[8]; // 108 Numerical User ID - char t_gid[8]; // 116 Numerical Group ID - char t_size[12]; // 124 Filesize - char t_mtime[12]; // 136 st_mtime - char t_chksum[8]; // 148 Checksum - char t_typeflag; // 156 Type of File - char t_linkname[100]; // 157 Target of Links - char t_magic[6]; // 257 "ustar" or other... - char t_version[2]; // 263 Version fixed to 00 - char t_uname[32]; // 265 User Name - char t_gname[32]; // 297 Group Name - char t_devmajor[8]; // 329 Major for devices - char t_devminor[8]; // 337 Minor for devices - char t_prefix[155]; // 345 Prefix for t_name - char t_mfill[12]; // 500 Filler up to 512 + char t_name[100]; // 0 Filename + char t_mode[8]; // 100 Permissions + char t_uid[8]; // 108 Numerical User ID + char t_gid[8]; // 116 Numerical Group ID + char t_size[12]; // 124 Filesize + char t_mtime[12]; // 136 st_mtime + char t_chksum[8]; // 148 Checksum + char t_typeflag; // 156 Type of File + char t_linkname[100]; // 157 Target of Links + char t_magic[6]; // 257 "ustar" or other... + char t_version[2]; // 263 Version fixed to 00 + char t_uname[32]; // 265 User Name + char t_gname[32]; // 297 Group Name + char t_devmajor[8]; // 329 Major for devices + char t_devminor[8]; // 337 Minor for devices + char t_prefix[155]; // 345 Prefix for t_name + char t_mfill[12]; // 500 Filler up to 512 }; */ @@ -71,1072 +71,1072 @@ struct header namespace ICSharpCode.SharpZipLib.Tar { - - - /// - /// This class encapsulates the Tar Entry Header used in Tar Archives. - /// The class also holds a number of tar constants, used mostly in headers. - /// - public class TarHeader : ICloneable - { - #region Constants - /// - /// The length of the name field in a header buffer. - /// - public const int NAMELEN = 100; - - /// - /// The length of the mode field in a header buffer. - /// - public const int MODELEN = 8; - - /// - /// The length of the user id field in a header buffer. - /// - public const int UIDLEN = 8; - - /// - /// The length of the group id field in a header buffer. - /// - public const int GIDLEN = 8; - - /// - /// The length of the checksum field in a header buffer. - /// - public const int CHKSUMLEN = 8; + + + /// + /// This class encapsulates the Tar Entry Header used in Tar Archives. + /// The class also holds a number of tar constants, used mostly in headers. + /// + public class TarHeader : ICloneable + { + #region Constants + /// + /// The length of the name field in a header buffer. + /// + public const int NAMELEN = 100; + + /// + /// The length of the mode field in a header buffer. + /// + public const int MODELEN = 8; + + /// + /// The length of the user id field in a header buffer. + /// + public const int UIDLEN = 8; + + /// + /// The length of the group id field in a header buffer. + /// + public const int GIDLEN = 8; + + /// + /// The length of the checksum field in a header buffer. + /// + public const int CHKSUMLEN = 8; - /// - /// Offset of checksum in a header buffer. - /// - public const int CHKSUMOFS = 148; - - /// - /// The length of the size field in a header buffer. - /// - public const int SIZELEN = 12; - - /// - /// The length of the magic field in a header buffer. - /// - public const int MAGICLEN = 6; - - /// - /// The length of the version field in a header buffer. - /// - public const int VERSIONLEN = 2; + /// + /// Offset of checksum in a header buffer. + /// + public const int CHKSUMOFS = 148; + + /// + /// The length of the size field in a header buffer. + /// + public const int SIZELEN = 12; + + /// + /// The length of the magic field in a header buffer. + /// + public const int MAGICLEN = 6; + + /// + /// The length of the version field in a header buffer. + /// + public const int VERSIONLEN = 2; - /// - /// The length of the modification time field in a header buffer. - /// - public const int MODTIMELEN = 12; - - /// - /// The length of the user name field in a header buffer. - /// - public const int UNAMELEN = 32; - - /// - /// The length of the group name field in a header buffer. - /// - public const int GNAMELEN = 32; - - /// - /// The length of the devices field in a header buffer. - /// - public const int DEVLEN = 8; - - // - // LF_ constants represent the "type" of an entry - // + /// + /// The length of the modification time field in a header buffer. + /// + public const int MODTIMELEN = 12; + + /// + /// The length of the user name field in a header buffer. + /// + public const int UNAMELEN = 32; + + /// + /// The length of the group name field in a header buffer. + /// + public const int GNAMELEN = 32; + + /// + /// The length of the devices field in a header buffer. + /// + public const int DEVLEN = 8; + + // + // LF_ constants represent the "type" of an entry + // - /// - /// The "old way" of indicating a normal file. - /// - public const byte LF_OLDNORM = 0; - - /// - /// Normal file type. - /// - public const byte LF_NORMAL = (byte) '0'; - - /// - /// Link file type. - /// - public const byte LF_LINK = (byte) '1'; - - /// - /// Symbolic link file type. - /// - public const byte LF_SYMLINK = (byte) '2'; - - /// - /// Character device file type. - /// - public const byte LF_CHR = (byte) '3'; - - /// - /// Block device file type. - /// - public const byte LF_BLK = (byte) '4'; - - /// - /// Directory file type. - /// - public const byte LF_DIR = (byte) '5'; - - /// - /// FIFO (pipe) file type. - /// - public const byte LF_FIFO = (byte) '6'; - - /// - /// Contiguous file type. - /// - public const byte LF_CONTIG = (byte) '7'; - - /// - /// Posix.1 2001 global extended header - /// - public const byte LF_GHDR = (byte) 'g'; - - /// - /// Posix.1 2001 extended header - /// - public const byte LF_XHDR = (byte) 'x'; - - // POSIX allows for upper case ascii type as extensions - - /// - /// Solaris access control list file type - /// - public const byte LF_ACL = (byte) 'A'; - - /// - /// GNU dir dump file type - /// This is a dir entry that contains the names of files that were in the - /// dir at the time the dump was made - /// - public const byte LF_GNU_DUMPDIR = (byte) 'D'; - - /// - /// Solaris Extended Attribute File - /// - public const byte LF_EXTATTR = (byte) 'E' ; - - /// - /// Inode (metadata only) no file content - /// - public const byte LF_META = (byte) 'I'; - - /// - /// Identifies the next file on the tape as having a long link name - /// - public const byte LF_GNU_LONGLINK = (byte) 'K'; - - /// - /// Identifies the next file on the tape as having a long name - /// - public const byte LF_GNU_LONGNAME = (byte) 'L'; - - /// - /// Continuation of a file that began on another volume - /// - public const byte LF_GNU_MULTIVOL = (byte) 'M'; - - /// - /// For storing filenames that dont fit in the main header (old GNU) - /// - public const byte LF_GNU_NAMES = (byte) 'N'; - - /// - /// GNU Sparse file - /// - public const byte LF_GNU_SPARSE = (byte) 'S'; - - /// - /// GNU Tape/volume header ignore on extraction - /// - public const byte LF_GNU_VOLHDR = (byte) 'V'; - - /// - /// The magic tag representing a POSIX tar archive. (includes trailing NULL) - /// - public const string TMAGIC = "ustar "; - - /// - /// The magic tag representing an old GNU tar archive where version is included in magic and overwrites it - /// - public const string GNU_TMAGIC = "ustar "; + /// + /// The "old way" of indicating a normal file. + /// + public const byte LF_OLDNORM = 0; + + /// + /// Normal file type. + /// + public const byte LF_NORMAL = (byte) '0'; + + /// + /// Link file type. + /// + public const byte LF_LINK = (byte) '1'; + + /// + /// Symbolic link file type. + /// + public const byte LF_SYMLINK = (byte) '2'; + + /// + /// Character device file type. + /// + public const byte LF_CHR = (byte) '3'; + + /// + /// Block device file type. + /// + public const byte LF_BLK = (byte) '4'; + + /// + /// Directory file type. + /// + public const byte LF_DIR = (byte) '5'; + + /// + /// FIFO (pipe) file type. + /// + public const byte LF_FIFO = (byte) '6'; + + /// + /// Contiguous file type. + /// + public const byte LF_CONTIG = (byte) '7'; + + /// + /// Posix.1 2001 global extended header + /// + public const byte LF_GHDR = (byte) 'g'; + + /// + /// Posix.1 2001 extended header + /// + public const byte LF_XHDR = (byte) 'x'; + + // POSIX allows for upper case ascii type as extensions + + /// + /// Solaris access control list file type + /// + public const byte LF_ACL = (byte) 'A'; + + /// + /// GNU dir dump file type + /// This is a dir entry that contains the names of files that were in the + /// dir at the time the dump was made + /// + public const byte LF_GNU_DUMPDIR = (byte) 'D'; + + /// + /// Solaris Extended Attribute File + /// + public const byte LF_EXTATTR = (byte) 'E' ; + + /// + /// Inode (metadata only) no file content + /// + public const byte LF_META = (byte) 'I'; + + /// + /// Identifies the next file on the tape as having a long link name + /// + public const byte LF_GNU_LONGLINK = (byte) 'K'; + + /// + /// Identifies the next file on the tape as having a long name + /// + public const byte LF_GNU_LONGNAME = (byte) 'L'; + + /// + /// Continuation of a file that began on another volume + /// + public const byte LF_GNU_MULTIVOL = (byte) 'M'; + + /// + /// For storing filenames that dont fit in the main header (old GNU) + /// + public const byte LF_GNU_NAMES = (byte) 'N'; + + /// + /// GNU Sparse file + /// + public const byte LF_GNU_SPARSE = (byte) 'S'; + + /// + /// GNU Tape/volume header ignore on extraction + /// + public const byte LF_GNU_VOLHDR = (byte) 'V'; + + /// + /// The magic tag representing a POSIX tar archive. (includes trailing NULL) + /// + public const string TMAGIC = "ustar "; + + /// + /// The magic tag representing an old GNU tar archive where version is included in magic and overwrites it + /// + public const string GNU_TMAGIC = "ustar "; - const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds - readonly static DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0); - #endregion + const long timeConversionFactor = 10000000L; // 1 tick == 100 nanoseconds + readonly static DateTime dateTime1970 = new DateTime(1970, 1, 1, 0, 0, 0, 0); + #endregion - #region Constructors + #region Constructors - /// - /// Initialise a default TarHeader instance - /// - public TarHeader() - { - Magic = TMAGIC; - Version = " "; - - Name = ""; - LinkName = ""; - - UserId = defaultUserId; - GroupId = defaultGroupId; - UserName = defaultUser; - GroupName = defaultGroupName; - Size = 0; - } + /// + /// Initialise a default TarHeader instance + /// + public TarHeader() + { + Magic = TMAGIC; + Version = " "; + + Name = ""; + LinkName = ""; + + UserId = defaultUserId; + GroupId = defaultGroupId; + UserName = defaultUser; + GroupName = defaultGroupName; + Size = 0; + } - #endregion + #endregion - #region Properties - /// - /// Get/set the name for this tar entry. - /// - /// Thrown when attempting to set the property to null. - public string Name - { - get { return name; } - set { - if ( value == null ) { - throw new ArgumentNullException("value"); - } - name = value; - } - } + #region Properties + /// + /// Get/set the name for this tar entry. + /// + /// Thrown when attempting to set the property to null. + public string Name + { + get { return name; } + set { + if ( value == null ) { + throw new ArgumentNullException("value"); + } + name = value; + } + } - /// - /// Get the name of this entry. - /// - /// The entry's name. - [Obsolete("Use the Name property instead", true)] - public string GetName() - { - return name; - } - - /// - /// Get/set the entry's Unix style permission mode. - /// - public int Mode - { - get { return mode; } - set { mode = value; } - } - - - /// - /// The entry's user id. - /// - /// - /// This is only directly relevant to unix systems. - /// The default is zero. - /// - public int UserId - { - get { return userId; } - set { userId = value; } - } - - - /// - /// Get/set the entry's group id. - /// - /// - /// This is only directly relevant to linux/unix systems. - /// The default value is zero. - /// - public int GroupId - { - get { return groupId; } - set { groupId = value; } - } - + /// + /// Get the name of this entry. + /// + /// The entry's name. + [Obsolete("Use the Name property instead", true)] + public string GetName() + { + return name; + } + + /// + /// Get/set the entry's Unix style permission mode. + /// + public int Mode + { + get { return mode; } + set { mode = value; } + } + + + /// + /// The entry's user id. + /// + /// + /// This is only directly relevant to unix systems. + /// The default is zero. + /// + public int UserId + { + get { return userId; } + set { userId = value; } + } + + + /// + /// Get/set the entry's group id. + /// + /// + /// This is only directly relevant to linux/unix systems. + /// The default value is zero. + /// + public int GroupId + { + get { return groupId; } + set { groupId = value; } + } + - /// - /// Get/set the entry's size. - /// - /// Thrown when setting the size to less than zero. - public long Size - { - get { return size; } - set { - if ( value < 0 ) { + /// + /// Get/set the entry's size. + /// + /// Thrown when setting the size to less than zero. + public long Size + { + get { return size; } + set { + if ( value < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException("value"); #else - throw new ArgumentOutOfRangeException("value", "Cannot be less than zero"); -#endif - } - size = value; - } - } - - - /// - /// Get/set the entry's modification time. - /// - /// - /// The modification time is only accurate to within a second. - /// - /// Thrown when setting the date time to less than 1/1/1970. - public DateTime ModTime - { - get { return modTime; } - set { - if ( value < dateTime1970 ) - { + throw new ArgumentOutOfRangeException("value", "Cannot be less than zero"); +#endif + } + size = value; + } + } + + + /// + /// Get/set the entry's modification time. + /// + /// + /// The modification time is only accurate to within a second. + /// + /// Thrown when setting the date time to less than 1/1/1970. + public DateTime ModTime + { + get { return modTime; } + set { + if ( value < dateTime1970 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException("value"); #else - throw new ArgumentOutOfRangeException("value", "ModTime cannot be before Jan 1st 1970"); -#endif - } - modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second); - } - } - - - /// - /// Get the entry's checksum. This is only valid/updated after writing or reading an entry. - /// - public int Checksum - { - get { return checksum; } - } - - - /// - /// Get value of true if the header checksum is valid, false otherwise. - /// - public bool IsChecksumValid - { - get { return isChecksumValid; } - } - - - /// - /// Get/set the entry's type flag. - /// - public byte TypeFlag - { - get { return typeFlag; } - set { typeFlag = value; } - } + throw new ArgumentOutOfRangeException("value", "ModTime cannot be before Jan 1st 1970"); +#endif + } + modTime = new DateTime(value.Year, value.Month, value.Day, value.Hour, value.Minute, value.Second); + } + } + + + /// + /// Get the entry's checksum. This is only valid/updated after writing or reading an entry. + /// + public int Checksum + { + get { return checksum; } + } + + + /// + /// Get value of true if the header checksum is valid, false otherwise. + /// + public bool IsChecksumValid + { + get { return isChecksumValid; } + } + + + /// + /// Get/set the entry's type flag. + /// + public byte TypeFlag + { + get { return typeFlag; } + set { typeFlag = value; } + } - - /// - /// The entry's link name. - /// - /// Thrown when attempting to set LinkName to null. - public string LinkName - { - get { return linkName; } - set { - if ( value == null ) { - throw new ArgumentNullException("value"); - } - linkName = value; - } - } - - - /// - /// Get/set the entry's magic tag. - /// - /// Thrown when attempting to set Magic to null. - public string Magic - { - get { return magic; } - set { - if ( value == null ) { - throw new ArgumentNullException("value"); - } - magic = value; - } - } - - - /// - /// The entry's version. - /// - /// Thrown when attempting to set Version to null. - public string Version - { - get { - return version; - } + + /// + /// The entry's link name. + /// + /// Thrown when attempting to set LinkName to null. + public string LinkName + { + get { return linkName; } + set { + if ( value == null ) { + throw new ArgumentNullException("value"); + } + linkName = value; + } + } + + + /// + /// Get/set the entry's magic tag. + /// + /// Thrown when attempting to set Magic to null. + public string Magic + { + get { return magic; } + set { + if ( value == null ) { + throw new ArgumentNullException("value"); + } + magic = value; + } + } + + + /// + /// The entry's version. + /// + /// Thrown when attempting to set Version to null. + public string Version + { + get { + return version; + } - set { - if ( value == null ) { - throw new ArgumentNullException("value"); - } - version = value; - } - } - - - /// - /// The entry's user name. - /// - public string UserName - { - get { return userName; } - set { - if (value != null) { - userName = value.Substring(0, Math.Min(UNAMELEN, value.Length)); - } - else { + set { + if ( value == null ) { + throw new ArgumentNullException("value"); + } + version = value; + } + } + + + /// + /// The entry's user name. + /// + public string UserName + { + get { return userName; } + set { + if (value != null) { + userName = value.Substring(0, Math.Min(UNAMELEN, value.Length)); + } + else { #if NETCF_1_0 || NETCF_2_0 - string currentUser = "PocketPC"; + string currentUser = "PocketPC"; #else - string currentUser = Environment.UserName; + string currentUser = Environment.UserName; #endif - if (currentUser.Length > UNAMELEN) { - currentUser = currentUser.Substring(0, UNAMELEN); - } - userName = currentUser; - } - } - } - - - /// - /// Get/set the entry's group name. - /// - /// - /// This is only directly relevant to unix systems. - /// - public string GroupName - { - get { return groupName; } - set { - if ( value == null ) { - groupName = "None"; - } - else { - groupName = value; - } - } - } - - - /// - /// Get/set the entry's major device number. - /// - public int DevMajor - { - get { return devMajor; } - set { devMajor = value; } - } - - - /// - /// Get/set the entry's minor device number. - /// - public int DevMinor - { - get { return devMinor; } - set { devMinor = value; } - } - - #endregion + if (currentUser.Length > UNAMELEN) { + currentUser = currentUser.Substring(0, UNAMELEN); + } + userName = currentUser; + } + } + } + + + /// + /// Get/set the entry's group name. + /// + /// + /// This is only directly relevant to unix systems. + /// + public string GroupName + { + get { return groupName; } + set { + if ( value == null ) { + groupName = "None"; + } + else { + groupName = value; + } + } + } + + + /// + /// Get/set the entry's major device number. + /// + public int DevMajor + { + get { return devMajor; } + set { devMajor = value; } + } + + + /// + /// Get/set the entry's minor device number. + /// + public int DevMinor + { + get { return devMinor; } + set { devMinor = value; } + } + + #endregion - #region ICloneable Members - /// - /// Create a new that is a copy of the current instance. - /// - /// A new that is a copy of the current instance. - public object Clone() - { - return MemberwiseClone(); - } - #endregion + #region ICloneable Members + /// + /// Create a new that is a copy of the current instance. + /// + /// A new that is a copy of the current instance. + public object Clone() + { + return MemberwiseClone(); + } + #endregion - /// - /// Parse TarHeader information from a header buffer. - /// - /// - /// The tar entry header buffer to get information from. - /// - public void ParseBuffer(byte[] header) - { - if ( header == null ) - { - throw new ArgumentNullException("header"); - } + /// + /// Parse TarHeader information from a header buffer. + /// + /// + /// The tar entry header buffer to get information from. + /// + public void ParseBuffer(byte[] header) + { + if ( header == null ) + { + throw new ArgumentNullException("header"); + } - int offset = 0; - - name = TarHeader.ParseName(header, offset, TarHeader.NAMELEN).ToString(); - offset += TarHeader.NAMELEN; - - mode = (int)TarHeader.ParseOctal(header, offset, TarHeader.MODELEN); - offset += TarHeader.MODELEN; - - UserId = (int)TarHeader.ParseOctal(header, offset, TarHeader.UIDLEN); - offset += TarHeader.UIDLEN; - - GroupId = (int)TarHeader.ParseOctal(header, offset, TarHeader.GIDLEN); - offset += TarHeader.GIDLEN; - - Size = TarHeader.ParseOctal(header, offset, TarHeader.SIZELEN); - offset += TarHeader.SIZELEN; - - ModTime = GetDateTimeFromCTime(TarHeader.ParseOctal(header, offset, TarHeader.MODTIMELEN)); - offset += TarHeader.MODTIMELEN; - - checksum = (int)TarHeader.ParseOctal(header, offset, TarHeader.CHKSUMLEN); - offset += TarHeader.CHKSUMLEN; - - TypeFlag = header[ offset++ ]; + int offset = 0; + + name = TarHeader.ParseName(header, offset, TarHeader.NAMELEN).ToString(); + offset += TarHeader.NAMELEN; + + mode = (int)TarHeader.ParseOctal(header, offset, TarHeader.MODELEN); + offset += TarHeader.MODELEN; + + UserId = (int)TarHeader.ParseOctal(header, offset, TarHeader.UIDLEN); + offset += TarHeader.UIDLEN; + + GroupId = (int)TarHeader.ParseOctal(header, offset, TarHeader.GIDLEN); + offset += TarHeader.GIDLEN; + + Size = TarHeader.ParseOctal(header, offset, TarHeader.SIZELEN); + offset += TarHeader.SIZELEN; + + ModTime = GetDateTimeFromCTime(TarHeader.ParseOctal(header, offset, TarHeader.MODTIMELEN)); + offset += TarHeader.MODTIMELEN; + + checksum = (int)TarHeader.ParseOctal(header, offset, TarHeader.CHKSUMLEN); + offset += TarHeader.CHKSUMLEN; + + TypeFlag = header[ offset++ ]; - LinkName = TarHeader.ParseName(header, offset, TarHeader.NAMELEN).ToString(); - offset += TarHeader.NAMELEN; - - Magic = TarHeader.ParseName(header, offset, TarHeader.MAGICLEN).ToString(); - offset += TarHeader.MAGICLEN; - - Version = TarHeader.ParseName(header, offset, TarHeader.VERSIONLEN).ToString(); - offset += TarHeader.VERSIONLEN; - - UserName = TarHeader.ParseName(header, offset, TarHeader.UNAMELEN).ToString(); - offset += TarHeader.UNAMELEN; - - GroupName = TarHeader.ParseName(header, offset, TarHeader.GNAMELEN).ToString(); - offset += TarHeader.GNAMELEN; - - DevMajor = (int)TarHeader.ParseOctal(header, offset, TarHeader.DEVLEN); - offset += TarHeader.DEVLEN; - - DevMinor = (int)TarHeader.ParseOctal(header, offset, TarHeader.DEVLEN); - - // Fields past this point not currently parsed or used... - - isChecksumValid = Checksum == TarHeader.MakeCheckSum(header); - } + LinkName = TarHeader.ParseName(header, offset, TarHeader.NAMELEN).ToString(); + offset += TarHeader.NAMELEN; + + Magic = TarHeader.ParseName(header, offset, TarHeader.MAGICLEN).ToString(); + offset += TarHeader.MAGICLEN; + + Version = TarHeader.ParseName(header, offset, TarHeader.VERSIONLEN).ToString(); + offset += TarHeader.VERSIONLEN; + + UserName = TarHeader.ParseName(header, offset, TarHeader.UNAMELEN).ToString(); + offset += TarHeader.UNAMELEN; + + GroupName = TarHeader.ParseName(header, offset, TarHeader.GNAMELEN).ToString(); + offset += TarHeader.GNAMELEN; + + DevMajor = (int)TarHeader.ParseOctal(header, offset, TarHeader.DEVLEN); + offset += TarHeader.DEVLEN; + + DevMinor = (int)TarHeader.ParseOctal(header, offset, TarHeader.DEVLEN); + + // Fields past this point not currently parsed or used... + + isChecksumValid = Checksum == TarHeader.MakeCheckSum(header); + } - /// - /// 'Write' header information to buffer provided, updating the check sum. - /// - /// output buffer for header information - public void WriteHeader(byte[] outBuffer) - { - if ( outBuffer == null ) - { - throw new ArgumentNullException("outBuffer"); - } + /// + /// 'Write' header information to buffer provided, updating the check sum. + /// + /// output buffer for header information + public void WriteHeader(byte[] outBuffer) + { + if ( outBuffer == null ) + { + throw new ArgumentNullException("outBuffer"); + } - int offset = 0; - - offset = GetNameBytes(Name, outBuffer, offset, NAMELEN); - offset = GetOctalBytes(mode, outBuffer, offset, MODELEN); - offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN); - offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN); - - offset = GetLongOctalBytes(Size, outBuffer, offset, SIZELEN); - offset = GetLongOctalBytes(GetCTime(ModTime), outBuffer, offset, MODTIMELEN); - - int csOffset = offset; - for (int c = 0; c < CHKSUMLEN; ++c) - { - outBuffer[offset++] = (byte)' '; - } - - outBuffer[offset++] = TypeFlag; - - offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN); - offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN); - offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN); - offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN); - offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN); - - if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK)) - { - offset = GetOctalBytes(DevMajor, outBuffer, offset, DEVLEN); - offset = GetOctalBytes(DevMinor, outBuffer, offset, DEVLEN); - } - - for ( ; offset < outBuffer.Length; ) - { - outBuffer[offset++] = 0; - } - - checksum = ComputeCheckSum(outBuffer); - - GetCheckSumOctalBytes(checksum, outBuffer, csOffset, CHKSUMLEN); - isChecksumValid = true; - } + int offset = 0; + + offset = GetNameBytes(Name, outBuffer, offset, NAMELEN); + offset = GetOctalBytes(mode, outBuffer, offset, MODELEN); + offset = GetOctalBytes(UserId, outBuffer, offset, UIDLEN); + offset = GetOctalBytes(GroupId, outBuffer, offset, GIDLEN); + + offset = GetLongOctalBytes(Size, outBuffer, offset, SIZELEN); + offset = GetLongOctalBytes(GetCTime(ModTime), outBuffer, offset, MODTIMELEN); + + int csOffset = offset; + for (int c = 0; c < CHKSUMLEN; ++c) + { + outBuffer[offset++] = (byte)' '; + } + + outBuffer[offset++] = TypeFlag; + + offset = GetNameBytes(LinkName, outBuffer, offset, NAMELEN); + offset = GetAsciiBytes(Magic, 0, outBuffer, offset, MAGICLEN); + offset = GetNameBytes(Version, outBuffer, offset, VERSIONLEN); + offset = GetNameBytes(UserName, outBuffer, offset, UNAMELEN); + offset = GetNameBytes(GroupName, outBuffer, offset, GNAMELEN); + + if ((TypeFlag == LF_CHR) || (TypeFlag == LF_BLK)) + { + offset = GetOctalBytes(DevMajor, outBuffer, offset, DEVLEN); + offset = GetOctalBytes(DevMinor, outBuffer, offset, DEVLEN); + } + + for ( ; offset < outBuffer.Length; ) + { + outBuffer[offset++] = 0; + } + + checksum = ComputeCheckSum(outBuffer); + + GetCheckSumOctalBytes(checksum, outBuffer, csOffset, CHKSUMLEN); + isChecksumValid = true; + } - /// - /// Get a hash code for the current object. - /// - /// A hash code for the current object. - public override int GetHashCode() - { - return Name.GetHashCode(); - } - - /// - /// Determines if this instance is equal to the specified object. - /// - /// The object to compare with. - /// true if the objects are equal, false otherwise. - public override bool Equals(object obj) - { - TarHeader localHeader = obj as TarHeader; + /// + /// Get a hash code for the current object. + /// + /// A hash code for the current object. + public override int GetHashCode() + { + return Name.GetHashCode(); + } + + /// + /// Determines if this instance is equal to the specified object. + /// + /// The object to compare with. + /// true if the objects are equal, false otherwise. + public override bool Equals(object obj) + { + TarHeader localHeader = obj as TarHeader; - bool result; - if ( localHeader != null ) - { - result = (name == localHeader.name) - && (mode == localHeader.mode) - && (UserId == localHeader.UserId) - && (GroupId == localHeader.GroupId) - && (Size == localHeader.Size) - && (ModTime == localHeader.ModTime) - && (Checksum == localHeader.Checksum) - && (TypeFlag == localHeader.TypeFlag) - && (LinkName == localHeader.LinkName) - && (Magic == localHeader.Magic) - && (Version == localHeader.Version) - && (UserName == localHeader.UserName) - && (GroupName == localHeader.GroupName) - && (DevMajor == localHeader.DevMajor) - && (DevMinor == localHeader.DevMinor); - } - else - { - result = false; - } - return result; - } - - /// - /// Set defaults for values used when constructing a TarHeader instance. - /// - /// Value to apply as a default for userId. - /// Value to apply as a default for userName. - /// Value to apply as a default for groupId. - /// Value to apply as a default for groupName. - static internal void SetValueDefaults(int userId, string userName, int groupId, string groupName) - { - defaultUserId = userIdAsSet = userId; - defaultUser = userNameAsSet = userName; - defaultGroupId = groupIdAsSet = groupId; - defaultGroupName = groupNameAsSet = groupName; - } + bool result; + if ( localHeader != null ) + { + result = (name == localHeader.name) + && (mode == localHeader.mode) + && (UserId == localHeader.UserId) + && (GroupId == localHeader.GroupId) + && (Size == localHeader.Size) + && (ModTime == localHeader.ModTime) + && (Checksum == localHeader.Checksum) + && (TypeFlag == localHeader.TypeFlag) + && (LinkName == localHeader.LinkName) + && (Magic == localHeader.Magic) + && (Version == localHeader.Version) + && (UserName == localHeader.UserName) + && (GroupName == localHeader.GroupName) + && (DevMajor == localHeader.DevMajor) + && (DevMinor == localHeader.DevMinor); + } + else + { + result = false; + } + return result; + } + + /// + /// Set defaults for values used when constructing a TarHeader instance. + /// + /// Value to apply as a default for userId. + /// Value to apply as a default for userName. + /// Value to apply as a default for groupId. + /// Value to apply as a default for groupName. + static internal void SetValueDefaults(int userId, string userName, int groupId, string groupName) + { + defaultUserId = userIdAsSet = userId; + defaultUser = userNameAsSet = userName; + defaultGroupId = groupIdAsSet = groupId; + defaultGroupName = groupNameAsSet = groupName; + } - static internal void RestoreSetValues() - { - defaultUserId = userIdAsSet; - defaultUser = userNameAsSet; - defaultGroupId = groupIdAsSet; - defaultGroupName = groupNameAsSet; - } + static internal void RestoreSetValues() + { + defaultUserId = userIdAsSet; + defaultUser = userNameAsSet; + defaultGroupId = groupIdAsSet; + defaultGroupName = groupNameAsSet; + } - /// - /// Parse an octal string from a header buffer. - /// - /// The header buffer from which to parse. - /// The offset into the buffer from which to parse. - /// The number of header bytes to parse. - /// The long equivalent of the octal string. - static public long ParseOctal(byte[] header, int offset, int length) - { - if ( header == null ) { - throw new ArgumentNullException("header"); - } + /// + /// Parse an octal string from a header buffer. + /// + /// The header buffer from which to parse. + /// The offset into the buffer from which to parse. + /// The number of header bytes to parse. + /// The long equivalent of the octal string. + static public long ParseOctal(byte[] header, int offset, int length) + { + if ( header == null ) { + throw new ArgumentNullException("header"); + } - long result = 0; - bool stillPadding = true; - - int end = offset + length; - for (int i = offset; i < end ; ++i) { - if (header[i] == 0) { - break; - } - - if (header[i] == (byte)' ' || header[i] == '0') { - if (stillPadding) { - continue; - } - - if (header[i] == (byte)' ') { - break; - } - } - - stillPadding = false; - - result = (result << 3) + (header[i] - '0'); - } - - return result; - } - - /// - /// Parse a name from a header buffer. - /// - /// - /// The header buffer from which to parse. - /// - /// - /// The offset into the buffer from which to parse. - /// - /// - /// The number of header bytes to parse. - /// - /// - /// The name parsed. - /// - static public StringBuilder ParseName(byte[] header, int offset, int length) - { - if ( header == null ) { - throw new ArgumentNullException("header"); - } + long result = 0; + bool stillPadding = true; + + int end = offset + length; + for (int i = offset; i < end ; ++i) { + if (header[i] == 0) { + break; + } + + if (header[i] == (byte)' ' || header[i] == '0') { + if (stillPadding) { + continue; + } + + if (header[i] == (byte)' ') { + break; + } + } + + stillPadding = false; + + result = (result << 3) + (header[i] - '0'); + } + + return result; + } + + /// + /// Parse a name from a header buffer. + /// + /// + /// The header buffer from which to parse. + /// + /// + /// The offset into the buffer from which to parse. + /// + /// + /// The number of header bytes to parse. + /// + /// + /// The name parsed. + /// + static public StringBuilder ParseName(byte[] header, int offset, int length) + { + if ( header == null ) { + throw new ArgumentNullException("header"); + } - if ( offset < 0 ) { + if ( offset < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "Cannot be less than zero"); -#endif - } + throw new ArgumentOutOfRangeException("offset", "Cannot be less than zero"); +#endif + } - if ( length < 0 ) - { + if ( length < 0 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("length"); + throw new ArgumentOutOfRangeException("length"); #else - throw new ArgumentOutOfRangeException("length", "Cannot be less than zero"); -#endif - } + throw new ArgumentOutOfRangeException("length", "Cannot be less than zero"); +#endif + } - if ( offset + length > header.Length ) - { - throw new ArgumentException("Exceeds header size", "length"); - } + if ( offset + length > header.Length ) + { + throw new ArgumentException("Exceeds header size", "length"); + } - StringBuilder result = new StringBuilder(length); - - for (int i = offset; i < offset + length; ++i) { - if (header[i] == 0) { - break; - } - result.Append((char)header[i]); - } - - return result; - } - - /// - /// Add name to the buffer as a collection of bytes - /// - /// The name to add - /// The offset of the first character - /// The buffer to add to - /// The index of the first byte to add - /// The number of characters/bytes to add - /// The next free index in the - public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length) - { - if ( name == null ) { - throw new ArgumentNullException("name"); - } + StringBuilder result = new StringBuilder(length); + + for (int i = offset; i < offset + length; ++i) { + if (header[i] == 0) { + break; + } + result.Append((char)header[i]); + } + + return result; + } + + /// + /// Add name to the buffer as a collection of bytes + /// + /// The name to add + /// The offset of the first character + /// The buffer to add to + /// The index of the first byte to add + /// The number of characters/bytes to add + /// The next free index in the + public static int GetNameBytes(StringBuilder name, int nameOffset, byte[] buffer, int bufferOffset, int length) + { + if ( name == null ) { + throw new ArgumentNullException("name"); + } - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } - return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length); - } - - /// - /// Add name to the buffer as a collection of bytes - /// - /// The name to add - /// The offset of the first character - /// The buffer to add to - /// The index of the first byte to add - /// The number of characters/bytes to add - /// The next free index in the - public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length) - { - if ( name == null ) - { - throw new ArgumentNullException("name"); - } + return GetNameBytes(name.ToString(), nameOffset, buffer, bufferOffset, length); + } + + /// + /// Add name to the buffer as a collection of bytes + /// + /// The name to add + /// The offset of the first character + /// The buffer to add to + /// The index of the first byte to add + /// The number of characters/bytes to add + /// The next free index in the + public static int GetNameBytes(string name, int nameOffset, byte[] buffer, int bufferOffset, int length) + { + if ( name == null ) + { + throw new ArgumentNullException("name"); + } - if ( buffer == null ) - { - throw new ArgumentNullException("buffer"); - } + if ( buffer == null ) + { + throw new ArgumentNullException("buffer"); + } - int i; - - for (i = 0 ; i < length - 1 && nameOffset + i < name.Length; ++i) { - buffer[bufferOffset + i] = (byte)name[nameOffset + i]; - } - - for (; i < length ; ++i) { - buffer[bufferOffset + i] = 0; - } - - return bufferOffset + length; - } + int i; + + for (i = 0 ; i < length - 1 && nameOffset + i < name.Length; ++i) { + buffer[bufferOffset + i] = (byte)name[nameOffset + i]; + } + + for (; i < length ; ++i) { + buffer[bufferOffset + i] = 0; + } + + return bufferOffset + length; + } - /// - /// Add an entry name to the buffer - /// - /// - /// The name to add - /// - /// - /// The buffer to add to - /// - /// - /// The offset into the buffer from which to start adding - /// - /// - /// The number of header bytes to add - /// - /// - /// The index of the next free byte in the buffer - /// - public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length) - { + /// + /// Add an entry name to the buffer + /// + /// + /// The name to add + /// + /// + /// The buffer to add to + /// + /// + /// The offset into the buffer from which to start adding + /// + /// + /// The number of header bytes to add + /// + /// + /// The index of the next free byte in the buffer + /// + public static int GetNameBytes(StringBuilder name, byte[] buffer, int offset, int length) + { - if ( name == null ) { - throw new ArgumentNullException("name"); - } + if ( name == null ) { + throw new ArgumentNullException("name"); + } - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } - return GetNameBytes(name.ToString(), 0, buffer, offset, length); - } - - /// - /// Add an entry name to the buffer - /// - /// The name to add - /// The buffer to add to - /// The offset into the buffer from which to start adding - /// The number of header bytes to add - /// The index of the next free byte in the buffer - public static int GetNameBytes(string name, byte[] buffer, int offset, int length) - { + return GetNameBytes(name.ToString(), 0, buffer, offset, length); + } + + /// + /// Add an entry name to the buffer + /// + /// The name to add + /// The buffer to add to + /// The offset into the buffer from which to start adding + /// The number of header bytes to add + /// The index of the next free byte in the buffer + public static int GetNameBytes(string name, byte[] buffer, int offset, int length) + { - if ( name == null ) { - throw new ArgumentNullException("name"); - } + if ( name == null ) { + throw new ArgumentNullException("name"); + } - if ( buffer == null ) - { - throw new ArgumentNullException("buffer"); - } + if ( buffer == null ) + { + throw new ArgumentNullException("buffer"); + } - return GetNameBytes(name, 0, buffer, offset, length); - } - - /// - /// Add a string to a buffer as a collection of ascii bytes. - /// - /// The string to add - /// The offset of the first character to add. - /// The buffer to add to. - /// The offset to start adding at. - /// The number of ascii characters to add. - /// The next free index in the buffer. - public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length ) - { - if ( toAdd == null ) { - throw new ArgumentNullException("toAdd"); - } + return GetNameBytes(name, 0, buffer, offset, length); + } + + /// + /// Add a string to a buffer as a collection of ascii bytes. + /// + /// The string to add + /// The offset of the first character to add. + /// The buffer to add to. + /// The offset to start adding at. + /// The number of ascii characters to add. + /// The next free index in the buffer. + public static int GetAsciiBytes(string toAdd, int nameOffset, byte[] buffer, int bufferOffset, int length ) + { + if ( toAdd == null ) { + throw new ArgumentNullException("toAdd"); + } - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } - for (int i = 0 ; i < length && nameOffset + i < toAdd.Length; ++i) - { - buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i]; - } - return bufferOffset + length; - } + for (int i = 0 ; i < length && nameOffset + i < toAdd.Length; ++i) + { + buffer[bufferOffset + i] = (byte)toAdd[nameOffset + i]; + } + return bufferOffset + length; + } - /// - /// Put an octal representation of a value into a buffer - /// - /// - /// the value to be converted to octal - /// - /// - /// buffer to store the octal string - /// - /// - /// The offset into the buffer where the value starts - /// - /// - /// The length of the octal string to create - /// - /// - /// The offset of the character next byte after the octal string - /// - public static int GetOctalBytes(long value, byte[] buffer, int offset, int length) - { - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } + /// + /// Put an octal representation of a value into a buffer + /// + /// + /// the value to be converted to octal + /// + /// + /// buffer to store the octal string + /// + /// + /// The offset into the buffer where the value starts + /// + /// + /// The length of the octal string to create + /// + /// + /// The offset of the character next byte after the octal string + /// + public static int GetOctalBytes(long value, byte[] buffer, int offset, int length) + { + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } - int localIndex = length - 1; + int localIndex = length - 1; - // Either a space or null is valid here. We use NULL as per GNUTar - buffer[offset + localIndex] = 0; - --localIndex; + // Either a space or null is valid here. We use NULL as per GNUTar + buffer[offset + localIndex] = 0; + --localIndex; - if (value > 0) { - for ( long v = value; (localIndex >= 0) && (v > 0); --localIndex ) { - buffer[offset + localIndex] = (byte)((byte)'0' + (byte)(v & 7)); - v >>= 3; - } - } - - for ( ; localIndex >= 0; --localIndex ) { - buffer[offset + localIndex] = (byte)'0'; - } - - return offset + length; - } - - /// - /// Put an octal representation of a value into a buffer - /// - /// Value to be convert to octal - /// The buffer to update - /// The offset into the buffer to store the value - /// The length of the octal string - /// Index of next byte - public static int GetLongOctalBytes(long value, byte[] buffer, int offset, int length) - { - return GetOctalBytes(value, buffer, offset, length); - } - - /// - /// Add the checksum integer to header buffer. - /// - /// - /// The header buffer to set the checksum for - /// The offset into the buffer for the checksum - /// The number of header bytes to update. - /// It's formatted differently from the other fields: it has 6 digits, a - /// null, then a space -- rather than digits, a space, then a null. - /// The final space is already there, from checksumming - /// - /// The modified buffer offset - static int GetCheckSumOctalBytes(long value, byte[] buffer, int offset, int length) - { - TarHeader.GetOctalBytes(value, buffer, offset, length - 1); - return offset + length; - } - - /// - /// Compute the checksum for a tar entry header. - /// The checksum field must be all spaces prior to this happening - /// - /// The tar entry's header buffer. - /// The computed checksum. - static int ComputeCheckSum(byte[] buffer) - { - int sum = 0; - for (int i = 0; i < buffer.Length; ++i) { - sum += buffer[i]; - } - return sum; - } - - /// - /// Make a checksum for a tar entry ignoring the checksum contents. - /// - /// The tar entry's header buffer. - /// The checksum for the buffer - static int MakeCheckSum(byte[] buffer) - { - int sum = 0; - for ( int i = 0; i < CHKSUMOFS; ++i ) - { - sum += buffer[i]; - } - - for ( int i = 0; i < TarHeader.CHKSUMLEN; ++i) - { - sum += (byte)' '; - } - - for (int i = CHKSUMOFS + CHKSUMLEN; i < buffer.Length; ++i) - { - sum += buffer[i]; - } - return sum; - } - - static int GetCTime(System.DateTime dateTime) - { - return unchecked((int)((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor)); - } - - static DateTime GetDateTimeFromCTime(long ticks) - { - DateTime result; - - try { - result = new DateTime(dateTime1970.Ticks + ticks * timeConversionFactor); - } - catch(ArgumentOutOfRangeException) { - result = dateTime1970; - } - return result; - } + if (value > 0) { + for ( long v = value; (localIndex >= 0) && (v > 0); --localIndex ) { + buffer[offset + localIndex] = (byte)((byte)'0' + (byte)(v & 7)); + v >>= 3; + } + } + + for ( ; localIndex >= 0; --localIndex ) { + buffer[offset + localIndex] = (byte)'0'; + } + + return offset + length; + } + + /// + /// Put an octal representation of a value into a buffer + /// + /// Value to be convert to octal + /// The buffer to update + /// The offset into the buffer to store the value + /// The length of the octal string + /// Index of next byte + public static int GetLongOctalBytes(long value, byte[] buffer, int offset, int length) + { + return GetOctalBytes(value, buffer, offset, length); + } + + /// + /// Add the checksum integer to header buffer. + /// + /// + /// The header buffer to set the checksum for + /// The offset into the buffer for the checksum + /// The number of header bytes to update. + /// It's formatted differently from the other fields: it has 6 digits, a + /// null, then a space -- rather than digits, a space, then a null. + /// The final space is already there, from checksumming + /// + /// The modified buffer offset + static int GetCheckSumOctalBytes(long value, byte[] buffer, int offset, int length) + { + TarHeader.GetOctalBytes(value, buffer, offset, length - 1); + return offset + length; + } + + /// + /// Compute the checksum for a tar entry header. + /// The checksum field must be all spaces prior to this happening + /// + /// The tar entry's header buffer. + /// The computed checksum. + static int ComputeCheckSum(byte[] buffer) + { + int sum = 0; + for (int i = 0; i < buffer.Length; ++i) { + sum += buffer[i]; + } + return sum; + } + + /// + /// Make a checksum for a tar entry ignoring the checksum contents. + /// + /// The tar entry's header buffer. + /// The checksum for the buffer + static int MakeCheckSum(byte[] buffer) + { + int sum = 0; + for ( int i = 0; i < CHKSUMOFS; ++i ) + { + sum += buffer[i]; + } + + for ( int i = 0; i < TarHeader.CHKSUMLEN; ++i) + { + sum += (byte)' '; + } + + for (int i = CHKSUMOFS + CHKSUMLEN; i < buffer.Length; ++i) + { + sum += buffer[i]; + } + return sum; + } + + static int GetCTime(System.DateTime dateTime) + { + return unchecked((int)((dateTime.Ticks - dateTime1970.Ticks) / timeConversionFactor)); + } + + static DateTime GetDateTimeFromCTime(long ticks) + { + DateTime result; + + try { + result = new DateTime(dateTime1970.Ticks + ticks * timeConversionFactor); + } + catch(ArgumentOutOfRangeException) { + result = dateTime1970; + } + return result; + } - #region Instance Fields - string name; - int mode; - int userId; - int groupId; - long size; - DateTime modTime; - int checksum; - bool isChecksumValid; - byte typeFlag; - string linkName; - string magic; - string version; - string userName; - string groupName; - int devMajor; - int devMinor; - #endregion + #region Instance Fields + string name; + int mode; + int userId; + int groupId; + long size; + DateTime modTime; + int checksum; + bool isChecksumValid; + byte typeFlag; + string linkName; + string magic; + string version; + string userName; + string groupName; + int devMajor; + int devMinor; + #endregion - #region Class Fields - // Values used during recursive operations. - static internal int userIdAsSet; - static internal int groupIdAsSet; - static internal string userNameAsSet; - static internal string groupNameAsSet = "None"; - - static internal int defaultUserId; - static internal int defaultGroupId; - static internal string defaultGroupName = "None"; - static internal string defaultUser; - #endregion - } + #region Class Fields + // Values used during recursive operations. + static internal int userIdAsSet; + static internal int groupIdAsSet; + static internal string userNameAsSet; + static internal string groupNameAsSet = "None"; + + static internal int defaultUserId; + static internal int defaultGroupId; + static internal string defaultGroupName = "None"; + static internal string defaultUser; + #endregion + } } /* The original Java file had this header: diff --git a/External/Tools/AppMan/ZipLib/Tar/TarInputStream.cs b/External/Tools/AppMan/ZipLib/Tar/TarInputStream.cs index 436b0027aa..e23fe1ea7a 100644 --- a/External/Tools/AppMan/ZipLib/Tar/TarInputStream.cs +++ b/External/Tools/AppMan/ZipLib/Tar/TarInputStream.cs @@ -39,37 +39,37 @@ namespace ICSharpCode.SharpZipLib.Tar { - - /// - /// The TarInputStream reads a UNIX tar archive as an InputStream. - /// methods are provided to position at each successive entry in - /// the archive, and the read each entry as a normal input stream - /// using read(). - /// - public class TarInputStream : Stream - { - #region Constructors - /// - /// Construct a TarInputStream with default block factor - /// - /// stream to source data from - public TarInputStream(Stream inputStream) - : this(inputStream, TarBuffer.DefaultBlockFactor) - { - } + + /// + /// The TarInputStream reads a UNIX tar archive as an InputStream. + /// methods are provided to position at each successive entry in + /// the archive, and the read each entry as a normal input stream + /// using read(). + /// + public class TarInputStream : Stream + { + #region Constructors + /// + /// Construct a TarInputStream with default block factor + /// + /// stream to source data from + public TarInputStream(Stream inputStream) + : this(inputStream, TarBuffer.DefaultBlockFactor) + { + } - /// - /// Construct a TarInputStream with user specified block factor - /// - /// stream to source data from - /// block factor to apply to archive - public TarInputStream(Stream inputStream, int blockFactor) - { - this.inputStream = inputStream; - tarBuffer = TarBuffer.CreateInputTarBuffer(inputStream, blockFactor); - } + /// + /// Construct a TarInputStream with user specified block factor + /// + /// stream to source data from + /// block factor to apply to archive + public TarInputStream(Stream inputStream, int blockFactor) + { + this.inputStream = inputStream; + tarBuffer = TarBuffer.CreateInputTarBuffer(inputStream, blockFactor); + } - #endregion + #endregion /// /// Get/set flag indicating ownership of the underlying stream. @@ -81,615 +81,615 @@ public bool IsStreamOwner set { tarBuffer.IsStreamOwner = value; } } - #region Stream Overrides - /// - /// Gets a value indicating whether the current stream supports reading - /// - public override bool CanRead - { - get { - return inputStream.CanRead; - } - } - - /// - /// Gets a value indicating whether the current stream supports seeking - /// This property always returns false. - /// - public override bool CanSeek { - get { - return false; - } - } - - /// - /// Gets a value indicating if the stream supports writing. - /// This property always returns false. - /// - public override bool CanWrite { - get { - return false; - } - } - - /// - /// The length in bytes of the stream - /// - public override long Length { - get { - return inputStream.Length; - } - } - - /// - /// Gets or sets the position within the stream. - /// Setting the Position is not supported and throws a NotSupportedExceptionNotSupportedException - /// - /// Any attempt to set position - public override long Position { - get { - return inputStream.Position; - } - set { - throw new NotSupportedException("TarInputStream Seek not supported"); - } - } - - /// - /// Flushes the baseInputStream - /// - public override void Flush() - { - inputStream.Flush(); - } - - /// - /// Set the streams position. This operation is not supported and will throw a NotSupportedException - /// - /// The offset relative to the origin to seek to. - /// The to start seeking from. - /// The new position in the stream. - /// Any access - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException("TarInputStream Seek not supported"); - } - - /// - /// Sets the length of the stream - /// This operation is not supported and will throw a NotSupportedException - /// - /// The new stream length. - /// Any access - public override void SetLength(long value) - { - throw new NotSupportedException("TarInputStream SetLength not supported"); - } - - /// - /// Writes a block of bytes to this stream using data from a buffer. - /// This operation is not supported and will throw a NotSupportedException - /// - /// The buffer containing bytes to write. - /// The offset in the buffer of the frist byte to write. - /// The number of bytes to write. - /// Any access - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotSupportedException("TarInputStream Write not supported"); - } - - /// - /// Writes a byte to the current position in the file stream. - /// This operation is not supported and will throw a NotSupportedException - /// - /// The byte value to write. - /// Any access - public override void WriteByte(byte value) - { - throw new NotSupportedException("TarInputStream WriteByte not supported"); - } - /// - /// Reads a byte from the current tar archive entry. - /// - /// A byte cast to an int; -1 if the at the end of the stream. - public override int ReadByte() - { - byte[] oneByteBuffer = new byte[1]; - int num = Read(oneByteBuffer, 0, 1); - if (num <= 0) - { + #region Stream Overrides + /// + /// Gets a value indicating whether the current stream supports reading + /// + public override bool CanRead + { + get { + return inputStream.CanRead; + } + } + + /// + /// Gets a value indicating whether the current stream supports seeking + /// This property always returns false. + /// + public override bool CanSeek { + get { + return false; + } + } + + /// + /// Gets a value indicating if the stream supports writing. + /// This property always returns false. + /// + public override bool CanWrite { + get { + return false; + } + } + + /// + /// The length in bytes of the stream + /// + public override long Length { + get { + return inputStream.Length; + } + } + + /// + /// Gets or sets the position within the stream. + /// Setting the Position is not supported and throws a NotSupportedExceptionNotSupportedException + /// + /// Any attempt to set position + public override long Position { + get { + return inputStream.Position; + } + set { + throw new NotSupportedException("TarInputStream Seek not supported"); + } + } + + /// + /// Flushes the baseInputStream + /// + public override void Flush() + { + inputStream.Flush(); + } + + /// + /// Set the streams position. This operation is not supported and will throw a NotSupportedException + /// + /// The offset relative to the origin to seek to. + /// The to start seeking from. + /// The new position in the stream. + /// Any access + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException("TarInputStream Seek not supported"); + } + + /// + /// Sets the length of the stream + /// This operation is not supported and will throw a NotSupportedException + /// + /// The new stream length. + /// Any access + public override void SetLength(long value) + { + throw new NotSupportedException("TarInputStream SetLength not supported"); + } + + /// + /// Writes a block of bytes to this stream using data from a buffer. + /// This operation is not supported and will throw a NotSupportedException + /// + /// The buffer containing bytes to write. + /// The offset in the buffer of the frist byte to write. + /// The number of bytes to write. + /// Any access + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException("TarInputStream Write not supported"); + } + + /// + /// Writes a byte to the current position in the file stream. + /// This operation is not supported and will throw a NotSupportedException + /// + /// The byte value to write. + /// Any access + public override void WriteByte(byte value) + { + throw new NotSupportedException("TarInputStream WriteByte not supported"); + } + /// + /// Reads a byte from the current tar archive entry. + /// + /// A byte cast to an int; -1 if the at the end of the stream. + public override int ReadByte() + { + byte[] oneByteBuffer = new byte[1]; + int num = Read(oneByteBuffer, 0, 1); + if (num <= 0) + { // return -1 to indicate that no byte was read. - return -1; - } - return oneByteBuffer[0]; - } - - /// - /// Reads bytes from the current tar archive entry. - /// - /// This method is aware of the boundaries of the current - /// entry in the archive and will deal with them appropriately - /// - /// - /// The buffer into which to place bytes read. - /// - /// - /// The offset at which to place bytes read. - /// - /// - /// The number of bytes to read. - /// - /// - /// The number of bytes read, or 0 at end of stream/EOF. - /// - public override int Read(byte[] buffer, int offset, int count) - { - if ( buffer == null ) - { - throw new ArgumentNullException("buffer"); - } + return -1; + } + return oneByteBuffer[0]; + } + + /// + /// Reads bytes from the current tar archive entry. + /// + /// This method is aware of the boundaries of the current + /// entry in the archive and will deal with them appropriately + /// + /// + /// The buffer into which to place bytes read. + /// + /// + /// The offset at which to place bytes read. + /// + /// + /// The number of bytes to read. + /// + /// + /// The number of bytes read, or 0 at end of stream/EOF. + /// + public override int Read(byte[] buffer, int offset, int count) + { + if ( buffer == null ) + { + throw new ArgumentNullException("buffer"); + } - int totalRead = 0; - - if (entryOffset >= entrySize) - { - return 0; - } - - long numToRead = count; - - if ((numToRead + entryOffset) > entrySize) - { - numToRead = entrySize - entryOffset; - } - - if (readBuffer != null) - { - int sz = (numToRead > readBuffer.Length) ? readBuffer.Length : (int)numToRead; - - Array.Copy(readBuffer, 0, buffer, offset, sz); - - if (sz >= readBuffer.Length) - { - readBuffer = null; - } - else - { - int newLen = readBuffer.Length - sz; - byte[] newBuf = new byte[newLen]; - Array.Copy(readBuffer, sz, newBuf, 0, newLen); - readBuffer = newBuf; - } - - totalRead += sz; - numToRead -= sz; - offset += sz; - } - - while (numToRead > 0) - { - byte[] rec = tarBuffer.ReadBlock(); - if (rec == null) - { - // Unexpected EOF! - throw new TarException("unexpected EOF with " + numToRead + " bytes unread"); - } - - int sz = (int)numToRead; - int recLen = rec.Length; - - if (recLen > sz) - { - Array.Copy(rec, 0, buffer, offset, sz); - readBuffer = new byte[recLen - sz]; - Array.Copy(rec, sz, readBuffer, 0, recLen - sz); - } - else - { - sz = recLen; - Array.Copy(rec, 0, buffer, offset, recLen); - } - - totalRead += sz; - numToRead -= sz; - offset += sz; - } - - entryOffset += totalRead; - - return totalRead; - } - - /// - /// Closes this stream. Calls the TarBuffer's close() method. - /// The underlying stream is closed by the TarBuffer. - /// - public override void Close() - { - tarBuffer.Close(); - } - - #endregion + int totalRead = 0; + + if (entryOffset >= entrySize) + { + return 0; + } + + long numToRead = count; + + if ((numToRead + entryOffset) > entrySize) + { + numToRead = entrySize - entryOffset; + } + + if (readBuffer != null) + { + int sz = (numToRead > readBuffer.Length) ? readBuffer.Length : (int)numToRead; + + Array.Copy(readBuffer, 0, buffer, offset, sz); + + if (sz >= readBuffer.Length) + { + readBuffer = null; + } + else + { + int newLen = readBuffer.Length - sz; + byte[] newBuf = new byte[newLen]; + Array.Copy(readBuffer, sz, newBuf, 0, newLen); + readBuffer = newBuf; + } + + totalRead += sz; + numToRead -= sz; + offset += sz; + } + + while (numToRead > 0) + { + byte[] rec = tarBuffer.ReadBlock(); + if (rec == null) + { + // Unexpected EOF! + throw new TarException("unexpected EOF with " + numToRead + " bytes unread"); + } + + int sz = (int)numToRead; + int recLen = rec.Length; + + if (recLen > sz) + { + Array.Copy(rec, 0, buffer, offset, sz); + readBuffer = new byte[recLen - sz]; + Array.Copy(rec, sz, readBuffer, 0, recLen - sz); + } + else + { + sz = recLen; + Array.Copy(rec, 0, buffer, offset, recLen); + } + + totalRead += sz; + numToRead -= sz; + offset += sz; + } + + entryOffset += totalRead; + + return totalRead; + } + + /// + /// Closes this stream. Calls the TarBuffer's close() method. + /// The underlying stream is closed by the TarBuffer. + /// + public override void Close() + { + tarBuffer.Close(); + } + + #endregion - /// - /// Set the entry factory for this instance. - /// - /// The factory for creating new entries - public void SetEntryFactory(IEntryFactory factory) - { - entryFactory = factory; - } - - /// - /// Get the record size being used by this stream's TarBuffer. - /// - public int RecordSize - { - get { return tarBuffer.RecordSize; } - } + /// + /// Set the entry factory for this instance. + /// + /// The factory for creating new entries + public void SetEntryFactory(IEntryFactory factory) + { + entryFactory = factory; + } + + /// + /// Get the record size being used by this stream's TarBuffer. + /// + public int RecordSize + { + get { return tarBuffer.RecordSize; } + } - /// - /// Get the record size being used by this stream's TarBuffer. - /// - /// - /// TarBuffer record size. - /// - [Obsolete("Use RecordSize property instead")] - public int GetRecordSize() - { - return tarBuffer.RecordSize; - } - - /// - /// Get the available data that can be read from the current - /// entry in the archive. This does not indicate how much data - /// is left in the entire archive, only in the current entry. - /// This value is determined from the entry's size header field - /// and the amount of data already read from the current entry. - /// - /// - /// The number of available bytes for the current entry. - /// - public long Available { - get { - return entrySize - entryOffset; - } - } - - /// - /// Skip bytes in the input buffer. This skips bytes in the - /// current entry's data, not the entire archive, and will - /// stop at the end of the current entry's data if the number - /// to skip extends beyond that point. - /// - /// - /// The number of bytes to skip. - /// - public void Skip(long skipCount) - { - // TODO: REVIEW efficiency of TarInputStream.Skip - // This is horribly inefficient, but it ensures that we - // properly skip over bytes via the TarBuffer... - // - byte[] skipBuf = new byte[8 * 1024]; - - for (long num = skipCount; num > 0;) { - int toRead = num > skipBuf.Length ? skipBuf.Length : (int)num; - int numRead = Read(skipBuf, 0, toRead); - - if (numRead == -1) { - break; - } - - num -= numRead; - } - } - - /// - /// Return a value of true if marking is supported; false otherwise. - /// - /// Currently marking is not supported, the return value is always false. - public bool IsMarkSupported { - get { - return false; - } - } - - /// - /// Since we do not support marking just yet, we do nothing. - /// - /// - /// The limit to mark. - /// - public void Mark(int markLimit) - { - } - - /// - /// Since we do not support marking just yet, we do nothing. - /// - public void Reset() - { - } - - /// - /// Get the next entry in this tar archive. This will skip - /// over any remaining data in the current entry, if there - /// is one, and place the input stream at the header of the - /// next entry, and read the header and instantiate a new - /// TarEntry from the header bytes and return that entry. - /// If there are no more entries in the archive, null will - /// be returned to indicate that the end of the archive has - /// been reached. - /// - /// - /// The next TarEntry in the archive, or null. - /// - public TarEntry GetNextEntry() - { - if (hasHitEOF) { - return null; - } - - if (currentEntry != null) { - SkipToNextEntry(); - } - - byte[] headerBuf = tarBuffer.ReadBlock(); - - if (headerBuf == null) { - hasHitEOF = true; - } else if (TarBuffer.IsEndOfArchiveBlock(headerBuf)) { - hasHitEOF = true; - } - - if (hasHitEOF) { - currentEntry = null; - } else { - try { - TarHeader header = new TarHeader(); - header.ParseBuffer(headerBuf); - if ( !header.IsChecksumValid ) - { - throw new TarException("Header checksum is invalid"); - } - this.entryOffset = 0; - this.entrySize = header.Size; - - StringBuilder longName = null; - - if (header.TypeFlag == TarHeader.LF_GNU_LONGNAME) { - - byte[] nameBuffer = new byte[TarBuffer.BlockSize]; - long numToRead = this.entrySize; - - longName = new StringBuilder(); - - while (numToRead > 0) { - int numRead = this.Read(nameBuffer, 0, (numToRead > nameBuffer.Length ? nameBuffer.Length : (int)numToRead)); - - if (numRead == -1) { - throw new InvalidHeaderException("Failed to read long name entry"); - } - - longName.Append(TarHeader.ParseName(nameBuffer, 0, numRead).ToString()); - numToRead -= numRead; - } - - SkipToNextEntry(); - headerBuf = this.tarBuffer.ReadBlock(); - } else if (header.TypeFlag == TarHeader.LF_GHDR) { // POSIX global extended header - // Ignore things we dont understand completely for now - SkipToNextEntry(); - headerBuf = this.tarBuffer.ReadBlock(); - } else if (header.TypeFlag == TarHeader.LF_XHDR) { // POSIX extended header - // Ignore things we dont understand completely for now - SkipToNextEntry(); - headerBuf = this.tarBuffer.ReadBlock(); - } else if (header.TypeFlag == TarHeader.LF_GNU_VOLHDR) { - // TODO: could show volume name when verbose - SkipToNextEntry(); - headerBuf = this.tarBuffer.ReadBlock(); - } else if (header.TypeFlag != TarHeader.LF_NORMAL && - header.TypeFlag != TarHeader.LF_OLDNORM && - header.TypeFlag != TarHeader.LF_DIR) { - // Ignore things we dont understand completely for now - SkipToNextEntry(); - headerBuf = tarBuffer.ReadBlock(); - } - - if (entryFactory == null) { - currentEntry = new TarEntry(headerBuf); - if (longName != null) { - currentEntry.Name = longName.ToString(); - } - } else { - currentEntry = entryFactory.CreateEntry(headerBuf); - } - - // Magic was checked here for 'ustar' but there are multiple valid possibilities - // so this is not done anymore. - - entryOffset = 0; - - // TODO: Review How do we resolve this discrepancy?! - entrySize = this.currentEntry.Size; - } catch (InvalidHeaderException ex) { - entrySize = 0; - entryOffset = 0; - currentEntry = null; - string errorText = string.Format("Bad header in record {0} block {1} {2}", - tarBuffer.CurrentRecord, tarBuffer.CurrentBlock, ex.Message); - throw new InvalidHeaderException(errorText); - } - } - return currentEntry; - } - - /// - /// Copies the contents of the current tar archive entry directly into - /// an output stream. - /// - /// - /// The OutputStream into which to write the entry's data. - /// - public void CopyEntryContents(Stream outputStream) - { - byte[] tempBuffer = new byte[32 * 1024]; - - while (true) { - int numRead = Read(tempBuffer, 0, tempBuffer.Length); - if (numRead <= 0) { - break; - } - outputStream.Write(tempBuffer, 0, numRead); - } - } + /// + /// Get the record size being used by this stream's TarBuffer. + /// + /// + /// TarBuffer record size. + /// + [Obsolete("Use RecordSize property instead")] + public int GetRecordSize() + { + return tarBuffer.RecordSize; + } + + /// + /// Get the available data that can be read from the current + /// entry in the archive. This does not indicate how much data + /// is left in the entire archive, only in the current entry. + /// This value is determined from the entry's size header field + /// and the amount of data already read from the current entry. + /// + /// + /// The number of available bytes for the current entry. + /// + public long Available { + get { + return entrySize - entryOffset; + } + } + + /// + /// Skip bytes in the input buffer. This skips bytes in the + /// current entry's data, not the entire archive, and will + /// stop at the end of the current entry's data if the number + /// to skip extends beyond that point. + /// + /// + /// The number of bytes to skip. + /// + public void Skip(long skipCount) + { + // TODO: REVIEW efficiency of TarInputStream.Skip + // This is horribly inefficient, but it ensures that we + // properly skip over bytes via the TarBuffer... + // + byte[] skipBuf = new byte[8 * 1024]; + + for (long num = skipCount; num > 0;) { + int toRead = num > skipBuf.Length ? skipBuf.Length : (int)num; + int numRead = Read(skipBuf, 0, toRead); + + if (numRead == -1) { + break; + } + + num -= numRead; + } + } + + /// + /// Return a value of true if marking is supported; false otherwise. + /// + /// Currently marking is not supported, the return value is always false. + public bool IsMarkSupported { + get { + return false; + } + } + + /// + /// Since we do not support marking just yet, we do nothing. + /// + /// + /// The limit to mark. + /// + public void Mark(int markLimit) + { + } + + /// + /// Since we do not support marking just yet, we do nothing. + /// + public void Reset() + { + } + + /// + /// Get the next entry in this tar archive. This will skip + /// over any remaining data in the current entry, if there + /// is one, and place the input stream at the header of the + /// next entry, and read the header and instantiate a new + /// TarEntry from the header bytes and return that entry. + /// If there are no more entries in the archive, null will + /// be returned to indicate that the end of the archive has + /// been reached. + /// + /// + /// The next TarEntry in the archive, or null. + /// + public TarEntry GetNextEntry() + { + if (hasHitEOF) { + return null; + } + + if (currentEntry != null) { + SkipToNextEntry(); + } + + byte[] headerBuf = tarBuffer.ReadBlock(); + + if (headerBuf == null) { + hasHitEOF = true; + } else if (TarBuffer.IsEndOfArchiveBlock(headerBuf)) { + hasHitEOF = true; + } + + if (hasHitEOF) { + currentEntry = null; + } else { + try { + TarHeader header = new TarHeader(); + header.ParseBuffer(headerBuf); + if ( !header.IsChecksumValid ) + { + throw new TarException("Header checksum is invalid"); + } + this.entryOffset = 0; + this.entrySize = header.Size; + + StringBuilder longName = null; + + if (header.TypeFlag == TarHeader.LF_GNU_LONGNAME) { + + byte[] nameBuffer = new byte[TarBuffer.BlockSize]; + long numToRead = this.entrySize; + + longName = new StringBuilder(); + + while (numToRead > 0) { + int numRead = this.Read(nameBuffer, 0, (numToRead > nameBuffer.Length ? nameBuffer.Length : (int)numToRead)); + + if (numRead == -1) { + throw new InvalidHeaderException("Failed to read long name entry"); + } + + longName.Append(TarHeader.ParseName(nameBuffer, 0, numRead).ToString()); + numToRead -= numRead; + } + + SkipToNextEntry(); + headerBuf = this.tarBuffer.ReadBlock(); + } else if (header.TypeFlag == TarHeader.LF_GHDR) { // POSIX global extended header + // Ignore things we dont understand completely for now + SkipToNextEntry(); + headerBuf = this.tarBuffer.ReadBlock(); + } else if (header.TypeFlag == TarHeader.LF_XHDR) { // POSIX extended header + // Ignore things we dont understand completely for now + SkipToNextEntry(); + headerBuf = this.tarBuffer.ReadBlock(); + } else if (header.TypeFlag == TarHeader.LF_GNU_VOLHDR) { + // TODO: could show volume name when verbose + SkipToNextEntry(); + headerBuf = this.tarBuffer.ReadBlock(); + } else if (header.TypeFlag != TarHeader.LF_NORMAL && + header.TypeFlag != TarHeader.LF_OLDNORM && + header.TypeFlag != TarHeader.LF_DIR) { + // Ignore things we dont understand completely for now + SkipToNextEntry(); + headerBuf = tarBuffer.ReadBlock(); + } + + if (entryFactory == null) { + currentEntry = new TarEntry(headerBuf); + if (longName != null) { + currentEntry.Name = longName.ToString(); + } + } else { + currentEntry = entryFactory.CreateEntry(headerBuf); + } + + // Magic was checked here for 'ustar' but there are multiple valid possibilities + // so this is not done anymore. + + entryOffset = 0; + + // TODO: Review How do we resolve this discrepancy?! + entrySize = this.currentEntry.Size; + } catch (InvalidHeaderException ex) { + entrySize = 0; + entryOffset = 0; + currentEntry = null; + string errorText = string.Format("Bad header in record {0} block {1} {2}", + tarBuffer.CurrentRecord, tarBuffer.CurrentBlock, ex.Message); + throw new InvalidHeaderException(errorText); + } + } + return currentEntry; + } + + /// + /// Copies the contents of the current tar archive entry directly into + /// an output stream. + /// + /// + /// The OutputStream into which to write the entry's data. + /// + public void CopyEntryContents(Stream outputStream) + { + byte[] tempBuffer = new byte[32 * 1024]; + + while (true) { + int numRead = Read(tempBuffer, 0, tempBuffer.Length); + if (numRead <= 0) { + break; + } + outputStream.Write(tempBuffer, 0, numRead); + } + } - void SkipToNextEntry() - { - long numToSkip = entrySize - entryOffset; - - if (numToSkip > 0) - { - Skip(numToSkip); - } - - readBuffer = null; - } - - /// - /// This interface is provided, along with the method , to allow - /// the programmer to have their own subclass instantiated for the - /// entries return from . - /// - public interface IEntryFactory - { - /// - /// Create an entry based on name alone - /// - /// - /// Name of the new EntryPointNotFoundException to create - /// - /// created TarEntry or descendant class - TarEntry CreateEntry(string name); - - /// - /// Create an instance based on an actual file - /// - /// - /// Name of file to represent in the entry - /// - /// - /// Created TarEntry or descendant class - /// - TarEntry CreateEntryFromFile(string fileName); - - /// - /// Create a tar entry based on the header information passed - /// - /// - /// Buffer containing header information to create an an entry from. - /// - /// - /// Created TarEntry or descendant class - /// - TarEntry CreateEntry(byte[] headerBuffer); - } + void SkipToNextEntry() + { + long numToSkip = entrySize - entryOffset; + + if (numToSkip > 0) + { + Skip(numToSkip); + } + + readBuffer = null; + } + + /// + /// This interface is provided, along with the method , to allow + /// the programmer to have their own subclass instantiated for the + /// entries return from . + /// + public interface IEntryFactory + { + /// + /// Create an entry based on name alone + /// + /// + /// Name of the new EntryPointNotFoundException to create + /// + /// created TarEntry or descendant class + TarEntry CreateEntry(string name); + + /// + /// Create an instance based on an actual file + /// + /// + /// Name of file to represent in the entry + /// + /// + /// Created TarEntry or descendant class + /// + TarEntry CreateEntryFromFile(string fileName); + + /// + /// Create a tar entry based on the header information passed + /// + /// + /// Buffer containing header information to create an an entry from. + /// + /// + /// Created TarEntry or descendant class + /// + TarEntry CreateEntry(byte[] headerBuffer); + } - /// - /// Standard entry factory class creating instances of the class TarEntry - /// - public class EntryFactoryAdapter : IEntryFactory - { - /// - /// Create a based on named - /// - /// The name to use for the entry - /// A new - public TarEntry CreateEntry(string name) - { - return TarEntry.CreateTarEntry(name); - } - - /// - /// Create a tar entry with details obtained from file - /// - /// The name of the file to retrieve details from. - /// A new - public TarEntry CreateEntryFromFile(string fileName) - { - return TarEntry.CreateEntryFromFile(fileName); - } + /// + /// Standard entry factory class creating instances of the class TarEntry + /// + public class EntryFactoryAdapter : IEntryFactory + { + /// + /// Create a based on named + /// + /// The name to use for the entry + /// A new + public TarEntry CreateEntry(string name) + { + return TarEntry.CreateTarEntry(name); + } + + /// + /// Create a tar entry with details obtained from file + /// + /// The name of the file to retrieve details from. + /// A new + public TarEntry CreateEntryFromFile(string fileName) + { + return TarEntry.CreateEntryFromFile(fileName); + } - /// - /// Create an entry based on details in header - /// - /// The buffer containing entry details. - /// A new - public TarEntry CreateEntry(byte[] headerBuffer) - { - return new TarEntry(headerBuffer); - } - } + /// + /// Create an entry based on details in header + /// + /// The buffer containing entry details. + /// A new + public TarEntry CreateEntry(byte[] headerBuffer) + { + return new TarEntry(headerBuffer); + } + } - #region Instance Fields - /// - /// Flag set when last block has been read - /// - protected bool hasHitEOF; - - /// - /// Size of this entry as recorded in header - /// - protected long entrySize; - - /// - /// Number of bytes read for this entry so far - /// - protected long entryOffset; + #region Instance Fields + /// + /// Flag set when last block has been read + /// + protected bool hasHitEOF; + + /// + /// Size of this entry as recorded in header + /// + protected long entrySize; + + /// + /// Number of bytes read for this entry so far + /// + protected long entryOffset; - /// - /// Buffer used with calls to Read() - /// - protected byte[] readBuffer; - - /// - /// Working buffer - /// - protected TarBuffer tarBuffer; - - /// - /// Current entry being read - /// - TarEntry currentEntry; - - /// - /// Factory used to create TarEntry or descendant class instance - /// - protected IEntryFactory entryFactory; - - /// - /// Stream used as the source of input data. - /// - readonly Stream inputStream; - #endregion - } + /// + /// Buffer used with calls to Read() + /// + protected byte[] readBuffer; + + /// + /// Working buffer + /// + protected TarBuffer tarBuffer; + + /// + /// Current entry being read + /// + TarEntry currentEntry; + + /// + /// Factory used to create TarEntry or descendant class instance + /// + protected IEntryFactory entryFactory; + + /// + /// Stream used as the source of input data. + /// + readonly Stream inputStream; + #endregion + } } /* The original Java file had this header: - ** Authored by Timothy Gerard Endres - ** - ** - ** This work has been placed into the public domain. - ** You may use this work in any way and for any purpose you wish. - ** - ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, - ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR - ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY - ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR - ** REDISTRIBUTION OF THIS SOFTWARE. - ** - */ - + ** Authored by Timothy Gerard Endres + ** + ** + ** This work has been placed into the public domain. + ** You may use this work in any way and for any purpose you wish. + ** + ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, + ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR + ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY + ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR + ** REDISTRIBUTION OF THIS SOFTWARE. + ** + */ + diff --git a/External/Tools/AppMan/ZipLib/Tar/TarOutputStream.cs b/External/Tools/AppMan/ZipLib/Tar/TarOutputStream.cs index fcac26fa6b..9ebe3f20ce 100644 --- a/External/Tools/AppMan/ZipLib/Tar/TarOutputStream.cs +++ b/External/Tools/AppMan/ZipLib/Tar/TarOutputStream.cs @@ -39,44 +39,44 @@ namespace ICSharpCode.SharpZipLib.Tar { - - /// - /// The TarOutputStream writes a UNIX tar archive as an OutputStream. - /// Methods are provided to put entries, and then write their contents - /// by writing to this stream using write(). - /// - /// public - public class TarOutputStream : Stream - { - #region Constructors - /// - /// Construct TarOutputStream using default block factor - /// - /// stream to write to - public TarOutputStream(Stream outputStream) - : this(outputStream, TarBuffer.DefaultBlockFactor) - { - } - - /// - /// Construct TarOutputStream with user specified block factor - /// - /// stream to write to - /// blocking factor - public TarOutputStream(Stream outputStream, int blockFactor) - { - if ( outputStream == null ) - { - throw new ArgumentNullException("outputStream"); - } + + /// + /// The TarOutputStream writes a UNIX tar archive as an OutputStream. + /// Methods are provided to put entries, and then write their contents + /// by writing to this stream using write(). + /// + /// public + public class TarOutputStream : Stream + { + #region Constructors + /// + /// Construct TarOutputStream using default block factor + /// + /// stream to write to + public TarOutputStream(Stream outputStream) + : this(outputStream, TarBuffer.DefaultBlockFactor) + { + } + + /// + /// Construct TarOutputStream with user specified block factor + /// + /// stream to write to + /// blocking factor + public TarOutputStream(Stream outputStream, int blockFactor) + { + if ( outputStream == null ) + { + throw new ArgumentNullException("outputStream"); + } - this.outputStream = outputStream; - buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor); - - assemblyBuffer = new byte[TarBuffer.BlockSize]; - blockBuffer = new byte[TarBuffer.BlockSize]; - } - #endregion + this.outputStream = outputStream; + buffer = TarBuffer.CreateOutputTarBuffer(outputStream, blockFactor); + + assemblyBuffer = new byte[TarBuffer.BlockSize]; + blockBuffer = new byte[TarBuffer.BlockSize]; + } + #endregion /// /// Get/set flag indicating ownership of the underlying stream. @@ -88,438 +88,438 @@ public bool IsStreamOwner set { buffer.IsStreamOwner = value; } } - /// - /// true if the stream supports reading; otherwise, false. - /// - public override bool CanRead - { - get - { - return outputStream.CanRead; - } - } - - /// - /// true if the stream supports seeking; otherwise, false. - /// - public override bool CanSeek - { - get - { - return outputStream.CanSeek; - } - } - - /// - /// true if stream supports writing; otherwise, false. - /// - public override bool CanWrite - { - get - { - return outputStream.CanWrite; - } - } - - /// - /// length of stream in bytes - /// - public override long Length - { - get - { - return outputStream.Length; - } - } - - /// - /// gets or sets the position within the current stream. - /// - public override long Position - { - get - { - return outputStream.Position; - } - set - { - outputStream.Position = value; - } - } - - /// - /// set the position within the current stream - /// - /// The offset relative to the to seek to - /// The to seek from. - /// The new position in the stream. - public override long Seek(long offset, SeekOrigin origin) - { - return outputStream.Seek(offset, origin); - } - - /// - /// Set the length of the current stream - /// - /// The new stream length. - public override void SetLength(long value) - { - outputStream.SetLength(value); - } - - /// - /// Read a byte from the stream and advance the position within the stream - /// by one byte or returns -1 if at the end of the stream. - /// - /// The byte value or -1 if at end of stream - public override int ReadByte() - { - return outputStream.ReadByte(); - } - - /// - /// read bytes from the current stream and advance the position within the - /// stream by the number of bytes read. - /// - /// The buffer to store read bytes in. - /// The index into the buffer to being storing bytes at. - /// The desired number of bytes to read. - /// The total number of bytes read, or zero if at the end of the stream. - /// The number of bytes may be less than the count - /// requested if data is not avialable. - public override int Read(byte[] buffer, int offset, int count) - { - return outputStream.Read(buffer, offset, count); - } + /// + /// true if the stream supports reading; otherwise, false. + /// + public override bool CanRead + { + get + { + return outputStream.CanRead; + } + } + + /// + /// true if the stream supports seeking; otherwise, false. + /// + public override bool CanSeek + { + get + { + return outputStream.CanSeek; + } + } + + /// + /// true if stream supports writing; otherwise, false. + /// + public override bool CanWrite + { + get + { + return outputStream.CanWrite; + } + } + + /// + /// length of stream in bytes + /// + public override long Length + { + get + { + return outputStream.Length; + } + } + + /// + /// gets or sets the position within the current stream. + /// + public override long Position + { + get + { + return outputStream.Position; + } + set + { + outputStream.Position = value; + } + } + + /// + /// set the position within the current stream + /// + /// The offset relative to the to seek to + /// The to seek from. + /// The new position in the stream. + public override long Seek(long offset, SeekOrigin origin) + { + return outputStream.Seek(offset, origin); + } + + /// + /// Set the length of the current stream + /// + /// The new stream length. + public override void SetLength(long value) + { + outputStream.SetLength(value); + } + + /// + /// Read a byte from the stream and advance the position within the stream + /// by one byte or returns -1 if at the end of the stream. + /// + /// The byte value or -1 if at end of stream + public override int ReadByte() + { + return outputStream.ReadByte(); + } + + /// + /// read bytes from the current stream and advance the position within the + /// stream by the number of bytes read. + /// + /// The buffer to store read bytes in. + /// The index into the buffer to being storing bytes at. + /// The desired number of bytes to read. + /// The total number of bytes read, or zero if at the end of the stream. + /// The number of bytes may be less than the count + /// requested if data is not avialable. + public override int Read(byte[] buffer, int offset, int count) + { + return outputStream.Read(buffer, offset, count); + } - /// - /// All buffered data is written to destination - /// - public override void Flush() - { - outputStream.Flush(); - } - - /// - /// Ends the TAR archive without closing the underlying OutputStream. - /// The result is that the EOF block of nulls is written. - /// - public void Finish() - { - if ( IsEntryOpen ) - { - CloseEntry(); - } - WriteEofBlock(); - } - - /// - /// Ends the TAR archive and closes the underlying OutputStream. - /// - /// This means that Finish() is called followed by calling the - /// TarBuffer's Close(). - public override void Close() - { - if ( !isClosed ) - { - isClosed = true; - Finish(); - buffer.Close(); - } - } - - /// - /// Get the record size being used by this stream's TarBuffer. - /// - public int RecordSize - { - get { return buffer.RecordSize; } - } + /// + /// All buffered data is written to destination + /// + public override void Flush() + { + outputStream.Flush(); + } + + /// + /// Ends the TAR archive without closing the underlying OutputStream. + /// The result is that the EOF block of nulls is written. + /// + public void Finish() + { + if ( IsEntryOpen ) + { + CloseEntry(); + } + WriteEofBlock(); + } + + /// + /// Ends the TAR archive and closes the underlying OutputStream. + /// + /// This means that Finish() is called followed by calling the + /// TarBuffer's Close(). + public override void Close() + { + if ( !isClosed ) + { + isClosed = true; + Finish(); + buffer.Close(); + } + } + + /// + /// Get the record size being used by this stream's TarBuffer. + /// + public int RecordSize + { + get { return buffer.RecordSize; } + } - /// - /// Get the record size being used by this stream's TarBuffer. - /// - /// - /// The TarBuffer record size. - /// - [Obsolete("Use RecordSize property instead")] - public int GetRecordSize() - { - return buffer.RecordSize; - } - - /// - /// Get a value indicating wether an entry is open, requiring more data to be written. - /// - bool IsEntryOpen - { - get { return (currBytes < currSize); } + /// + /// Get the record size being used by this stream's TarBuffer. + /// + /// + /// The TarBuffer record size. + /// + [Obsolete("Use RecordSize property instead")] + public int GetRecordSize() + { + return buffer.RecordSize; + } + + /// + /// Get a value indicating wether an entry is open, requiring more data to be written. + /// + bool IsEntryOpen + { + get { return (currBytes < currSize); } - } + } - /// - /// Put an entry on the output stream. This writes the entry's - /// header and positions the output stream for writing - /// the contents of the entry. Once this method is called, the - /// stream is ready for calls to write() to write the entry's - /// contents. Once the contents are written, closeEntry() - /// MUST be called to ensure that all buffered data - /// is completely written to the output stream. - /// - /// - /// The TarEntry to be written to the archive. - /// - public void PutNextEntry(TarEntry entry) - { - if ( entry == null ) { - throw new ArgumentNullException("entry"); - } + /// + /// Put an entry on the output stream. This writes the entry's + /// header and positions the output stream for writing + /// the contents of the entry. Once this method is called, the + /// stream is ready for calls to write() to write the entry's + /// contents. Once the contents are written, closeEntry() + /// MUST be called to ensure that all buffered data + /// is completely written to the output stream. + /// + /// + /// The TarEntry to be written to the archive. + /// + public void PutNextEntry(TarEntry entry) + { + if ( entry == null ) { + throw new ArgumentNullException("entry"); + } - if (entry.TarHeader.Name.Length >= TarHeader.NAMELEN) { - TarHeader longHeader = new TarHeader(); - longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME; - longHeader.Name = longHeader.Name + "././@LongLink"; - longHeader.UserId = 0; - longHeader.GroupId = 0; - longHeader.GroupName = ""; - longHeader.UserName = ""; - longHeader.LinkName = ""; + if (entry.TarHeader.Name.Length >= TarHeader.NAMELEN) { + TarHeader longHeader = new TarHeader(); + longHeader.TypeFlag = TarHeader.LF_GNU_LONGNAME; + longHeader.Name = longHeader.Name + "././@LongLink"; + longHeader.UserId = 0; + longHeader.GroupId = 0; + longHeader.GroupName = ""; + longHeader.UserName = ""; + longHeader.LinkName = ""; longHeader.Size = entry.TarHeader.Name.Length; - longHeader.WriteHeader(blockBuffer); - buffer.WriteBlock(blockBuffer); // Add special long filename header block + longHeader.WriteHeader(blockBuffer); + buffer.WriteBlock(blockBuffer); // Add special long filename header block - int nameCharIndex = 0; + int nameCharIndex = 0; - while (nameCharIndex < entry.TarHeader.Name.Length) { - Array.Clear(blockBuffer, 0, blockBuffer.Length); - TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize); - nameCharIndex += TarBuffer.BlockSize; - buffer.WriteBlock(blockBuffer); - } - } - - entry.WriteEntryHeader(blockBuffer); - buffer.WriteBlock(blockBuffer); - - currBytes = 0; - - currSize = entry.IsDirectory ? 0 : entry.Size; - } - - /// - /// Close an entry. This method MUST be called for all file - /// entries that contain data. The reason is that we must - /// buffer data written to the stream in order to satisfy - /// the buffer's block based writes. Thus, there may be - /// data fragments still being assembled that must be written - /// to the output stream before this entry is closed and the - /// next entry written. - /// - public void CloseEntry() - { - if (assemblyBufferLength > 0) { - Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength); - - buffer.WriteBlock(assemblyBuffer); - - currBytes += assemblyBufferLength; - assemblyBufferLength = 0; - } - - if (currBytes < currSize) { - string errorText = string.Format( - "Entry closed at '{0}' before the '{1}' bytes specified in the header were written", - currBytes, currSize); - throw new TarException(errorText); - } - } - - /// - /// Writes a byte to the current tar archive entry. - /// This method simply calls Write(byte[], int, int). - /// - /// - /// The byte to be written. - /// - public override void WriteByte(byte value) - { - Write(new byte[] { value }, 0, 1); - } - - /// - /// Writes bytes to the current tar archive entry. This method - /// is aware of the current entry and will throw an exception if - /// you attempt to write bytes past the length specified for the - /// current entry. The method is also (painfully) aware of the - /// record buffering required by TarBuffer, and manages buffers - /// that are not a multiple of recordsize in length, including - /// assembling records from small buffers. - /// - /// - /// The buffer to write to the archive. - /// - /// - /// The offset in the buffer from which to get bytes. - /// - /// - /// The number of bytes to write. - /// - public override void Write(byte[] buffer, int offset, int count) - { - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } - - if ( offset < 0 ) - { + while (nameCharIndex < entry.TarHeader.Name.Length) { + Array.Clear(blockBuffer, 0, blockBuffer.Length); + TarHeader.GetAsciiBytes(entry.TarHeader.Name, nameCharIndex, this.blockBuffer, 0, TarBuffer.BlockSize); + nameCharIndex += TarBuffer.BlockSize; + buffer.WriteBlock(blockBuffer); + } + } + + entry.WriteEntryHeader(blockBuffer); + buffer.WriteBlock(blockBuffer); + + currBytes = 0; + + currSize = entry.IsDirectory ? 0 : entry.Size; + } + + /// + /// Close an entry. This method MUST be called for all file + /// entries that contain data. The reason is that we must + /// buffer data written to the stream in order to satisfy + /// the buffer's block based writes. Thus, there may be + /// data fragments still being assembled that must be written + /// to the output stream before this entry is closed and the + /// next entry written. + /// + public void CloseEntry() + { + if (assemblyBufferLength > 0) { + Array.Clear(assemblyBuffer, assemblyBufferLength, assemblyBuffer.Length - assemblyBufferLength); + + buffer.WriteBlock(assemblyBuffer); + + currBytes += assemblyBufferLength; + assemblyBufferLength = 0; + } + + if (currBytes < currSize) { + string errorText = string.Format( + "Entry closed at '{0}' before the '{1}' bytes specified in the header were written", + currBytes, currSize); + throw new TarException(errorText); + } + } + + /// + /// Writes a byte to the current tar archive entry. + /// This method simply calls Write(byte[], int, int). + /// + /// + /// The byte to be written. + /// + public override void WriteByte(byte value) + { + Write(new byte[] { value }, 0, 1); + } + + /// + /// Writes bytes to the current tar archive entry. This method + /// is aware of the current entry and will throw an exception if + /// you attempt to write bytes past the length specified for the + /// current entry. The method is also (painfully) aware of the + /// record buffering required by TarBuffer, and manages buffers + /// that are not a multiple of recordsize in length, including + /// assembling records from small buffers. + /// + /// + /// The buffer to write to the archive. + /// + /// + /// The offset in the buffer from which to get bytes. + /// + /// + /// The number of bytes to write. + /// + public override void Write(byte[] buffer, int offset, int count) + { + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } + + if ( offset < 0 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); -#endif - } + throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); +#endif + } - if ( buffer.Length - offset < count ) - { - throw new ArgumentException("offset and count combination is invalid"); - } + if ( buffer.Length - offset < count ) + { + throw new ArgumentException("offset and count combination is invalid"); + } - if ( count < 0 ) - { + if ( count < 0 ) + { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "Cannot be negative"); + throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif - } + } - if ( (currBytes + count) > currSize ) { - string errorText = string.Format("request to write '{0}' bytes exceeds size in header of '{1}' bytes", - count, this.currSize); + if ( (currBytes + count) > currSize ) { + string errorText = string.Format("request to write '{0}' bytes exceeds size in header of '{1}' bytes", + count, this.currSize); #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", errorText); -#endif - } - - // - // We have to deal with assembly!!! - // The programmer can be writing little 32 byte chunks for all - // we know, and we must assemble complete blocks for writing. - // TODO REVIEW Maybe this should be in TarBuffer? Could that help to - // eliminate some of the buffer copying. - // - if (assemblyBufferLength > 0) { - if ((assemblyBufferLength + count ) >= blockBuffer.Length) { - int aLen = blockBuffer.Length - assemblyBufferLength; - - Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength); - Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen); - - this.buffer.WriteBlock(blockBuffer); - - currBytes += blockBuffer.Length; - - offset += aLen; - count -= aLen; - - assemblyBufferLength = 0; - } else { - Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); - offset += count; - assemblyBufferLength += count; - count -= count; - } - } - - // - // When we get here we have EITHER: - // o An empty "assembly" buffer. - // o No bytes to write (count == 0) - // - while (count > 0) { - if (count < blockBuffer.Length) { - Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); - assemblyBufferLength += count; - break; - } - - this.buffer.WriteBlock(buffer, offset); - - int bufferLength = blockBuffer.Length; - currBytes += bufferLength; - count -= bufferLength; - offset += bufferLength; - } - } - - /// - /// Write an EOF (end of archive) block to the tar archive. - /// An EOF block consists of all zeros. - /// - void WriteEofBlock() - { - Array.Clear(blockBuffer, 0, blockBuffer.Length); - buffer.WriteBlock(blockBuffer); - } + throw new ArgumentOutOfRangeException("count", errorText); +#endif + } + + // + // We have to deal with assembly!!! + // The programmer can be writing little 32 byte chunks for all + // we know, and we must assemble complete blocks for writing. + // TODO REVIEW Maybe this should be in TarBuffer? Could that help to + // eliminate some of the buffer copying. + // + if (assemblyBufferLength > 0) { + if ((assemblyBufferLength + count ) >= blockBuffer.Length) { + int aLen = blockBuffer.Length - assemblyBufferLength; + + Array.Copy(assemblyBuffer, 0, blockBuffer, 0, assemblyBufferLength); + Array.Copy(buffer, offset, blockBuffer, assemblyBufferLength, aLen); + + this.buffer.WriteBlock(blockBuffer); + + currBytes += blockBuffer.Length; + + offset += aLen; + count -= aLen; + + assemblyBufferLength = 0; + } else { + Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); + offset += count; + assemblyBufferLength += count; + count -= count; + } + } + + // + // When we get here we have EITHER: + // o An empty "assembly" buffer. + // o No bytes to write (count == 0) + // + while (count > 0) { + if (count < blockBuffer.Length) { + Array.Copy(buffer, offset, assemblyBuffer, assemblyBufferLength, count); + assemblyBufferLength += count; + break; + } + + this.buffer.WriteBlock(buffer, offset); + + int bufferLength = blockBuffer.Length; + currBytes += bufferLength; + count -= bufferLength; + offset += bufferLength; + } + } + + /// + /// Write an EOF (end of archive) block to the tar archive. + /// An EOF block consists of all zeros. + /// + void WriteEofBlock() + { + Array.Clear(blockBuffer, 0, blockBuffer.Length); + buffer.WriteBlock(blockBuffer); + } - #region Instance Fields - /// - /// bytes written for this entry so far - /// - long currBytes; - - /// - /// current 'Assembly' buffer length - /// - int assemblyBufferLength; + #region Instance Fields + /// + /// bytes written for this entry so far + /// + long currBytes; + + /// + /// current 'Assembly' buffer length + /// + int assemblyBufferLength; - /// - /// Flag indicating wether this instance has been closed or not. - /// - bool isClosed; + /// + /// Flag indicating wether this instance has been closed or not. + /// + bool isClosed; - /// - /// Size for the current entry - /// - protected long currSize; + /// + /// Size for the current entry + /// + protected long currSize; - /// - /// single block working buffer - /// - protected byte[] blockBuffer; + /// + /// single block working buffer + /// + protected byte[] blockBuffer; - /// - /// 'Assembly' buffer used to assemble data before writing - /// - protected byte[] assemblyBuffer; - - /// - /// TarBuffer used to provide correct blocking factor - /// - protected TarBuffer buffer; - - /// - /// the destination stream for the archive contents - /// - protected Stream outputStream; - #endregion - } + /// + /// 'Assembly' buffer used to assemble data before writing + /// + protected byte[] assemblyBuffer; + + /// + /// TarBuffer used to provide correct blocking factor + /// + protected TarBuffer buffer; + + /// + /// the destination stream for the archive contents + /// + protected Stream outputStream; + #endregion + } } /* The original Java file had this header: - ** Authored by Timothy Gerard Endres - ** - ** - ** This work has been placed into the public domain. - ** You may use this work in any way and for any purpose you wish. - ** - ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, - ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR - ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY - ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR - ** REDISTRIBUTION OF THIS SOFTWARE. - ** - */ + ** Authored by Timothy Gerard Endres + ** + ** + ** This work has been placed into the public domain. + ** You may use this work in any way and for any purpose you wish. + ** + ** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND, + ** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR + ** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY + ** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR + ** REDISTRIBUTION OF THIS SOFTWARE. + ** + */ diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/Deflater.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/Deflater.cs index dadbfb6633..49b9570489 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/Deflater.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/Deflater.cs @@ -41,517 +41,517 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - - /// - /// This is the Deflater class. The deflater class compresses input - /// with the deflate algorithm described in RFC 1951. It has several - /// compression levels and three different strategies described below. - /// - /// This class is not thread safe. This is inherent in the API, due - /// to the split of deflate and setInput. - /// - /// author of the original java version : Jochen Hoenicke - /// - public class Deflater - { - #region Deflater Documentation - /* - * The Deflater can do the following state transitions: - * - * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. - * / | (2) (5) | - * / v (5) | - * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) - * \ | (3) | ,--------' - * | | | (3) / - * v v (5) v v - * (1) -> BUSY_STATE ----> FINISHING_STATE - * | (6) - * v - * FINISHED_STATE - * \_____________________________________/ - * | (7) - * v - * CLOSED_STATE - * - * (1) If we should produce a header we start in INIT_STATE, otherwise - * we start in BUSY_STATE. - * (2) A dictionary may be set only when we are in INIT_STATE, then - * we change the state as indicated. - * (3) Whether a dictionary is set or not, on the first call of deflate - * we change to BUSY_STATE. - * (4) -- intentionally left blank -- :) - * (5) FINISHING_STATE is entered, when flush() is called to indicate that - * there is no more INPUT. There are also states indicating, that - * the header wasn't written yet. - * (6) FINISHED_STATE is entered, when everything has been flushed to the - * internal pending output buffer. - * (7) At any time (7) - * - */ - #endregion - #region Public Constants - /// - /// The best and slowest compression level. This tries to find very - /// long and distant string repetitions. - /// - public const int BEST_COMPRESSION = 9; - - /// - /// The worst but fastest compression level. - /// - public const int BEST_SPEED = 1; - - /// - /// The default compression level. - /// - public const int DEFAULT_COMPRESSION = -1; - - /// - /// This level won't compress at all but output uncompressed blocks. - /// - public const int NO_COMPRESSION = 0; - - /// - /// The compression method. This is the only method supported so far. - /// There is no need to use this constant at all. - /// - public const int DEFLATED = 8; - #endregion - #region Local Constants - private const int IS_SETDICT = 0x01; - private const int IS_FLUSHING = 0x04; - private const int IS_FINISHING = 0x08; - - private const int INIT_STATE = 0x00; - private const int SETDICT_STATE = 0x01; - // private static int INIT_FINISHING_STATE = 0x08; - // private static int SETDICT_FINISHING_STATE = 0x09; - private const int BUSY_STATE = 0x10; - private const int FLUSHING_STATE = 0x14; - private const int FINISHING_STATE = 0x1c; - private const int FINISHED_STATE = 0x1e; - private const int CLOSED_STATE = 0x7f; - #endregion - #region Constructors - /// - /// Creates a new deflater with default compression level. - /// - public Deflater() : this(DEFAULT_COMPRESSION, false) - { - - } - - /// - /// Creates a new deflater with given compression level. - /// - /// - /// the compression level, a value between NO_COMPRESSION - /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. - /// - /// if lvl is out of range. - public Deflater(int level) : this(level, false) - { - - } - - /// - /// Creates a new deflater with given compression level. - /// - /// - /// the compression level, a value between NO_COMPRESSION - /// and BEST_COMPRESSION. - /// - /// - /// true, if we should suppress the Zlib/RFC1950 header at the - /// beginning and the adler checksum at the end of the output. This is - /// useful for the GZIP/PKZIP formats. - /// - /// if lvl is out of range. - public Deflater(int level, bool noZlibHeaderOrFooter) - { - if (level == DEFAULT_COMPRESSION) { - level = 6; - } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { - throw new ArgumentOutOfRangeException("level"); - } - - pending = new DeflaterPending(); - engine = new DeflaterEngine(pending); - this.noZlibHeaderOrFooter = noZlibHeaderOrFooter; - SetStrategy(DeflateStrategy.Default); - SetLevel(level); - Reset(); - } - #endregion - - /// - /// Resets the deflater. The deflater acts afterwards as if it was - /// just created with the same compression level and strategy as it - /// had before. - /// - public void Reset() - { - state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE); - totalOut = 0; - pending.Reset(); - engine.Reset(); - } - - /// - /// Gets the current adler checksum of the data that was processed so far. - /// - public int Adler { - get { - return engine.Adler; - } - } - - /// - /// Gets the number of input bytes processed so far. - /// - public long TotalIn { - get { - return engine.TotalIn; - } - } - - /// - /// Gets the number of output bytes so far. - /// - public long TotalOut { - get { - return totalOut; - } - } - - /// - /// Flushes the current input block. Further calls to deflate() will - /// produce enough output to inflate everything in the current input - /// block. This is not part of Sun's JDK so I have made it package - /// private. It is used by DeflaterOutputStream to implement - /// flush(). - /// - public void Flush() - { - state |= IS_FLUSHING; - } - - /// - /// Finishes the deflater with the current input block. It is an error - /// to give more input after this method was called. This method must - /// be called to force all bytes to be flushed. - /// - public void Finish() - { - state |= (IS_FLUSHING | IS_FINISHING); - } - - /// - /// Returns true if the stream was finished and no more output bytes - /// are available. - /// - public bool IsFinished { - get { - return (state == FINISHED_STATE) && pending.IsFlushed; - } - } - - /// - /// Returns true, if the input buffer is empty. - /// You should then call setInput(). - /// NOTE: This method can also return true when the stream - /// was finished. - /// - public bool IsNeedingInput { - get { - return engine.NeedsInput(); - } - } - - /// - /// Sets the data which should be compressed next. This should be only - /// called when needsInput indicates that more input is needed. - /// If you call setInput when needsInput() returns false, the - /// previous input that is still pending will be thrown away. - /// The given byte array should not be changed, before needsInput() returns - /// true again. - /// This call is equivalent to setInput(input, 0, input.length). - /// - /// - /// the buffer containing the input data. - /// - /// - /// if the buffer was finished() or ended(). - /// - public void SetInput(byte[] input) - { - SetInput(input, 0, input.Length); - } - - /// - /// Sets the data which should be compressed next. This should be - /// only called when needsInput indicates that more input is needed. - /// The given byte array should not be changed, before needsInput() returns - /// true again. - /// - /// - /// the buffer containing the input data. - /// - /// - /// the start of the data. - /// - /// - /// the number of data bytes of input. - /// - /// - /// if the buffer was Finish()ed or if previous input is still pending. - /// - public void SetInput(byte[] input, int offset, int count) - { - if ((state & IS_FINISHING) != 0) { - throw new InvalidOperationException("Finish() already called"); - } - engine.SetInput(input, offset, count); - } - - /// - /// Sets the compression level. There is no guarantee of the exact - /// position of the change, but if you call this when needsInput is - /// true the change of compression level will occur somewhere near - /// before the end of the so far given input. - /// - /// - /// the new compression level. - /// - public void SetLevel(int level) - { - if (level == DEFAULT_COMPRESSION) { - level = 6; - } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { - throw new ArgumentOutOfRangeException("level"); - } - - if (this.level != level) { - this.level = level; - engine.SetLevel(level); - } - } - - /// - /// Get current compression level - /// - /// Returns the current compression level - public int GetLevel() { - return level; - } - - /// - /// Sets the compression strategy. Strategy is one of - /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact - /// position where the strategy is changed, the same as for - /// SetLevel() applies. - /// - /// - /// The new compression strategy. - /// - public void SetStrategy(DeflateStrategy strategy) - { - engine.Strategy = strategy; - } - - /// - /// Deflates the current input block with to the given array. - /// - /// - /// The buffer where compressed data is stored - /// - /// - /// The number of compressed bytes added to the output, or 0 if either - /// IsNeedingInput() or IsFinished returns true or length is zero. - /// - public int Deflate(byte[] output) - { - return Deflate(output, 0, output.Length); - } - - /// - /// Deflates the current input block to the given array. - /// - /// - /// Buffer to store the compressed data. - /// - /// - /// Offset into the output array. - /// - /// - /// The maximum number of bytes that may be stored. - /// - /// - /// The number of compressed bytes added to the output, or 0 if either - /// needsInput() or finished() returns true or length is zero. - /// - /// - /// If Finish() was previously called. - /// - /// - /// If offset or length don't match the array length. - /// - public int Deflate(byte[] output, int offset, int length) - { - int origLength = length; - - if (state == CLOSED_STATE) { - throw new InvalidOperationException("Deflater closed"); - } - - if (state < BUSY_STATE) { - // output header - int header = (DEFLATED + - ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; - int level_flags = (level - 1) >> 1; - if (level_flags < 0 || level_flags > 3) { - level_flags = 3; - } - header |= level_flags << 6; - if ((state & IS_SETDICT) != 0) { - // Dictionary was set - header |= DeflaterConstants.PRESET_DICT; - } - header += 31 - (header % 31); - - pending.WriteShortMSB(header); - if ((state & IS_SETDICT) != 0) { - int chksum = engine.Adler; - engine.ResetAdler(); - pending.WriteShortMSB(chksum >> 16); - pending.WriteShortMSB(chksum & 0xffff); - } - - state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); - } - - for (;;) { - int count = pending.Flush(output, offset, length); - offset += count; - totalOut += count; - length -= count; - - if (length == 0 || state == FINISHED_STATE) { - break; - } - - if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { - if (state == BUSY_STATE) { - // We need more input now - return origLength - length; - } else if (state == FLUSHING_STATE) { - if (level != NO_COMPRESSION) { - /* We have to supply some lookahead. 8 bit lookahead - * is needed by the zlib inflater, and we must fill - * the next byte, so that all bits are flushed. - */ - int neededbits = 8 + ((-pending.BitCount) & 7); - while (neededbits > 0) { - /* write a static tree block consisting solely of - * an EOF: - */ - pending.WriteBits(2, 10); - neededbits -= 10; - } - } - state = BUSY_STATE; - } else if (state == FINISHING_STATE) { - pending.AlignToByte(); + + /// + /// This is the Deflater class. The deflater class compresses input + /// with the deflate algorithm described in RFC 1951. It has several + /// compression levels and three different strategies described below. + /// + /// This class is not thread safe. This is inherent in the API, due + /// to the split of deflate and setInput. + /// + /// author of the original java version : Jochen Hoenicke + /// + public class Deflater + { + #region Deflater Documentation + /* + * The Deflater can do the following state transitions: + * + * (1) -> INIT_STATE ----> INIT_FINISHING_STATE ---. + * / | (2) (5) | + * / v (5) | + * (3)| SETDICT_STATE ---> SETDICT_FINISHING_STATE |(3) + * \ | (3) | ,--------' + * | | | (3) / + * v v (5) v v + * (1) -> BUSY_STATE ----> FINISHING_STATE + * | (6) + * v + * FINISHED_STATE + * \_____________________________________/ + * | (7) + * v + * CLOSED_STATE + * + * (1) If we should produce a header we start in INIT_STATE, otherwise + * we start in BUSY_STATE. + * (2) A dictionary may be set only when we are in INIT_STATE, then + * we change the state as indicated. + * (3) Whether a dictionary is set or not, on the first call of deflate + * we change to BUSY_STATE. + * (4) -- intentionally left blank -- :) + * (5) FINISHING_STATE is entered, when flush() is called to indicate that + * there is no more INPUT. There are also states indicating, that + * the header wasn't written yet. + * (6) FINISHED_STATE is entered, when everything has been flushed to the + * internal pending output buffer. + * (7) At any time (7) + * + */ + #endregion + #region Public Constants + /// + /// The best and slowest compression level. This tries to find very + /// long and distant string repetitions. + /// + public const int BEST_COMPRESSION = 9; + + /// + /// The worst but fastest compression level. + /// + public const int BEST_SPEED = 1; + + /// + /// The default compression level. + /// + public const int DEFAULT_COMPRESSION = -1; + + /// + /// This level won't compress at all but output uncompressed blocks. + /// + public const int NO_COMPRESSION = 0; + + /// + /// The compression method. This is the only method supported so far. + /// There is no need to use this constant at all. + /// + public const int DEFLATED = 8; + #endregion + #region Local Constants + private const int IS_SETDICT = 0x01; + private const int IS_FLUSHING = 0x04; + private const int IS_FINISHING = 0x08; + + private const int INIT_STATE = 0x00; + private const int SETDICT_STATE = 0x01; + // private static int INIT_FINISHING_STATE = 0x08; + // private static int SETDICT_FINISHING_STATE = 0x09; + private const int BUSY_STATE = 0x10; + private const int FLUSHING_STATE = 0x14; + private const int FINISHING_STATE = 0x1c; + private const int FINISHED_STATE = 0x1e; + private const int CLOSED_STATE = 0x7f; + #endregion + #region Constructors + /// + /// Creates a new deflater with default compression level. + /// + public Deflater() : this(DEFAULT_COMPRESSION, false) + { + + } + + /// + /// Creates a new deflater with given compression level. + /// + /// + /// the compression level, a value between NO_COMPRESSION + /// and BEST_COMPRESSION, or DEFAULT_COMPRESSION. + /// + /// if lvl is out of range. + public Deflater(int level) : this(level, false) + { + + } + + /// + /// Creates a new deflater with given compression level. + /// + /// + /// the compression level, a value between NO_COMPRESSION + /// and BEST_COMPRESSION. + /// + /// + /// true, if we should suppress the Zlib/RFC1950 header at the + /// beginning and the adler checksum at the end of the output. This is + /// useful for the GZIP/PKZIP formats. + /// + /// if lvl is out of range. + public Deflater(int level, bool noZlibHeaderOrFooter) + { + if (level == DEFAULT_COMPRESSION) { + level = 6; + } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { + throw new ArgumentOutOfRangeException("level"); + } + + pending = new DeflaterPending(); + engine = new DeflaterEngine(pending); + this.noZlibHeaderOrFooter = noZlibHeaderOrFooter; + SetStrategy(DeflateStrategy.Default); + SetLevel(level); + Reset(); + } + #endregion + + /// + /// Resets the deflater. The deflater acts afterwards as if it was + /// just created with the same compression level and strategy as it + /// had before. + /// + public void Reset() + { + state = (noZlibHeaderOrFooter ? BUSY_STATE : INIT_STATE); + totalOut = 0; + pending.Reset(); + engine.Reset(); + } + + /// + /// Gets the current adler checksum of the data that was processed so far. + /// + public int Adler { + get { + return engine.Adler; + } + } + + /// + /// Gets the number of input bytes processed so far. + /// + public long TotalIn { + get { + return engine.TotalIn; + } + } + + /// + /// Gets the number of output bytes so far. + /// + public long TotalOut { + get { + return totalOut; + } + } + + /// + /// Flushes the current input block. Further calls to deflate() will + /// produce enough output to inflate everything in the current input + /// block. This is not part of Sun's JDK so I have made it package + /// private. It is used by DeflaterOutputStream to implement + /// flush(). + /// + public void Flush() + { + state |= IS_FLUSHING; + } + + /// + /// Finishes the deflater with the current input block. It is an error + /// to give more input after this method was called. This method must + /// be called to force all bytes to be flushed. + /// + public void Finish() + { + state |= (IS_FLUSHING | IS_FINISHING); + } + + /// + /// Returns true if the stream was finished and no more output bytes + /// are available. + /// + public bool IsFinished { + get { + return (state == FINISHED_STATE) && pending.IsFlushed; + } + } + + /// + /// Returns true, if the input buffer is empty. + /// You should then call setInput(). + /// NOTE: This method can also return true when the stream + /// was finished. + /// + public bool IsNeedingInput { + get { + return engine.NeedsInput(); + } + } + + /// + /// Sets the data which should be compressed next. This should be only + /// called when needsInput indicates that more input is needed. + /// If you call setInput when needsInput() returns false, the + /// previous input that is still pending will be thrown away. + /// The given byte array should not be changed, before needsInput() returns + /// true again. + /// This call is equivalent to setInput(input, 0, input.length). + /// + /// + /// the buffer containing the input data. + /// + /// + /// if the buffer was finished() or ended(). + /// + public void SetInput(byte[] input) + { + SetInput(input, 0, input.Length); + } + + /// + /// Sets the data which should be compressed next. This should be + /// only called when needsInput indicates that more input is needed. + /// The given byte array should not be changed, before needsInput() returns + /// true again. + /// + /// + /// the buffer containing the input data. + /// + /// + /// the start of the data. + /// + /// + /// the number of data bytes of input. + /// + /// + /// if the buffer was Finish()ed or if previous input is still pending. + /// + public void SetInput(byte[] input, int offset, int count) + { + if ((state & IS_FINISHING) != 0) { + throw new InvalidOperationException("Finish() already called"); + } + engine.SetInput(input, offset, count); + } + + /// + /// Sets the compression level. There is no guarantee of the exact + /// position of the change, but if you call this when needsInput is + /// true the change of compression level will occur somewhere near + /// before the end of the so far given input. + /// + /// + /// the new compression level. + /// + public void SetLevel(int level) + { + if (level == DEFAULT_COMPRESSION) { + level = 6; + } else if (level < NO_COMPRESSION || level > BEST_COMPRESSION) { + throw new ArgumentOutOfRangeException("level"); + } + + if (this.level != level) { + this.level = level; + engine.SetLevel(level); + } + } + + /// + /// Get current compression level + /// + /// Returns the current compression level + public int GetLevel() { + return level; + } + + /// + /// Sets the compression strategy. Strategy is one of + /// DEFAULT_STRATEGY, HUFFMAN_ONLY and FILTERED. For the exact + /// position where the strategy is changed, the same as for + /// SetLevel() applies. + /// + /// + /// The new compression strategy. + /// + public void SetStrategy(DeflateStrategy strategy) + { + engine.Strategy = strategy; + } + + /// + /// Deflates the current input block with to the given array. + /// + /// + /// The buffer where compressed data is stored + /// + /// + /// The number of compressed bytes added to the output, or 0 if either + /// IsNeedingInput() or IsFinished returns true or length is zero. + /// + public int Deflate(byte[] output) + { + return Deflate(output, 0, output.Length); + } + + /// + /// Deflates the current input block to the given array. + /// + /// + /// Buffer to store the compressed data. + /// + /// + /// Offset into the output array. + /// + /// + /// The maximum number of bytes that may be stored. + /// + /// + /// The number of compressed bytes added to the output, or 0 if either + /// needsInput() or finished() returns true or length is zero. + /// + /// + /// If Finish() was previously called. + /// + /// + /// If offset or length don't match the array length. + /// + public int Deflate(byte[] output, int offset, int length) + { + int origLength = length; + + if (state == CLOSED_STATE) { + throw new InvalidOperationException("Deflater closed"); + } + + if (state < BUSY_STATE) { + // output header + int header = (DEFLATED + + ((DeflaterConstants.MAX_WBITS - 8) << 4)) << 8; + int level_flags = (level - 1) >> 1; + if (level_flags < 0 || level_flags > 3) { + level_flags = 3; + } + header |= level_flags << 6; + if ((state & IS_SETDICT) != 0) { + // Dictionary was set + header |= DeflaterConstants.PRESET_DICT; + } + header += 31 - (header % 31); + + pending.WriteShortMSB(header); + if ((state & IS_SETDICT) != 0) { + int chksum = engine.Adler; + engine.ResetAdler(); + pending.WriteShortMSB(chksum >> 16); + pending.WriteShortMSB(chksum & 0xffff); + } + + state = BUSY_STATE | (state & (IS_FLUSHING | IS_FINISHING)); + } + + for (;;) { + int count = pending.Flush(output, offset, length); + offset += count; + totalOut += count; + length -= count; + + if (length == 0 || state == FINISHED_STATE) { + break; + } + + if (!engine.Deflate((state & IS_FLUSHING) != 0, (state & IS_FINISHING) != 0)) { + if (state == BUSY_STATE) { + // We need more input now + return origLength - length; + } else if (state == FLUSHING_STATE) { + if (level != NO_COMPRESSION) { + /* We have to supply some lookahead. 8 bit lookahead + * is needed by the zlib inflater, and we must fill + * the next byte, so that all bits are flushed. + */ + int neededbits = 8 + ((-pending.BitCount) & 7); + while (neededbits > 0) { + /* write a static tree block consisting solely of + * an EOF: + */ + pending.WriteBits(2, 10); + neededbits -= 10; + } + } + state = BUSY_STATE; + } else if (state == FINISHING_STATE) { + pending.AlignToByte(); - // Compressed data is complete. Write footer information if required. - if (!noZlibHeaderOrFooter) { - int adler = engine.Adler; - pending.WriteShortMSB(adler >> 16); - pending.WriteShortMSB(adler & 0xffff); - } - state = FINISHED_STATE; - } - } - } - return origLength - length; - } - - /// - /// Sets the dictionary which should be used in the deflate process. - /// This call is equivalent to setDictionary(dict, 0, dict.Length). - /// - /// - /// the dictionary. - /// - /// - /// if SetInput () or Deflate () were already called or another dictionary was already set. - /// - public void SetDictionary(byte[] dictionary) - { - SetDictionary(dictionary, 0, dictionary.Length); - } - - /// - /// Sets the dictionary which should be used in the deflate process. - /// The dictionary is a byte array containing strings that are - /// likely to occur in the data which should be compressed. The - /// dictionary is not stored in the compressed output, only a - /// checksum. To decompress the output you need to supply the same - /// dictionary again. - /// - /// - /// The dictionary data - /// - /// - /// The index where dictionary information commences. - /// - /// - /// The number of bytes in the dictionary. - /// - /// - /// If SetInput () or Deflate() were already called or another dictionary was already set. - /// - public void SetDictionary(byte[] dictionary, int index, int count) - { - if (state != INIT_STATE) { - throw new InvalidOperationException(); - } - - state = SETDICT_STATE; - engine.SetDictionary(dictionary, index, count); - } + // Compressed data is complete. Write footer information if required. + if (!noZlibHeaderOrFooter) { + int adler = engine.Adler; + pending.WriteShortMSB(adler >> 16); + pending.WriteShortMSB(adler & 0xffff); + } + state = FINISHED_STATE; + } + } + } + return origLength - length; + } + + /// + /// Sets the dictionary which should be used in the deflate process. + /// This call is equivalent to setDictionary(dict, 0, dict.Length). + /// + /// + /// the dictionary. + /// + /// + /// if SetInput () or Deflate () were already called or another dictionary was already set. + /// + public void SetDictionary(byte[] dictionary) + { + SetDictionary(dictionary, 0, dictionary.Length); + } + + /// + /// Sets the dictionary which should be used in the deflate process. + /// The dictionary is a byte array containing strings that are + /// likely to occur in the data which should be compressed. The + /// dictionary is not stored in the compressed output, only a + /// checksum. To decompress the output you need to supply the same + /// dictionary again. + /// + /// + /// The dictionary data + /// + /// + /// The index where dictionary information commences. + /// + /// + /// The number of bytes in the dictionary. + /// + /// + /// If SetInput () or Deflate() were already called or another dictionary was already set. + /// + public void SetDictionary(byte[] dictionary, int index, int count) + { + if (state != INIT_STATE) { + throw new InvalidOperationException(); + } + + state = SETDICT_STATE; + engine.SetDictionary(dictionary, index, count); + } - #region Instance Fields - /// - /// Compression level. - /// - int level; - - /// - /// If true no Zlib/RFC1950 headers or footers are generated - /// - bool noZlibHeaderOrFooter; - - /// - /// The current state. - /// - int state; - - /// - /// The total bytes of output written. - /// - long totalOut; - - /// - /// The pending output. - /// - DeflaterPending pending; - - /// - /// The deflater engine. - /// - DeflaterEngine engine; - #endregion - } + #region Instance Fields + /// + /// Compression level. + /// + int level; + + /// + /// If true no Zlib/RFC1950 headers or footers are generated + /// + bool noZlibHeaderOrFooter; + + /// + /// The current state. + /// + int state; + + /// + /// The total bytes of output written. + /// + long totalOut; + + /// + /// The pending output. + /// + DeflaterPending pending; + + /// + /// The deflater engine. + /// + DeflaterEngine engine; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterConstants.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterConstants.cs index a973db2c0b..fee602c200 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterConstants.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterConstants.cs @@ -41,146 +41,146 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - - /// - /// This class contains constants used for deflation. - /// - public class DeflaterConstants - { - /// - /// Set to true to enable debugging - /// - public const bool DEBUGGING = false; - - /// - /// Written to Zip file to identify a stored block - /// - public const int STORED_BLOCK = 0; - - /// - /// Identifies static tree in Zip file - /// - public const int STATIC_TREES = 1; - - /// - /// Identifies dynamic tree in Zip file - /// - public const int DYN_TREES = 2; - - /// - /// Header flag indicating a preset dictionary for deflation - /// - public const int PRESET_DICT = 0x20; - - /// - /// Sets internal buffer sizes for Huffman encoding - /// - public const int DEFAULT_MEM_LEVEL = 8; + + /// + /// This class contains constants used for deflation. + /// + public class DeflaterConstants + { + /// + /// Set to true to enable debugging + /// + public const bool DEBUGGING = false; + + /// + /// Written to Zip file to identify a stored block + /// + public const int STORED_BLOCK = 0; + + /// + /// Identifies static tree in Zip file + /// + public const int STATIC_TREES = 1; + + /// + /// Identifies dynamic tree in Zip file + /// + public const int DYN_TREES = 2; + + /// + /// Header flag indicating a preset dictionary for deflation + /// + public const int PRESET_DICT = 0x20; + + /// + /// Sets internal buffer sizes for Huffman encoding + /// + public const int DEFAULT_MEM_LEVEL = 8; - /// - /// Internal compression engine constant - /// - public const int MAX_MATCH = 258; - - /// - /// Internal compression engine constant - /// - public const int MIN_MATCH = 3; - - /// - /// Internal compression engine constant - /// - public const int MAX_WBITS = 15; - - /// - /// Internal compression engine constant - /// - public const int WSIZE = 1 << MAX_WBITS; - - /// - /// Internal compression engine constant - /// - public const int WMASK = WSIZE - 1; - - /// - /// Internal compression engine constant - /// - public const int HASH_BITS = DEFAULT_MEM_LEVEL + 7; - - /// - /// Internal compression engine constant - /// - public const int HASH_SIZE = 1 << HASH_BITS; - - /// - /// Internal compression engine constant - /// - public const int HASH_MASK = HASH_SIZE - 1; - - /// - /// Internal compression engine constant - /// - public const int HASH_SHIFT = (HASH_BITS + MIN_MATCH - 1) / MIN_MATCH; - - /// - /// Internal compression engine constant - /// - public const int MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; - - /// - /// Internal compression engine constant - /// - public const int MAX_DIST = WSIZE - MIN_LOOKAHEAD; - - /// - /// Internal compression engine constant - /// - public const int PENDING_BUF_SIZE = 1 << (DEFAULT_MEM_LEVEL + 8); - - /// - /// Internal compression engine constant - /// - public static int MAX_BLOCK_SIZE = Math.Min(65535, PENDING_BUF_SIZE - 5); - - /// - /// Internal compression engine constant - /// - public const int DEFLATE_STORED = 0; - - /// - /// Internal compression engine constant - /// - public const int DEFLATE_FAST = 1; - - /// - /// Internal compression engine constant - /// - public const int DEFLATE_SLOW = 2; - - /// - /// Internal compression engine constant - /// - public static int[] GOOD_LENGTH = { 0, 4, 4, 4, 4, 8, 8, 8, 32, 32 }; - - /// - /// Internal compression engine constant - /// - public static int[] MAX_LAZY = { 0, 4, 5, 6, 4, 16, 16, 32, 128, 258 }; - - /// - /// Internal compression engine constant - /// - public static int[] NICE_LENGTH = { 0, 8, 16, 32, 16, 32, 128, 128, 258, 258 }; - - /// - /// Internal compression engine constant - /// - public static int[] MAX_CHAIN = { 0, 4, 8, 32, 16, 32, 128, 256, 1024, 4096 }; - - /// - /// Internal compression engine constant - /// - public static int[] COMPR_FUNC = { 0, 1, 1, 1, 1, 2, 2, 2, 2, 2 }; - - } + /// + /// Internal compression engine constant + /// + public const int MAX_MATCH = 258; + + /// + /// Internal compression engine constant + /// + public const int MIN_MATCH = 3; + + /// + /// Internal compression engine constant + /// + public const int MAX_WBITS = 15; + + /// + /// Internal compression engine constant + /// + public const int WSIZE = 1 << MAX_WBITS; + + /// + /// Internal compression engine constant + /// + public const int WMASK = WSIZE - 1; + + /// + /// Internal compression engine constant + /// + public const int HASH_BITS = DEFAULT_MEM_LEVEL + 7; + + /// + /// Internal compression engine constant + /// + public const int HASH_SIZE = 1 << HASH_BITS; + + /// + /// Internal compression engine constant + /// + public const int HASH_MASK = HASH_SIZE - 1; + + /// + /// Internal compression engine constant + /// + public const int HASH_SHIFT = (HASH_BITS + MIN_MATCH - 1) / MIN_MATCH; + + /// + /// Internal compression engine constant + /// + public const int MIN_LOOKAHEAD = MAX_MATCH + MIN_MATCH + 1; + + /// + /// Internal compression engine constant + /// + public const int MAX_DIST = WSIZE - MIN_LOOKAHEAD; + + /// + /// Internal compression engine constant + /// + public const int PENDING_BUF_SIZE = 1 << (DEFAULT_MEM_LEVEL + 8); + + /// + /// Internal compression engine constant + /// + public static int MAX_BLOCK_SIZE = Math.Min(65535, PENDING_BUF_SIZE - 5); + + /// + /// Internal compression engine constant + /// + public const int DEFLATE_STORED = 0; + + /// + /// Internal compression engine constant + /// + public const int DEFLATE_FAST = 1; + + /// + /// Internal compression engine constant + /// + public const int DEFLATE_SLOW = 2; + + /// + /// Internal compression engine constant + /// + public static int[] GOOD_LENGTH = { 0, 4, 4, 4, 4, 8, 8, 8, 32, 32 }; + + /// + /// Internal compression engine constant + /// + public static int[] MAX_LAZY = { 0, 4, 5, 6, 4, 16, 16, 32, 128, 258 }; + + /// + /// Internal compression engine constant + /// + public static int[] NICE_LENGTH = { 0, 8, 16, 32, 16, 32, 128, 128, 258, 258 }; + + /// + /// Internal compression engine constant + /// + public static int[] MAX_CHAIN = { 0, 4, 8, 32, 16, 32, 128, 256, 1024, 4096 }; + + /// + /// Internal compression engine constant + /// + public static int[] COMPR_FUNC = { 0, 1, 1, 1, 1, 2, 2, 2, 2, 2 }; + + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterEngine.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterEngine.cs index 3cbb5aa2a0..0aced7df4d 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterEngine.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterEngine.cs @@ -43,827 +43,827 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - - /// - /// Strategies for deflater - /// - public enum DeflateStrategy - { - /// - /// The default strategy - /// - Default = 0, - - /// - /// This strategy will only allow longer string repetitions. It is - /// useful for random data with a small character set. - /// - Filtered = 1, - - - /// - /// This strategy will not look for string repetitions at all. It - /// only encodes with Huffman trees (which means, that more common - /// characters get a smaller encoding. - /// - HuffmanOnly = 2 - } - - // DEFLATE ALGORITHM: - // - // The uncompressed stream is inserted into the window array. When - // the window array is full the first half is thrown away and the - // second half is copied to the beginning. - // - // The head array is a hash table. Three characters build a hash value - // and they the value points to the corresponding index in window of - // the last string with this hash. The prev array implements a - // linked list of matches with the same hash: prev[index & WMASK] points - // to the previous index with the same hash. - // - - - /// - /// Low level compression engine for deflate algorithm which uses a 32K sliding window - /// with secondary compression from Huffman/Shannon-Fano codes. - /// - public class DeflaterEngine : DeflaterConstants - { - #region Constants - const int TooFar = 4096; - #endregion - - #region Constructors - /// - /// Construct instance with pending buffer - /// - /// - /// Pending buffer to use - /// > - public DeflaterEngine(DeflaterPending pending) - { - this.pending = pending; - huffman = new DeflaterHuffman(pending); - adler = new Adler32(); - - window = new byte[2 * WSIZE]; - head = new short[HASH_SIZE]; - prev = new short[WSIZE]; - - // We start at index 1, to avoid an implementation deficiency, that - // we cannot build a repeat pattern at index 0. - blockStart = strstart = 1; - } - - #endregion - - /// - /// Deflate drives actual compression of data - /// - /// True to flush input buffers - /// Finish deflation with the current input. - /// Returns true if progress has been made. - public bool Deflate(bool flush, bool finish) - { - bool progress; - do - { - FillWindow(); - bool canFlush = flush && (inputOff == inputEnd); + + /// + /// Strategies for deflater + /// + public enum DeflateStrategy + { + /// + /// The default strategy + /// + Default = 0, + + /// + /// This strategy will only allow longer string repetitions. It is + /// useful for random data with a small character set. + /// + Filtered = 1, + + + /// + /// This strategy will not look for string repetitions at all. It + /// only encodes with Huffman trees (which means, that more common + /// characters get a smaller encoding. + /// + HuffmanOnly = 2 + } + + // DEFLATE ALGORITHM: + // + // The uncompressed stream is inserted into the window array. When + // the window array is full the first half is thrown away and the + // second half is copied to the beginning. + // + // The head array is a hash table. Three characters build a hash value + // and they the value points to the corresponding index in window of + // the last string with this hash. The prev array implements a + // linked list of matches with the same hash: prev[index & WMASK] points + // to the previous index with the same hash. + // + + + /// + /// Low level compression engine for deflate algorithm which uses a 32K sliding window + /// with secondary compression from Huffman/Shannon-Fano codes. + /// + public class DeflaterEngine : DeflaterConstants + { + #region Constants + const int TooFar = 4096; + #endregion + + #region Constructors + /// + /// Construct instance with pending buffer + /// + /// + /// Pending buffer to use + /// > + public DeflaterEngine(DeflaterPending pending) + { + this.pending = pending; + huffman = new DeflaterHuffman(pending); + adler = new Adler32(); + + window = new byte[2 * WSIZE]; + head = new short[HASH_SIZE]; + prev = new short[WSIZE]; + + // We start at index 1, to avoid an implementation deficiency, that + // we cannot build a repeat pattern at index 0. + blockStart = strstart = 1; + } + + #endregion + + /// + /// Deflate drives actual compression of data + /// + /// True to flush input buffers + /// Finish deflation with the current input. + /// Returns true if progress has been made. + public bool Deflate(bool flush, bool finish) + { + bool progress; + do + { + FillWindow(); + bool canFlush = flush && (inputOff == inputEnd); #if DebugDeflation - if (DeflaterConstants.DEBUGGING) { - Console.WriteLine("window: [" + blockStart + "," + strstart + "," - + lookahead + "], " + compressionFunction + "," + canFlush); - } + if (DeflaterConstants.DEBUGGING) { + Console.WriteLine("window: [" + blockStart + "," + strstart + "," + + lookahead + "], " + compressionFunction + "," + canFlush); + } #endif - switch (compressionFunction) - { - case DEFLATE_STORED: - progress = DeflateStored(canFlush, finish); - break; - case DEFLATE_FAST: - progress = DeflateFast(canFlush, finish); - break; - case DEFLATE_SLOW: - progress = DeflateSlow(canFlush, finish); - break; - default: - throw new InvalidOperationException("unknown compressionFunction"); - } - } while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made - return progress; - } - - /// - /// Sets input data to be deflated. Should only be called when NeedsInput() - /// returns true - /// - /// The buffer containing input data. - /// The offset of the first byte of data. - /// The number of bytes of data to use as input. - public void SetInput(byte[] buffer, int offset, int count) - { - if ( buffer == null ) - { - throw new ArgumentNullException("buffer"); - } - - if ( offset < 0 ) - { - throw new ArgumentOutOfRangeException("offset"); - } - - if ( count < 0 ) - { - throw new ArgumentOutOfRangeException("count"); - } - - if (inputOff < inputEnd) - { - throw new InvalidOperationException("Old input was not completely processed"); - } - - int end = offset + count; - - /* We want to throw an ArrayIndexOutOfBoundsException early. The - * check is very tricky: it also handles integer wrap around. - */ - if ((offset > end) || (end > buffer.Length) ) - { - throw new ArgumentOutOfRangeException("count"); - } - - inputBuf = buffer; - inputOff = offset; - inputEnd = end; - } - - /// - /// Determines if more input is needed. - /// - /// Return true if input is needed via SetInput - public bool NeedsInput() - { - return (inputEnd == inputOff); - } - - /// - /// Set compression dictionary - /// - /// The buffer containing the dictionary data - /// The offset in the buffer for the first byte of data - /// The length of the dictionary data. - public void SetDictionary(byte[] buffer, int offset, int length) - { + switch (compressionFunction) + { + case DEFLATE_STORED: + progress = DeflateStored(canFlush, finish); + break; + case DEFLATE_FAST: + progress = DeflateFast(canFlush, finish); + break; + case DEFLATE_SLOW: + progress = DeflateSlow(canFlush, finish); + break; + default: + throw new InvalidOperationException("unknown compressionFunction"); + } + } while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made + return progress; + } + + /// + /// Sets input data to be deflated. Should only be called when NeedsInput() + /// returns true + /// + /// The buffer containing input data. + /// The offset of the first byte of data. + /// The number of bytes of data to use as input. + public void SetInput(byte[] buffer, int offset, int count) + { + if ( buffer == null ) + { + throw new ArgumentNullException("buffer"); + } + + if ( offset < 0 ) + { + throw new ArgumentOutOfRangeException("offset"); + } + + if ( count < 0 ) + { + throw new ArgumentOutOfRangeException("count"); + } + + if (inputOff < inputEnd) + { + throw new InvalidOperationException("Old input was not completely processed"); + } + + int end = offset + count; + + /* We want to throw an ArrayIndexOutOfBoundsException early. The + * check is very tricky: it also handles integer wrap around. + */ + if ((offset > end) || (end > buffer.Length) ) + { + throw new ArgumentOutOfRangeException("count"); + } + + inputBuf = buffer; + inputOff = offset; + inputEnd = end; + } + + /// + /// Determines if more input is needed. + /// + /// Return true if input is needed via SetInput + public bool NeedsInput() + { + return (inputEnd == inputOff); + } + + /// + /// Set compression dictionary + /// + /// The buffer containing the dictionary data + /// The offset in the buffer for the first byte of data + /// The length of the dictionary data. + public void SetDictionary(byte[] buffer, int offset, int length) + { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (strstart != 1) ) - { - throw new InvalidOperationException("strstart not 1"); - } + if (DeflaterConstants.DEBUGGING && (strstart != 1) ) + { + throw new InvalidOperationException("strstart not 1"); + } #endif - adler.Update(buffer, offset, length); - if (length < MIN_MATCH) - { - return; - } - - if (length > MAX_DIST) - { - offset += length - MAX_DIST; - length = MAX_DIST; - } - - System.Array.Copy(buffer, offset, window, strstart, length); - - UpdateHash(); - --length; - while (--length > 0) - { - InsertString(); - strstart++; - } - strstart += 2; - blockStart = strstart; - } - - /// - /// Reset internal state - /// - public void Reset() - { - huffman.Reset(); - adler.Reset(); - blockStart = strstart = 1; - lookahead = 0; - totalIn = 0; - prevAvailable = false; - matchLen = MIN_MATCH - 1; - - for (int i = 0; i < HASH_SIZE; i++) { - head[i] = 0; - } - - for (int i = 0; i < WSIZE; i++) { - prev[i] = 0; - } - } - - /// - /// Reset Adler checksum - /// - public void ResetAdler() - { - adler.Reset(); - } - - /// - /// Get current value of Adler checksum - /// - public int Adler { - get { - return unchecked((int)adler.Value); - } - } - - /// - /// Total data processed - /// - public long TotalIn { - get { - return totalIn; - } - } - - /// - /// Get/set the deflate strategy - /// - public DeflateStrategy Strategy { - get { - return strategy; - } - set { - strategy = value; - } - } - - /// - /// Set the deflate level (0-9) - /// - /// The value to set the level to. - public void SetLevel(int level) - { - if ( (level < 0) || (level > 9) ) - { - throw new ArgumentOutOfRangeException("level"); - } - - goodLength = DeflaterConstants.GOOD_LENGTH[level]; - max_lazy = DeflaterConstants.MAX_LAZY[level]; - niceLength = DeflaterConstants.NICE_LENGTH[level]; - max_chain = DeflaterConstants.MAX_CHAIN[level]; - - if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction) { + adler.Update(buffer, offset, length); + if (length < MIN_MATCH) + { + return; + } + + if (length > MAX_DIST) + { + offset += length - MAX_DIST; + length = MAX_DIST; + } + + System.Array.Copy(buffer, offset, window, strstart, length); + + UpdateHash(); + --length; + while (--length > 0) + { + InsertString(); + strstart++; + } + strstart += 2; + blockStart = strstart; + } + + /// + /// Reset internal state + /// + public void Reset() + { + huffman.Reset(); + adler.Reset(); + blockStart = strstart = 1; + lookahead = 0; + totalIn = 0; + prevAvailable = false; + matchLen = MIN_MATCH - 1; + + for (int i = 0; i < HASH_SIZE; i++) { + head[i] = 0; + } + + for (int i = 0; i < WSIZE; i++) { + prev[i] = 0; + } + } + + /// + /// Reset Adler checksum + /// + public void ResetAdler() + { + adler.Reset(); + } + + /// + /// Get current value of Adler checksum + /// + public int Adler { + get { + return unchecked((int)adler.Value); + } + } + + /// + /// Total data processed + /// + public long TotalIn { + get { + return totalIn; + } + } + + /// + /// Get/set the deflate strategy + /// + public DeflateStrategy Strategy { + get { + return strategy; + } + set { + strategy = value; + } + } + + /// + /// Set the deflate level (0-9) + /// + /// The value to set the level to. + public void SetLevel(int level) + { + if ( (level < 0) || (level > 9) ) + { + throw new ArgumentOutOfRangeException("level"); + } + + goodLength = DeflaterConstants.GOOD_LENGTH[level]; + max_lazy = DeflaterConstants.MAX_LAZY[level]; + niceLength = DeflaterConstants.NICE_LENGTH[level]; + max_chain = DeflaterConstants.MAX_CHAIN[level]; + + if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction) { #if DebugDeflation - if (DeflaterConstants.DEBUGGING) { - Console.WriteLine("Change from " + compressionFunction + " to " - + DeflaterConstants.COMPR_FUNC[level]); - } + if (DeflaterConstants.DEBUGGING) { + Console.WriteLine("Change from " + compressionFunction + " to " + + DeflaterConstants.COMPR_FUNC[level]); + } #endif - switch (compressionFunction) { - case DEFLATE_STORED: - if (strstart > blockStart) { - huffman.FlushStoredBlock(window, blockStart, - strstart - blockStart, false); - blockStart = strstart; - } - UpdateHash(); - break; - - case DEFLATE_FAST: - if (strstart > blockStart) { - huffman.FlushBlock(window, blockStart, strstart - blockStart, - false); - blockStart = strstart; - } - break; - - case DEFLATE_SLOW: - if (prevAvailable) { - huffman.TallyLit(window[strstart-1] & 0xff); - } - if (strstart > blockStart) { - huffman.FlushBlock(window, blockStart, strstart - blockStart, false); - blockStart = strstart; - } - prevAvailable = false; - matchLen = MIN_MATCH - 1; - break; - } - compressionFunction = COMPR_FUNC[level]; - } - } - - /// - /// Fill the window - /// - public void FillWindow() - { - /* If the window is almost full and there is insufficient lookahead, - * move the upper half to the lower one to make room in the upper half. - */ - if (strstart >= WSIZE + MAX_DIST) - { - SlideWindow(); - } - - /* If there is not enough lookahead, but still some input left, - * read in the input - */ - while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd) - { - int more = 2 * WSIZE - lookahead - strstart; - - if (more > inputEnd - inputOff) - { - more = inputEnd - inputOff; - } - - System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more); - adler.Update(inputBuf, inputOff, more); - - inputOff += more; - totalIn += more; - lookahead += more; - } - - if (lookahead >= MIN_MATCH) - { - UpdateHash(); - } - } - - void UpdateHash() - { + switch (compressionFunction) { + case DEFLATE_STORED: + if (strstart > blockStart) { + huffman.FlushStoredBlock(window, blockStart, + strstart - blockStart, false); + blockStart = strstart; + } + UpdateHash(); + break; + + case DEFLATE_FAST: + if (strstart > blockStart) { + huffman.FlushBlock(window, blockStart, strstart - blockStart, + false); + blockStart = strstart; + } + break; + + case DEFLATE_SLOW: + if (prevAvailable) { + huffman.TallyLit(window[strstart-1] & 0xff); + } + if (strstart > blockStart) { + huffman.FlushBlock(window, blockStart, strstart - blockStart, false); + blockStart = strstart; + } + prevAvailable = false; + matchLen = MIN_MATCH - 1; + break; + } + compressionFunction = COMPR_FUNC[level]; + } + } + + /// + /// Fill the window + /// + public void FillWindow() + { + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (strstart >= WSIZE + MAX_DIST) + { + SlideWindow(); + } + + /* If there is not enough lookahead, but still some input left, + * read in the input + */ + while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd) + { + int more = 2 * WSIZE - lookahead - strstart; + + if (more > inputEnd - inputOff) + { + more = inputEnd - inputOff; + } + + System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more); + adler.Update(inputBuf, inputOff, more); + + inputOff += more; + totalIn += more; + lookahead += more; + } + + if (lookahead >= MIN_MATCH) + { + UpdateHash(); + } + } + + void UpdateHash() + { /* - if (DEBUGGING) { - Console.WriteLine("updateHash: "+strstart); - } + if (DEBUGGING) { + Console.WriteLine("updateHash: "+strstart); + } */ - ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1]; - } - - /// - /// Inserts the current string in the head hash and returns the previous - /// value for this hash. - /// - /// The previous hash value - int InsertString() - { - short match; - int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH -1)]) & HASH_MASK; + ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1]; + } + + /// + /// Inserts the current string in the head hash and returns the previous + /// value for this hash. + /// + /// The previous hash value + int InsertString() + { + short match; + int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH -1)]) & HASH_MASK; #if DebugDeflation - if (DeflaterConstants.DEBUGGING) - { - if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^ - (window[strstart + 1] << HASH_SHIFT) ^ - (window[strstart + 2])) & HASH_MASK)) { - throw new SharpZipBaseException("hash inconsistent: " + hash + "/" - +window[strstart] + "," - +window[strstart + 1] + "," - +window[strstart + 2] + "," + HASH_SHIFT); - } - } + if (DeflaterConstants.DEBUGGING) + { + if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^ + (window[strstart + 1] << HASH_SHIFT) ^ + (window[strstart + 2])) & HASH_MASK)) { + throw new SharpZipBaseException("hash inconsistent: " + hash + "/" + +window[strstart] + "," + +window[strstart + 1] + "," + +window[strstart + 2] + "," + HASH_SHIFT); + } + } #endif - prev[strstart & WMASK] = match = head[hash]; - head[hash] = unchecked((short)strstart); - ins_h = hash; - return match & 0xffff; - } - - void SlideWindow() - { - Array.Copy(window, WSIZE, window, 0, WSIZE); - matchStart -= WSIZE; - strstart -= WSIZE; - blockStart -= WSIZE; - - // Slide the hash table (could be avoided with 32 bit values - // at the expense of memory usage). - for (int i = 0; i < HASH_SIZE; ++i) { - int m = head[i] & 0xffff; - head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); - } - - // Slide the prev table. - for (int i = 0; i < WSIZE; i++) { - int m = prev[i] & 0xffff; - prev[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); - } - } - - /// - /// Find the best (longest) string in the window matching the - /// string starting at strstart. - /// - /// Preconditions: - /// - /// strstart + MAX_MATCH <= window.length. - /// - /// - /// True if a match greater than the minimum length is found - bool FindLongestMatch(int curMatch) - { - int chainLength = this.max_chain; - int niceLength = this.niceLength; - short[] prev = this.prev; - int scan = this.strstart; - int match; - int best_end = this.strstart + matchLen; - int best_len = Math.Max(matchLen, MIN_MATCH - 1); - - int limit = Math.Max(strstart - MAX_DIST, 0); - - int strend = strstart + MAX_MATCH - 1; - byte scan_end1 = window[best_end - 1]; - byte scan_end = window[best_end]; - - // Do not waste too much time if we already have a good match: - if (best_len >= this.goodLength) { - chainLength >>= 2; - } - - /* Do not look for matches beyond the end of the input. This is necessary - * to make deflate deterministic. - */ - if (niceLength > lookahead) { - niceLength = lookahead; - } - + prev[strstart & WMASK] = match = head[hash]; + head[hash] = unchecked((short)strstart); + ins_h = hash; + return match & 0xffff; + } + + void SlideWindow() + { + Array.Copy(window, WSIZE, window, 0, WSIZE); + matchStart -= WSIZE; + strstart -= WSIZE; + blockStart -= WSIZE; + + // Slide the hash table (could be avoided with 32 bit values + // at the expense of memory usage). + for (int i = 0; i < HASH_SIZE; ++i) { + int m = head[i] & 0xffff; + head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); + } + + // Slide the prev table. + for (int i = 0; i < WSIZE; i++) { + int m = prev[i] & 0xffff; + prev[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); + } + } + + /// + /// Find the best (longest) string in the window matching the + /// string starting at strstart. + /// + /// Preconditions: + /// + /// strstart + MAX_MATCH <= window.length. + /// + /// + /// True if a match greater than the minimum length is found + bool FindLongestMatch(int curMatch) + { + int chainLength = this.max_chain; + int niceLength = this.niceLength; + short[] prev = this.prev; + int scan = this.strstart; + int match; + int best_end = this.strstart + matchLen; + int best_len = Math.Max(matchLen, MIN_MATCH - 1); + + int limit = Math.Max(strstart - MAX_DIST, 0); + + int strend = strstart + MAX_MATCH - 1; + byte scan_end1 = window[best_end - 1]; + byte scan_end = window[best_end]; + + // Do not waste too much time if we already have a good match: + if (best_len >= this.goodLength) { + chainLength >>= 2; + } + + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (niceLength > lookahead) { + niceLength = lookahead; + } + #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (strstart > 2 * WSIZE - MIN_LOOKAHEAD)) - { - throw new InvalidOperationException("need lookahead"); - } -#endif - - do { + if (DeflaterConstants.DEBUGGING && (strstart > 2 * WSIZE - MIN_LOOKAHEAD)) + { + throw new InvalidOperationException("need lookahead"); + } +#endif + + do { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (curMatch >= strstart) ) - { - throw new InvalidOperationException("no future"); - } + if (DeflaterConstants.DEBUGGING && (curMatch >= strstart) ) + { + throw new InvalidOperationException("no future"); + } #endif - if (window[curMatch + best_len] != scan_end || - window[curMatch + best_len - 1] != scan_end1 || - window[curMatch] != window[scan] || - window[curMatch + 1] != window[scan + 1]) { - continue; - } - - match = curMatch + 2; - scan += 2; - - /* We check for insufficient lookahead only every 8th comparison; - * the 256th check will be made at strstart + 258. - */ - while ( - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - window[++scan] == window[++match] && - (scan < strend)) - { - // Do nothing - } - - if (scan > best_end) { + if (window[curMatch + best_len] != scan_end || + window[curMatch + best_len - 1] != scan_end1 || + window[curMatch] != window[scan] || + window[curMatch + 1] != window[scan + 1]) { + continue; + } + + match = curMatch + 2; + scan += 2; + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart + 258. + */ + while ( + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + window[++scan] == window[++match] && + (scan < strend)) + { + // Do nothing + } + + if (scan > best_end) { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (ins_h == 0) ) - Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart)); + if (DeflaterConstants.DEBUGGING && (ins_h == 0) ) + Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart)); #endif - matchStart = curMatch; - best_end = scan; - best_len = scan - strstart; - - if (best_len >= niceLength) { - break; - } - - scan_end1 = window[best_end - 1]; - scan_end = window[best_end]; - } - scan = strstart; - } while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit && --chainLength != 0); - - matchLen = Math.Min(best_len, lookahead); - return matchLen >= MIN_MATCH; - } - - bool DeflateStored(bool flush, bool finish) - { - if (!flush && (lookahead == 0)) { - return false; - } - - strstart += lookahead; - lookahead = 0; - - int storedLength = strstart - blockStart; - - if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full - (blockStart < WSIZE && storedLength >= MAX_DIST) || // Block may move out of window - flush) { - bool lastBlock = finish; - if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE) { - storedLength = DeflaterConstants.MAX_BLOCK_SIZE; - lastBlock = false; - } - + matchStart = curMatch; + best_end = scan; + best_len = scan - strstart; + + if (best_len >= niceLength) { + break; + } + + scan_end1 = window[best_end - 1]; + scan_end = window[best_end]; + } + scan = strstart; + } while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit && --chainLength != 0); + + matchLen = Math.Min(best_len, lookahead); + return matchLen >= MIN_MATCH; + } + + bool DeflateStored(bool flush, bool finish) + { + if (!flush && (lookahead == 0)) { + return false; + } + + strstart += lookahead; + lookahead = 0; + + int storedLength = strstart - blockStart; + + if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full + (blockStart < WSIZE && storedLength >= MAX_DIST) || // Block may move out of window + flush) { + bool lastBlock = finish; + if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE) { + storedLength = DeflaterConstants.MAX_BLOCK_SIZE; + lastBlock = false; + } + #if DebugDeflation - if (DeflaterConstants.DEBUGGING) - { - Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]"); - } + if (DeflaterConstants.DEBUGGING) + { + Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]"); + } #endif - huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock); - blockStart += storedLength; - return !lastBlock; - } - return true; - } - - bool DeflateFast(bool flush, bool finish) - { - if (lookahead < MIN_LOOKAHEAD && !flush) { - return false; - } - - while (lookahead >= MIN_LOOKAHEAD || flush) { - if (lookahead == 0) { - // We are flushing everything - huffman.FlushBlock(window, blockStart, strstart - blockStart, finish); - blockStart = strstart; - return false; - } - - if (strstart > 2 * WSIZE - MIN_LOOKAHEAD) { - /* slide window, as FindLongestMatch needs this. - * This should only happen when flushing and the window - * is almost full. - */ - SlideWindow(); - } - - int hashHead; - if (lookahead >= MIN_MATCH && - (hashHead = InsertString()) != 0 && - strategy != DeflateStrategy.HuffmanOnly && - strstart - hashHead <= MAX_DIST && - FindLongestMatch(hashHead)) { - // longestMatch sets matchStart and matchLen + huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock); + blockStart += storedLength; + return !lastBlock; + } + return true; + } + + bool DeflateFast(bool flush, bool finish) + { + if (lookahead < MIN_LOOKAHEAD && !flush) { + return false; + } + + while (lookahead >= MIN_LOOKAHEAD || flush) { + if (lookahead == 0) { + // We are flushing everything + huffman.FlushBlock(window, blockStart, strstart - blockStart, finish); + blockStart = strstart; + return false; + } + + if (strstart > 2 * WSIZE - MIN_LOOKAHEAD) { + /* slide window, as FindLongestMatch needs this. + * This should only happen when flushing and the window + * is almost full. + */ + SlideWindow(); + } + + int hashHead; + if (lookahead >= MIN_MATCH && + (hashHead = InsertString()) != 0 && + strategy != DeflateStrategy.HuffmanOnly && + strstart - hashHead <= MAX_DIST && + FindLongestMatch(hashHead)) { + // longestMatch sets matchStart and matchLen #if DebugDeflation - if (DeflaterConstants.DEBUGGING) - { - for (int i = 0 ; i < matchLen; i++) { - if (window[strstart + i] != window[matchStart + i]) { - throw new SharpZipBaseException("Match failure"); - } - } - } -#endif - - bool full = huffman.TallyDist(strstart - matchStart, matchLen); - - lookahead -= matchLen; - if (matchLen <= max_lazy && lookahead >= MIN_MATCH) { - while (--matchLen > 0) { - ++strstart; - InsertString(); - } - ++strstart; - } else { - strstart += matchLen; - if (lookahead >= MIN_MATCH - 1) { - UpdateHash(); - } - } - matchLen = MIN_MATCH - 1; - if (!full) { - continue; - } - } else { - // No match found - huffman.TallyLit(window[strstart] & 0xff); - ++strstart; - --lookahead; - } - - if (huffman.IsFull()) { - bool lastBlock = finish && (lookahead == 0); - huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock); - blockStart = strstart; - return !lastBlock; - } - } - return true; - } - - bool DeflateSlow(bool flush, bool finish) - { - if (lookahead < MIN_LOOKAHEAD && !flush) { - return false; - } - - while (lookahead >= MIN_LOOKAHEAD || flush) { - if (lookahead == 0) { - if (prevAvailable) { - huffman.TallyLit(window[strstart-1] & 0xff); - } - prevAvailable = false; - - // We are flushing everything + if (DeflaterConstants.DEBUGGING) + { + for (int i = 0 ; i < matchLen; i++) { + if (window[strstart + i] != window[matchStart + i]) { + throw new SharpZipBaseException("Match failure"); + } + } + } +#endif + + bool full = huffman.TallyDist(strstart - matchStart, matchLen); + + lookahead -= matchLen; + if (matchLen <= max_lazy && lookahead >= MIN_MATCH) { + while (--matchLen > 0) { + ++strstart; + InsertString(); + } + ++strstart; + } else { + strstart += matchLen; + if (lookahead >= MIN_MATCH - 1) { + UpdateHash(); + } + } + matchLen = MIN_MATCH - 1; + if (!full) { + continue; + } + } else { + // No match found + huffman.TallyLit(window[strstart] & 0xff); + ++strstart; + --lookahead; + } + + if (huffman.IsFull()) { + bool lastBlock = finish && (lookahead == 0); + huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock); + blockStart = strstart; + return !lastBlock; + } + } + return true; + } + + bool DeflateSlow(bool flush, bool finish) + { + if (lookahead < MIN_LOOKAHEAD && !flush) { + return false; + } + + while (lookahead >= MIN_LOOKAHEAD || flush) { + if (lookahead == 0) { + if (prevAvailable) { + huffman.TallyLit(window[strstart-1] & 0xff); + } + prevAvailable = false; + + // We are flushing everything #if DebugDeflation - if (DeflaterConstants.DEBUGGING && !flush) - { - throw new SharpZipBaseException("Not flushing, but no lookahead"); - } + if (DeflaterConstants.DEBUGGING && !flush) + { + throw new SharpZipBaseException("Not flushing, but no lookahead"); + } #endif - huffman.FlushBlock(window, blockStart, strstart - blockStart, - finish); - blockStart = strstart; - return false; - } - - if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD) { - /* slide window, as FindLongestMatch needs this. - * This should only happen when flushing and the window - * is almost full. - */ - SlideWindow(); - } - - int prevMatch = matchStart; - int prevLen = matchLen; - if (lookahead >= MIN_MATCH) { - - int hashHead = InsertString(); - - if (strategy != DeflateStrategy.HuffmanOnly && - hashHead != 0 && - strstart - hashHead <= MAX_DIST && - FindLongestMatch(hashHead)) { - - // longestMatch sets matchStart and matchLen - - // Discard match if too small and too far away - if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == MIN_MATCH && strstart - matchStart > TooFar))) { - matchLen = MIN_MATCH - 1; - } - } - } - - // previous match was better - if ((prevLen >= MIN_MATCH) && (matchLen <= prevLen) ) { + huffman.FlushBlock(window, blockStart, strstart - blockStart, + finish); + blockStart = strstart; + return false; + } + + if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD) { + /* slide window, as FindLongestMatch needs this. + * This should only happen when flushing and the window + * is almost full. + */ + SlideWindow(); + } + + int prevMatch = matchStart; + int prevLen = matchLen; + if (lookahead >= MIN_MATCH) { + + int hashHead = InsertString(); + + if (strategy != DeflateStrategy.HuffmanOnly && + hashHead != 0 && + strstart - hashHead <= MAX_DIST && + FindLongestMatch(hashHead)) { + + // longestMatch sets matchStart and matchLen + + // Discard match if too small and too far away + if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == MIN_MATCH && strstart - matchStart > TooFar))) { + matchLen = MIN_MATCH - 1; + } + } + } + + // previous match was better + if ((prevLen >= MIN_MATCH) && (matchLen <= prevLen) ) { #if DebugDeflation - if (DeflaterConstants.DEBUGGING) - { - for (int i = 0 ; i < matchLen; i++) { - if (window[strstart-1+i] != window[prevMatch + i]) - throw new SharpZipBaseException(); - } - } + if (DeflaterConstants.DEBUGGING) + { + for (int i = 0 ; i < matchLen; i++) { + if (window[strstart-1+i] != window[prevMatch + i]) + throw new SharpZipBaseException(); + } + } #endif - huffman.TallyDist(strstart - 1 - prevMatch, prevLen); - prevLen -= 2; - do { - strstart++; - lookahead--; - if (lookahead >= MIN_MATCH) { - InsertString(); - } - } while (--prevLen > 0); - - strstart ++; - lookahead--; - prevAvailable = false; - matchLen = MIN_MATCH - 1; - } else { - if (prevAvailable) { - huffman.TallyLit(window[strstart-1] & 0xff); - } - prevAvailable = true; - strstart++; - lookahead--; - } - - if (huffman.IsFull()) { - int len = strstart - blockStart; - if (prevAvailable) { - len--; - } - bool lastBlock = (finish && (lookahead == 0) && !prevAvailable); - huffman.FlushBlock(window, blockStart, len, lastBlock); - blockStart += len; - return !lastBlock; - } - } - return true; - } - - #region Instance Fields - - // Hash index of string to be inserted - int ins_h; - - /// - /// Hashtable, hashing three characters to an index for window, so - /// that window[index]..window[index+2] have this hash code. - /// Note that the array should really be unsigned short, so you need - /// to and the values with 0xffff. - /// - short[] head; - - /// - /// prev[index & WMASK] points to the previous index that has the - /// same hash code as the string starting at index. This way - /// entries with the same hash code are in a linked list. - /// Note that the array should really be unsigned short, so you need - /// to and the values with 0xffff. - /// - short[] prev; - - int matchStart; - // Length of best match - int matchLen; - // Set if previous match exists - bool prevAvailable; - int blockStart; - - /// - /// Points to the current character in the window. - /// - int strstart; - - /// - /// lookahead is the number of characters starting at strstart in - /// window that are valid. - /// So window[strstart] until window[strstart+lookahead-1] are valid - /// characters. - /// - int lookahead; - - /// - /// This array contains the part of the uncompressed stream that - /// is of relevance. The current character is indexed by strstart. - /// - byte[] window; - - DeflateStrategy strategy; - int max_chain, max_lazy, niceLength, goodLength; - - /// - /// The current compression function. - /// - int compressionFunction; - - /// - /// The input data for compression. - /// - byte[] inputBuf; - - /// - /// The total bytes of input read. - /// - long totalIn; - - /// - /// The offset into inputBuf, where input data starts. - /// - int inputOff; - - /// - /// The end offset of the input data. - /// - int inputEnd; - - DeflaterPending pending; - DeflaterHuffman huffman; - - /// - /// The adler checksum - /// - Adler32 adler; - #endregion - } + huffman.TallyDist(strstart - 1 - prevMatch, prevLen); + prevLen -= 2; + do { + strstart++; + lookahead--; + if (lookahead >= MIN_MATCH) { + InsertString(); + } + } while (--prevLen > 0); + + strstart ++; + lookahead--; + prevAvailable = false; + matchLen = MIN_MATCH - 1; + } else { + if (prevAvailable) { + huffman.TallyLit(window[strstart-1] & 0xff); + } + prevAvailable = true; + strstart++; + lookahead--; + } + + if (huffman.IsFull()) { + int len = strstart - blockStart; + if (prevAvailable) { + len--; + } + bool lastBlock = (finish && (lookahead == 0) && !prevAvailable); + huffman.FlushBlock(window, blockStart, len, lastBlock); + blockStart += len; + return !lastBlock; + } + } + return true; + } + + #region Instance Fields + + // Hash index of string to be inserted + int ins_h; + + /// + /// Hashtable, hashing three characters to an index for window, so + /// that window[index]..window[index+2] have this hash code. + /// Note that the array should really be unsigned short, so you need + /// to and the values with 0xffff. + /// + short[] head; + + /// + /// prev[index & WMASK] points to the previous index that has the + /// same hash code as the string starting at index. This way + /// entries with the same hash code are in a linked list. + /// Note that the array should really be unsigned short, so you need + /// to and the values with 0xffff. + /// + short[] prev; + + int matchStart; + // Length of best match + int matchLen; + // Set if previous match exists + bool prevAvailable; + int blockStart; + + /// + /// Points to the current character in the window. + /// + int strstart; + + /// + /// lookahead is the number of characters starting at strstart in + /// window that are valid. + /// So window[strstart] until window[strstart+lookahead-1] are valid + /// characters. + /// + int lookahead; + + /// + /// This array contains the part of the uncompressed stream that + /// is of relevance. The current character is indexed by strstart. + /// + byte[] window; + + DeflateStrategy strategy; + int max_chain, max_lazy, niceLength, goodLength; + + /// + /// The current compression function. + /// + int compressionFunction; + + /// + /// The input data for compression. + /// + byte[] inputBuf; + + /// + /// The total bytes of input read. + /// + long totalIn; + + /// + /// The offset into inputBuf, where input data starts. + /// + int inputOff; + + /// + /// The end offset of the input data. + /// + int inputEnd; + + DeflaterPending pending; + DeflaterHuffman huffman; + + /// + /// The adler checksum + /// + Adler32 adler; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterHuffman.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterHuffman.cs index 8c89e59874..dec6edcd35 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterHuffman.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterHuffman.cs @@ -41,868 +41,868 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - - /// - /// This is the DeflaterHuffman class. - /// - /// This class is not thread safe. This is inherent in the API, due - /// to the split of Deflate and SetInput. - /// - /// author of the original java version : Jochen Hoenicke - /// - public class DeflaterHuffman - { - const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6); - const int LITERAL_NUM = 286; + + /// + /// This is the DeflaterHuffman class. + /// + /// This class is not thread safe. This is inherent in the API, due + /// to the split of Deflate and SetInput. + /// + /// author of the original java version : Jochen Hoenicke + /// + public class DeflaterHuffman + { + const int BUFSIZE = 1 << (DeflaterConstants.DEFAULT_MEM_LEVEL + 6); + const int LITERAL_NUM = 286; - // Number of distance codes - const int DIST_NUM = 30; - // Number of codes used to transfer bit lengths - const int BITLEN_NUM = 19; + // Number of distance codes + const int DIST_NUM = 30; + // Number of codes used to transfer bit lengths + const int BITLEN_NUM = 19; - // repeat previous bit length 3-6 times (2 bits of repeat count) - const int REP_3_6 = 16; - // repeat a zero length 3-10 times (3 bits of repeat count) - const int REP_3_10 = 17; - // repeat a zero length 11-138 times (7 bits of repeat count) - const int REP_11_138 = 18; + // repeat previous bit length 3-6 times (2 bits of repeat count) + const int REP_3_6 = 16; + // repeat a zero length 3-10 times (3 bits of repeat count) + const int REP_3_10 = 17; + // repeat a zero length 11-138 times (7 bits of repeat count) + const int REP_11_138 = 18; - const int EOF_SYMBOL = 256; + const int EOF_SYMBOL = 256; - // The lengths of the bit length codes are sent in order of decreasing - // probability, to avoid transmitting the lengths for unused bit length codes. - static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; - - static readonly byte[] bit4Reverse = { - 0, - 8, - 4, - 12, - 2, - 10, - 6, - 14, - 1, - 9, - 5, - 13, - 3, - 11, - 7, - 15 - }; + // The lengths of the bit length codes are sent in order of decreasing + // probability, to avoid transmitting the lengths for unused bit length codes. + static readonly int[] BL_ORDER = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + + static readonly byte[] bit4Reverse = { + 0, + 8, + 4, + 12, + 2, + 10, + 6, + 14, + 1, + 9, + 5, + 13, + 3, + 11, + 7, + 15 + }; - static short[] staticLCodes; - static byte[] staticLLength; - static short[] staticDCodes; - static byte[] staticDLength; - - class Tree - { - #region Instance Fields - public short[] freqs; - - public byte[] length; - - public int minNumCodes; - - public int numCodes; - - short[] codes; - int[] bl_counts; - int maxLength; - DeflaterHuffman dh; - #endregion + static short[] staticLCodes; + static byte[] staticLLength; + static short[] staticDCodes; + static byte[] staticDLength; + + class Tree + { + #region Instance Fields + public short[] freqs; + + public byte[] length; + + public int minNumCodes; + + public int numCodes; + + short[] codes; + int[] bl_counts; + int maxLength; + DeflaterHuffman dh; + #endregion - #region Constructors - public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength) - { - this.dh = dh; - this.minNumCodes = minCodes; - this.maxLength = maxLength; - freqs = new short[elems]; - bl_counts = new int[maxLength]; - } - - #endregion + #region Constructors + public Tree(DeflaterHuffman dh, int elems, int minCodes, int maxLength) + { + this.dh = dh; + this.minNumCodes = minCodes; + this.maxLength = maxLength; + freqs = new short[elems]; + bl_counts = new int[maxLength]; + } + + #endregion - /// - /// Resets the internal state of the tree - /// - public void Reset() - { - for (int i = 0; i < freqs.Length; i++) { - freqs[i] = 0; - } - codes = null; - length = null; - } - - public void WriteSymbol(int code) - { - // if (DeflaterConstants.DEBUGGING) { - // freqs[code]--; - // // Console.Write("writeSymbol("+freqs.length+","+code+"): "); - // } - dh.pending.WriteBits(codes[code] & 0xffff, length[code]); - } - - /// - /// Check that all frequencies are zero - /// - /// - /// At least one frequency is non-zero - /// - public void CheckEmpty() - { - bool empty = true; - for (int i = 0; i < freqs.Length; i++) { - if (freqs[i] != 0) { - //Console.WriteLine("freqs[" + i + "] == " + freqs[i]); - empty = false; - } - } - - if (!empty) { - throw new SharpZipBaseException("!Empty"); - } - } + /// + /// Resets the internal state of the tree + /// + public void Reset() + { + for (int i = 0; i < freqs.Length; i++) { + freqs[i] = 0; + } + codes = null; + length = null; + } + + public void WriteSymbol(int code) + { + // if (DeflaterConstants.DEBUGGING) { + // freqs[code]--; + // // Console.Write("writeSymbol("+freqs.length+","+code+"): "); + // } + dh.pending.WriteBits(codes[code] & 0xffff, length[code]); + } + + /// + /// Check that all frequencies are zero + /// + /// + /// At least one frequency is non-zero + /// + public void CheckEmpty() + { + bool empty = true; + for (int i = 0; i < freqs.Length; i++) { + if (freqs[i] != 0) { + //Console.WriteLine("freqs[" + i + "] == " + freqs[i]); + empty = false; + } + } + + if (!empty) { + throw new SharpZipBaseException("!Empty"); + } + } - /// - /// Set static codes and length - /// - /// new codes - /// length for new codes - public void SetStaticCodes(short[] staticCodes, byte[] staticLengths) - { - codes = staticCodes; - length = staticLengths; - } - - /// - /// Build dynamic codes and lengths - /// - public void BuildCodes() - { - int numSymbols = freqs.Length; - int[] nextCode = new int[maxLength]; - int code = 0; + /// + /// Set static codes and length + /// + /// new codes + /// length for new codes + public void SetStaticCodes(short[] staticCodes, byte[] staticLengths) + { + codes = staticCodes; + length = staticLengths; + } + + /// + /// Build dynamic codes and lengths + /// + public void BuildCodes() + { + int numSymbols = freqs.Length; + int[] nextCode = new int[maxLength]; + int code = 0; - codes = new short[freqs.Length]; - - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("buildCodes: "+freqs.Length); - // } - - for (int bits = 0; bits < maxLength; bits++) { - nextCode[bits] = code; - code += bl_counts[bits] << (15 - bits); + codes = new short[freqs.Length]; + + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("buildCodes: "+freqs.Length); + // } + + for (int bits = 0; bits < maxLength; bits++) { + nextCode[bits] = code; + code += bl_counts[bits] << (15 - bits); - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits] - // +" nextCode: "+code); - // } - } + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("bits: " + ( bits + 1) + " count: " + bl_counts[bits] + // +" nextCode: "+code); + // } + } #if DebugDeflation - if ( DeflaterConstants.DEBUGGING && (code != 65536) ) - { - throw new SharpZipBaseException("Inconsistent bl_counts!"); - } -#endif - for (int i=0; i < numCodes; i++) { - int bits = length[i]; - if (bits > 0) { + if ( DeflaterConstants.DEBUGGING && (code != 65536) ) + { + throw new SharpZipBaseException("Inconsistent bl_counts!"); + } +#endif + for (int i=0; i < numCodes; i++) { + int bits = length[i]; + if (bits > 0) { - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"), - // +bits); - // } + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("codes["+i+"] = rev(" + nextCode[bits-1]+"), + // +bits); + // } - codes[i] = BitReverse(nextCode[bits-1]); - nextCode[bits-1] += 1 << (16 - bits); - } - } - } - - public void BuildTree() - { - int numSymbols = freqs.Length; - - /* heap is a priority queue, sorted by frequency, least frequent - * nodes first. The heap is a binary tree, with the property, that - * the parent node is smaller than both child nodes. This assures - * that the smallest node is the first parent. - * - * The binary tree is encoded in an array: 0 is root node and - * the nodes 2*n+1, 2*n+2 are the child nodes of node n. - */ - int[] heap = new int[numSymbols]; - int heapLen = 0; - int maxCode = 0; - for (int n = 0; n < numSymbols; n++) { - int freq = freqs[n]; - if (freq != 0) { - // Insert n into heap - int pos = heapLen++; - int ppos; - while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) { - heap[pos] = heap[ppos]; - pos = ppos; - } - heap[pos] = n; - - maxCode = n; - } - } - - /* We could encode a single literal with 0 bits but then we - * don't see the literals. Therefore we force at least two - * literals to avoid this case. We don't care about order in - * this case, both literals get a 1 bit code. - */ - while (heapLen < 2) { - int node = maxCode < 2 ? ++maxCode : 0; - heap[heapLen++] = node; - } - - numCodes = Math.Max(maxCode + 1, minNumCodes); - - int numLeafs = heapLen; - int[] childs = new int[4 * heapLen - 2]; - int[] values = new int[2 * heapLen - 1]; - int numNodes = numLeafs; - for (int i = 0; i < heapLen; i++) { - int node = heap[i]; - childs[2 * i] = node; - childs[2 * i + 1] = -1; - values[i] = freqs[node] << 8; - heap[i] = i; - } - - /* Construct the Huffman tree by repeatedly combining the least two - * frequent nodes. - */ - do { - int first = heap[0]; - int last = heap[--heapLen]; - - // Propagate the hole to the leafs of the heap - int ppos = 0; - int path = 1; - - while (path < heapLen) { - if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { - path++; - } - - heap[ppos] = heap[path]; - ppos = path; - path = path * 2 + 1; - } - - /* Now propagate the last element down along path. Normally - * it shouldn't go too deep. - */ - int lastVal = values[last]; - while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { - heap[path] = heap[ppos]; - } - heap[path] = last; - - - int second = heap[0]; - - // Create a new node father of first and second - last = numNodes++; - childs[2 * last] = first; - childs[2 * last + 1] = second; - int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff); - values[last] = lastVal = values[first] + values[second] - mindepth + 1; - - // Again, propagate the hole to the leafs - ppos = 0; - path = 1; - - while (path < heapLen) { - if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { - path++; - } - - heap[ppos] = heap[path]; - ppos = path; - path = ppos * 2 + 1; - } - - // Now propagate the new element down along path - while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { - heap[path] = heap[ppos]; - } - heap[path] = last; - } while (heapLen > 1); - - if (heap[0] != childs.Length / 2 - 1) { - throw new SharpZipBaseException("Heap invariant violated"); - } - - BuildLength(childs); - } - - /// - /// Get encoded length - /// - /// Encoded length, the sum of frequencies * lengths - public int GetEncodedLength() - { - int len = 0; - for (int i = 0; i < freqs.Length; i++) { - len += freqs[i] * length[i]; - } - return len; - } - - /// - /// Scan a literal or distance tree to determine the frequencies of the codes - /// in the bit length tree. - /// - public void CalcBLFreq(Tree blTree) - { - int max_count; /* max repeat count */ - int min_count; /* min repeat count */ - int count; /* repeat count of the current code */ - int curlen = -1; /* length of current code */ - - int i = 0; - while (i < numCodes) { - count = 1; - int nextlen = length[i]; - if (nextlen == 0) { - max_count = 138; - min_count = 3; - } else { - max_count = 6; - min_count = 3; - if (curlen != nextlen) { - blTree.freqs[nextlen]++; - count = 0; - } - } - curlen = nextlen; - i++; - - while (i < numCodes && curlen == length[i]) { - i++; - if (++count >= max_count) { - break; - } - } - - if (count < min_count) { - blTree.freqs[curlen] += (short)count; - } else if (curlen != 0) { - blTree.freqs[REP_3_6]++; - } else if (count <= 10) { - blTree.freqs[REP_3_10]++; - } else { - blTree.freqs[REP_11_138]++; - } - } - } - - /// - /// Write tree values - /// - /// Tree to write - public void WriteTree(Tree blTree) - { - int max_count; // max repeat count - int min_count; // min repeat count - int count; // repeat count of the current code - int curlen = -1; // length of current code - - int i = 0; - while (i < numCodes) { - count = 1; - int nextlen = length[i]; - if (nextlen == 0) { - max_count = 138; - min_count = 3; - } else { - max_count = 6; - min_count = 3; - if (curlen != nextlen) { - blTree.WriteSymbol(nextlen); - count = 0; - } - } - curlen = nextlen; - i++; - - while (i < numCodes && curlen == length[i]) { - i++; - if (++count >= max_count) { - break; - } - } - - if (count < min_count) { - while (count-- > 0) { - blTree.WriteSymbol(curlen); - } - } else if (curlen != 0) { - blTree.WriteSymbol(REP_3_6); - dh.pending.WriteBits(count - 3, 2); - } else if (count <= 10) { - blTree.WriteSymbol(REP_3_10); - dh.pending.WriteBits(count - 3, 3); - } else { - blTree.WriteSymbol(REP_11_138); - dh.pending.WriteBits(count - 11, 7); - } - } - } + codes[i] = BitReverse(nextCode[bits-1]); + nextCode[bits-1] += 1 << (16 - bits); + } + } + } + + public void BuildTree() + { + int numSymbols = freqs.Length; + + /* heap is a priority queue, sorted by frequency, least frequent + * nodes first. The heap is a binary tree, with the property, that + * the parent node is smaller than both child nodes. This assures + * that the smallest node is the first parent. + * + * The binary tree is encoded in an array: 0 is root node and + * the nodes 2*n+1, 2*n+2 are the child nodes of node n. + */ + int[] heap = new int[numSymbols]; + int heapLen = 0; + int maxCode = 0; + for (int n = 0; n < numSymbols; n++) { + int freq = freqs[n]; + if (freq != 0) { + // Insert n into heap + int pos = heapLen++; + int ppos; + while (pos > 0 && freqs[heap[ppos = (pos - 1) / 2]] > freq) { + heap[pos] = heap[ppos]; + pos = ppos; + } + heap[pos] = n; + + maxCode = n; + } + } + + /* We could encode a single literal with 0 bits but then we + * don't see the literals. Therefore we force at least two + * literals to avoid this case. We don't care about order in + * this case, both literals get a 1 bit code. + */ + while (heapLen < 2) { + int node = maxCode < 2 ? ++maxCode : 0; + heap[heapLen++] = node; + } + + numCodes = Math.Max(maxCode + 1, minNumCodes); + + int numLeafs = heapLen; + int[] childs = new int[4 * heapLen - 2]; + int[] values = new int[2 * heapLen - 1]; + int numNodes = numLeafs; + for (int i = 0; i < heapLen; i++) { + int node = heap[i]; + childs[2 * i] = node; + childs[2 * i + 1] = -1; + values[i] = freqs[node] << 8; + heap[i] = i; + } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + do { + int first = heap[0]; + int last = heap[--heapLen]; + + // Propagate the hole to the leafs of the heap + int ppos = 0; + int path = 1; + + while (path < heapLen) { + if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { + path++; + } + + heap[ppos] = heap[path]; + ppos = path; + path = path * 2 + 1; + } + + /* Now propagate the last element down along path. Normally + * it shouldn't go too deep. + */ + int lastVal = values[last]; + while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { + heap[path] = heap[ppos]; + } + heap[path] = last; + + + int second = heap[0]; + + // Create a new node father of first and second + last = numNodes++; + childs[2 * last] = first; + childs[2 * last + 1] = second; + int mindepth = Math.Min(values[first] & 0xff, values[second] & 0xff); + values[last] = lastVal = values[first] + values[second] - mindepth + 1; + + // Again, propagate the hole to the leafs + ppos = 0; + path = 1; + + while (path < heapLen) { + if (path + 1 < heapLen && values[heap[path]] > values[heap[path+1]]) { + path++; + } + + heap[ppos] = heap[path]; + ppos = path; + path = ppos * 2 + 1; + } + + // Now propagate the new element down along path + while ((path = ppos) > 0 && values[heap[ppos = (path - 1)/2]] > lastVal) { + heap[path] = heap[ppos]; + } + heap[path] = last; + } while (heapLen > 1); + + if (heap[0] != childs.Length / 2 - 1) { + throw new SharpZipBaseException("Heap invariant violated"); + } + + BuildLength(childs); + } + + /// + /// Get encoded length + /// + /// Encoded length, the sum of frequencies * lengths + public int GetEncodedLength() + { + int len = 0; + for (int i = 0; i < freqs.Length; i++) { + len += freqs[i] * length[i]; + } + return len; + } + + /// + /// Scan a literal or distance tree to determine the frequencies of the codes + /// in the bit length tree. + /// + public void CalcBLFreq(Tree blTree) + { + int max_count; /* max repeat count */ + int min_count; /* min repeat count */ + int count; /* repeat count of the current code */ + int curlen = -1; /* length of current code */ + + int i = 0; + while (i < numCodes) { + count = 1; + int nextlen = length[i]; + if (nextlen == 0) { + max_count = 138; + min_count = 3; + } else { + max_count = 6; + min_count = 3; + if (curlen != nextlen) { + blTree.freqs[nextlen]++; + count = 0; + } + } + curlen = nextlen; + i++; + + while (i < numCodes && curlen == length[i]) { + i++; + if (++count >= max_count) { + break; + } + } + + if (count < min_count) { + blTree.freqs[curlen] += (short)count; + } else if (curlen != 0) { + blTree.freqs[REP_3_6]++; + } else if (count <= 10) { + blTree.freqs[REP_3_10]++; + } else { + blTree.freqs[REP_11_138]++; + } + } + } + + /// + /// Write tree values + /// + /// Tree to write + public void WriteTree(Tree blTree) + { + int max_count; // max repeat count + int min_count; // min repeat count + int count; // repeat count of the current code + int curlen = -1; // length of current code + + int i = 0; + while (i < numCodes) { + count = 1; + int nextlen = length[i]; + if (nextlen == 0) { + max_count = 138; + min_count = 3; + } else { + max_count = 6; + min_count = 3; + if (curlen != nextlen) { + blTree.WriteSymbol(nextlen); + count = 0; + } + } + curlen = nextlen; + i++; + + while (i < numCodes && curlen == length[i]) { + i++; + if (++count >= max_count) { + break; + } + } + + if (count < min_count) { + while (count-- > 0) { + blTree.WriteSymbol(curlen); + } + } else if (curlen != 0) { + blTree.WriteSymbol(REP_3_6); + dh.pending.WriteBits(count - 3, 2); + } else if (count <= 10) { + blTree.WriteSymbol(REP_3_10); + dh.pending.WriteBits(count - 3, 3); + } else { + blTree.WriteSymbol(REP_11_138); + dh.pending.WriteBits(count - 11, 7); + } + } + } - void BuildLength(int[] childs) - { - this.length = new byte [freqs.Length]; - int numNodes = childs.Length / 2; - int numLeafs = (numNodes + 1) / 2; - int overflow = 0; - - for (int i = 0; i < maxLength; i++) { - bl_counts[i] = 0; - } - - // First calculate optimal bit lengths - int[] lengths = new int[numNodes]; - lengths[numNodes-1] = 0; - - for (int i = numNodes - 1; i >= 0; i--) { - if (childs[2 * i + 1] != -1) { - int bitLength = lengths[i] + 1; - if (bitLength > maxLength) { - bitLength = maxLength; - overflow++; - } - lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength; - } else { - // A leaf node - int bitLength = lengths[i]; - bl_counts[bitLength - 1]++; - this.length[childs[2*i]] = (byte) lengths[i]; - } - } - - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("Tree "+freqs.Length+" lengths:"); - // for (int i=0; i < numLeafs; i++) { - // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] - // + " len: "+length[childs[2*i]]); - // } - // } - - if (overflow == 0) { - return; - } - - int incrBitLen = maxLength - 1; - do { - // Find the first bit length which could increase: - while (bl_counts[--incrBitLen] == 0) - ; - - // Move this node one down and remove a corresponding - // number of overflow nodes. - do { - bl_counts[incrBitLen]--; - bl_counts[++incrBitLen]++; - overflow -= 1 << (maxLength - 1 - incrBitLen); - } while (overflow > 0 && incrBitLen < maxLength - 1); - } while (overflow > 0); - - /* We may have overshot above. Move some nodes from maxLength to - * maxLength-1 in that case. - */ - bl_counts[maxLength-1] += overflow; - bl_counts[maxLength-2] -= overflow; - - /* Now recompute all bit lengths, scanning in increasing - * frequency. It is simpler to reconstruct all lengths instead of - * fixing only the wrong ones. This idea is taken from 'ar' - * written by Haruhiko Okumura. - * - * The nodes were inserted with decreasing frequency into the childs - * array. - */ - int nodePtr = 2 * numLeafs; - for (int bits = maxLength; bits != 0; bits--) { - int n = bl_counts[bits-1]; - while (n > 0) { - int childPtr = 2*childs[nodePtr++]; - if (childs[childPtr + 1] == -1) { - // We found another leaf - length[childs[childPtr]] = (byte) bits; - n--; - } - } - } - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("*** After overflow elimination. ***"); - // for (int i=0; i < numLeafs; i++) { - // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] - // + " len: "+length[childs[2*i]]); - // } - // } - } - - } + void BuildLength(int[] childs) + { + this.length = new byte [freqs.Length]; + int numNodes = childs.Length / 2; + int numLeafs = (numNodes + 1) / 2; + int overflow = 0; + + for (int i = 0; i < maxLength; i++) { + bl_counts[i] = 0; + } + + // First calculate optimal bit lengths + int[] lengths = new int[numNodes]; + lengths[numNodes-1] = 0; + + for (int i = numNodes - 1; i >= 0; i--) { + if (childs[2 * i + 1] != -1) { + int bitLength = lengths[i] + 1; + if (bitLength > maxLength) { + bitLength = maxLength; + overflow++; + } + lengths[childs[2 * i]] = lengths[childs[2 * i + 1]] = bitLength; + } else { + // A leaf node + int bitLength = lengths[i]; + bl_counts[bitLength - 1]++; + this.length[childs[2*i]] = (byte) lengths[i]; + } + } + + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("Tree "+freqs.Length+" lengths:"); + // for (int i=0; i < numLeafs; i++) { + // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] + // + " len: "+length[childs[2*i]]); + // } + // } + + if (overflow == 0) { + return; + } + + int incrBitLen = maxLength - 1; + do { + // Find the first bit length which could increase: + while (bl_counts[--incrBitLen] == 0) + ; + + // Move this node one down and remove a corresponding + // number of overflow nodes. + do { + bl_counts[incrBitLen]--; + bl_counts[++incrBitLen]++; + overflow -= 1 << (maxLength - 1 - incrBitLen); + } while (overflow > 0 && incrBitLen < maxLength - 1); + } while (overflow > 0); + + /* We may have overshot above. Move some nodes from maxLength to + * maxLength-1 in that case. + */ + bl_counts[maxLength-1] += overflow; + bl_counts[maxLength-2] -= overflow; + + /* Now recompute all bit lengths, scanning in increasing + * frequency. It is simpler to reconstruct all lengths instead of + * fixing only the wrong ones. This idea is taken from 'ar' + * written by Haruhiko Okumura. + * + * The nodes were inserted with decreasing frequency into the childs + * array. + */ + int nodePtr = 2 * numLeafs; + for (int bits = maxLength; bits != 0; bits--) { + int n = bl_counts[bits-1]; + while (n > 0) { + int childPtr = 2*childs[nodePtr++]; + if (childs[childPtr + 1] == -1) { + // We found another leaf + length[childs[childPtr]] = (byte) bits; + n--; + } + } + } + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("*** After overflow elimination. ***"); + // for (int i=0; i < numLeafs; i++) { + // //Console.WriteLine("Node "+childs[2*i]+" freq: "+freqs[childs[2*i]] + // + " len: "+length[childs[2*i]]); + // } + // } + } + + } - #region Instance Fields - /// - /// Pending buffer to use - /// - public DeflaterPending pending; - - Tree literalTree; - Tree distTree; - Tree blTree; - - // Buffer for distances - short[] d_buf; - byte[] l_buf; - int last_lit; - int extra_bits; - #endregion + #region Instance Fields + /// + /// Pending buffer to use + /// + public DeflaterPending pending; + + Tree literalTree; + Tree distTree; + Tree blTree; + + // Buffer for distances + short[] d_buf; + byte[] l_buf; + int last_lit; + int extra_bits; + #endregion - static DeflaterHuffman() - { - // See RFC 1951 3.2.6 - // Literal codes - staticLCodes = new short[LITERAL_NUM]; - staticLLength = new byte[LITERAL_NUM]; + static DeflaterHuffman() + { + // See RFC 1951 3.2.6 + // Literal codes + staticLCodes = new short[LITERAL_NUM]; + staticLLength = new byte[LITERAL_NUM]; - int i = 0; - while (i < 144) { - staticLCodes[i] = BitReverse((0x030 + i) << 8); - staticLLength[i++] = 8; - } + int i = 0; + while (i < 144) { + staticLCodes[i] = BitReverse((0x030 + i) << 8); + staticLLength[i++] = 8; + } - while (i < 256) { - staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7); - staticLLength[i++] = 9; - } + while (i < 256) { + staticLCodes[i] = BitReverse((0x190 - 144 + i) << 7); + staticLLength[i++] = 9; + } - while (i < 280) { - staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9); - staticLLength[i++] = 7; - } + while (i < 280) { + staticLCodes[i] = BitReverse((0x000 - 256 + i) << 9); + staticLLength[i++] = 7; + } - while (i < LITERAL_NUM) { - staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8); - staticLLength[i++] = 8; - } - - // Distance codes - staticDCodes = new short[DIST_NUM]; - staticDLength = new byte[DIST_NUM]; - for (i = 0; i < DIST_NUM; i++) { - staticDCodes[i] = BitReverse(i << 11); - staticDLength[i] = 5; - } - } - - /// - /// Construct instance with pending buffer - /// - /// Pending buffer to use - public DeflaterHuffman(DeflaterPending pending) - { - this.pending = pending; - - literalTree = new Tree(this, LITERAL_NUM, 257, 15); - distTree = new Tree(this, DIST_NUM, 1, 15); - blTree = new Tree(this, BITLEN_NUM, 4, 7); - - d_buf = new short[BUFSIZE]; - l_buf = new byte [BUFSIZE]; - } + while (i < LITERAL_NUM) { + staticLCodes[i] = BitReverse((0x0c0 - 280 + i) << 8); + staticLLength[i++] = 8; + } + + // Distance codes + staticDCodes = new short[DIST_NUM]; + staticDLength = new byte[DIST_NUM]; + for (i = 0; i < DIST_NUM; i++) { + staticDCodes[i] = BitReverse(i << 11); + staticDLength[i] = 5; + } + } + + /// + /// Construct instance with pending buffer + /// + /// Pending buffer to use + public DeflaterHuffman(DeflaterPending pending) + { + this.pending = pending; + + literalTree = new Tree(this, LITERAL_NUM, 257, 15); + distTree = new Tree(this, DIST_NUM, 1, 15); + blTree = new Tree(this, BITLEN_NUM, 4, 7); + + d_buf = new short[BUFSIZE]; + l_buf = new byte [BUFSIZE]; + } - /// - /// Reset internal state - /// - public void Reset() - { - last_lit = 0; - extra_bits = 0; - literalTree.Reset(); - distTree.Reset(); - blTree.Reset(); - } - - /// - /// Write all trees to pending buffer - /// - /// The number/rank of treecodes to send. - public void SendAllTrees(int blTreeCodes) - { - blTree.BuildCodes(); - literalTree.BuildCodes(); - distTree.BuildCodes(); - pending.WriteBits(literalTree.numCodes - 257, 5); - pending.WriteBits(distTree.numCodes - 1, 5); - pending.WriteBits(blTreeCodes - 4, 4); - for (int rank = 0; rank < blTreeCodes; rank++) { - pending.WriteBits(blTree.length[BL_ORDER[rank]], 3); - } - literalTree.WriteTree(blTree); - distTree.WriteTree(blTree); + /// + /// Reset internal state + /// + public void Reset() + { + last_lit = 0; + extra_bits = 0; + literalTree.Reset(); + distTree.Reset(); + blTree.Reset(); + } + + /// + /// Write all trees to pending buffer + /// + /// The number/rank of treecodes to send. + public void SendAllTrees(int blTreeCodes) + { + blTree.BuildCodes(); + literalTree.BuildCodes(); + distTree.BuildCodes(); + pending.WriteBits(literalTree.numCodes - 257, 5); + pending.WriteBits(distTree.numCodes - 1, 5); + pending.WriteBits(blTreeCodes - 4, 4); + for (int rank = 0; rank < blTreeCodes; rank++) { + pending.WriteBits(blTree.length[BL_ORDER[rank]], 3); + } + literalTree.WriteTree(blTree); + distTree.WriteTree(blTree); #if DebugDeflation - if (DeflaterConstants.DEBUGGING) { - blTree.CheckEmpty(); - } + if (DeflaterConstants.DEBUGGING) { + blTree.CheckEmpty(); + } #endif - } + } - /// - /// Compress current buffer writing data to pending buffer - /// - public void CompressBlock() - { - for (int i = 0; i < last_lit; i++) { - int litlen = l_buf[i] & 0xff; - int dist = d_buf[i]; - if (dist-- != 0) { - // if (DeflaterConstants.DEBUGGING) { - // Console.Write("["+(dist+1)+","+(litlen+3)+"]: "); - // } - - int lc = Lcode(litlen); - literalTree.WriteSymbol(lc); - - int bits = (lc - 261) / 4; - if (bits > 0 && bits <= 5) { - pending.WriteBits(litlen & ((1 << bits) - 1), bits); - } - - int dc = Dcode(dist); - distTree.WriteSymbol(dc); - - bits = dc / 2 - 1; - if (bits > 0) { - pending.WriteBits(dist & ((1 << bits) - 1), bits); - } - } else { - // if (DeflaterConstants.DEBUGGING) { - // if (litlen > 32 && litlen < 127) { - // Console.Write("("+(char)litlen+"): "); - // } else { - // Console.Write("{"+litlen+"}: "); - // } - // } - literalTree.WriteSymbol(litlen); - } - } + /// + /// Compress current buffer writing data to pending buffer + /// + public void CompressBlock() + { + for (int i = 0; i < last_lit; i++) { + int litlen = l_buf[i] & 0xff; + int dist = d_buf[i]; + if (dist-- != 0) { + // if (DeflaterConstants.DEBUGGING) { + // Console.Write("["+(dist+1)+","+(litlen+3)+"]: "); + // } + + int lc = Lcode(litlen); + literalTree.WriteSymbol(lc); + + int bits = (lc - 261) / 4; + if (bits > 0 && bits <= 5) { + pending.WriteBits(litlen & ((1 << bits) - 1), bits); + } + + int dc = Dcode(dist); + distTree.WriteSymbol(dc); + + bits = dc / 2 - 1; + if (bits > 0) { + pending.WriteBits(dist & ((1 << bits) - 1), bits); + } + } else { + // if (DeflaterConstants.DEBUGGING) { + // if (litlen > 32 && litlen < 127) { + // Console.Write("("+(char)litlen+"): "); + // } else { + // Console.Write("{"+litlen+"}: "); + // } + // } + literalTree.WriteSymbol(litlen); + } + } #if DebugDeflation - if (DeflaterConstants.DEBUGGING) { - Console.Write("EOF: "); - } + if (DeflaterConstants.DEBUGGING) { + Console.Write("EOF: "); + } #endif - literalTree.WriteSymbol(EOF_SYMBOL); + literalTree.WriteSymbol(EOF_SYMBOL); #if DebugDeflation - if (DeflaterConstants.DEBUGGING) { - literalTree.CheckEmpty(); - distTree.CheckEmpty(); - } + if (DeflaterConstants.DEBUGGING) { + literalTree.CheckEmpty(); + distTree.CheckEmpty(); + } #endif - } - - /// - /// Flush block to output with no compression - /// - /// Data to write - /// Index of first byte to write - /// Count of bytes to write - /// True if this is the last block - public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) - { + } + + /// + /// Flush block to output with no compression + /// + /// Data to write + /// Index of first byte to write + /// Count of bytes to write + /// True if this is the last block + public void FlushStoredBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) + { #if DebugDeflation - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("Flushing stored block "+ storedLength); - // } + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("Flushing stored block "+ storedLength); + // } #endif - pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3); - pending.AlignToByte(); - pending.WriteShort(storedLength); - pending.WriteShort(~storedLength); - pending.WriteBlock(stored, storedOffset, storedLength); - Reset(); - } + pending.WriteBits((DeflaterConstants.STORED_BLOCK << 1) + (lastBlock ? 1 : 0), 3); + pending.AlignToByte(); + pending.WriteShort(storedLength); + pending.WriteShort(~storedLength); + pending.WriteBlock(stored, storedOffset, storedLength); + Reset(); + } - /// - /// Flush block to output with compression - /// - /// Data to flush - /// Index of first byte to flush - /// Count of bytes to flush - /// True if this is the last block - public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) - { - literalTree.freqs[EOF_SYMBOL]++; - - // Build trees - literalTree.BuildTree(); - distTree.BuildTree(); - - // Calculate bitlen frequency - literalTree.CalcBLFreq(blTree); - distTree.CalcBLFreq(blTree); - - // Build bitlen tree - blTree.BuildTree(); - - int blTreeCodes = 4; - for (int i = 18; i > blTreeCodes; i--) { - if (blTree.length[BL_ORDER[i]] > 0) { - blTreeCodes = i+1; - } - } - int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() + - literalTree.GetEncodedLength() + distTree.GetEncodedLength() + - extra_bits; - - int static_len = extra_bits; - for (int i = 0; i < LITERAL_NUM; i++) { - static_len += literalTree.freqs[i] * staticLLength[i]; - } - for (int i = 0; i < DIST_NUM; i++) { - static_len += distTree.freqs[i] * staticDLength[i]; - } - if (opt_len >= static_len) { - // Force static trees - opt_len = static_len; - } - - if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) { - // Store Block + /// + /// Flush block to output with compression + /// + /// Data to flush + /// Index of first byte to flush + /// Count of bytes to flush + /// True if this is the last block + public void FlushBlock(byte[] stored, int storedOffset, int storedLength, bool lastBlock) + { + literalTree.freqs[EOF_SYMBOL]++; + + // Build trees + literalTree.BuildTree(); + distTree.BuildTree(); + + // Calculate bitlen frequency + literalTree.CalcBLFreq(blTree); + distTree.CalcBLFreq(blTree); + + // Build bitlen tree + blTree.BuildTree(); + + int blTreeCodes = 4; + for (int i = 18; i > blTreeCodes; i--) { + if (blTree.length[BL_ORDER[i]] > 0) { + blTreeCodes = i+1; + } + } + int opt_len = 14 + blTreeCodes * 3 + blTree.GetEncodedLength() + + literalTree.GetEncodedLength() + distTree.GetEncodedLength() + + extra_bits; + + int static_len = extra_bits; + for (int i = 0; i < LITERAL_NUM; i++) { + static_len += literalTree.freqs[i] * staticLLength[i]; + } + for (int i = 0; i < DIST_NUM; i++) { + static_len += distTree.freqs[i] * staticDLength[i]; + } + if (opt_len >= static_len) { + // Force static trees + opt_len = static_len; + } + + if (storedOffset >= 0 && storedLength + 4 < opt_len >> 3) { + // Store Block - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len - // + " <= " + static_len); - // } - FlushStoredBlock(stored, storedOffset, storedLength, lastBlock); - } else if (opt_len == static_len) { - // Encode with static tree - pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3); - literalTree.SetStaticCodes(staticLCodes, staticLLength); - distTree.SetStaticCodes(staticDCodes, staticDLength); - CompressBlock(); - Reset(); - } else { - // Encode with dynamic tree - pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3); - SendAllTrees(blTreeCodes); - CompressBlock(); - Reset(); - } - } - - /// - /// Get value indicating if internal buffer is full - /// - /// true if buffer is full - public bool IsFull() - { - return last_lit >= BUFSIZE; - } - - /// - /// Add literal to buffer - /// - /// Literal value to add to buffer. - /// Value indicating internal buffer is full - public bool TallyLit(int literal) - { - // if (DeflaterConstants.DEBUGGING) { - // if (lit > 32 && lit < 127) { - // //Console.WriteLine("("+(char)lit+")"); - // } else { - // //Console.WriteLine("{"+lit+"}"); - // } - // } - d_buf[last_lit] = 0; - l_buf[last_lit++] = (byte)literal; - literalTree.freqs[literal]++; - return IsFull(); - } - - /// - /// Add distance code and length to literal and distance trees - /// - /// Distance code - /// Length - /// Value indicating if internal buffer is full - public bool TallyDist(int distance, int length) - { - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("[" + distance + "," + length + "]"); - // } - - d_buf[last_lit] = (short)distance; - l_buf[last_lit++] = (byte)(length - 3); - - int lc = Lcode(length - 3); - literalTree.freqs[lc]++; - if (lc >= 265 && lc < 285) { - extra_bits += (lc - 261) / 4; - } - - int dc = Dcode(distance - 1); - distTree.freqs[dc]++; - if (dc >= 4) { - extra_bits += dc / 2 - 1; - } - return IsFull(); - } + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("Storing, since " + storedLength + " < " + opt_len + // + " <= " + static_len); + // } + FlushStoredBlock(stored, storedOffset, storedLength, lastBlock); + } else if (opt_len == static_len) { + // Encode with static tree + pending.WriteBits((DeflaterConstants.STATIC_TREES << 1) + (lastBlock ? 1 : 0), 3); + literalTree.SetStaticCodes(staticLCodes, staticLLength); + distTree.SetStaticCodes(staticDCodes, staticDLength); + CompressBlock(); + Reset(); + } else { + // Encode with dynamic tree + pending.WriteBits((DeflaterConstants.DYN_TREES << 1) + (lastBlock ? 1 : 0), 3); + SendAllTrees(blTreeCodes); + CompressBlock(); + Reset(); + } + } + + /// + /// Get value indicating if internal buffer is full + /// + /// true if buffer is full + public bool IsFull() + { + return last_lit >= BUFSIZE; + } + + /// + /// Add literal to buffer + /// + /// Literal value to add to buffer. + /// Value indicating internal buffer is full + public bool TallyLit(int literal) + { + // if (DeflaterConstants.DEBUGGING) { + // if (lit > 32 && lit < 127) { + // //Console.WriteLine("("+(char)lit+")"); + // } else { + // //Console.WriteLine("{"+lit+"}"); + // } + // } + d_buf[last_lit] = 0; + l_buf[last_lit++] = (byte)literal; + literalTree.freqs[literal]++; + return IsFull(); + } + + /// + /// Add distance code and length to literal and distance trees + /// + /// Distance code + /// Length + /// Value indicating if internal buffer is full + public bool TallyDist(int distance, int length) + { + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("[" + distance + "," + length + "]"); + // } + + d_buf[last_lit] = (short)distance; + l_buf[last_lit++] = (byte)(length - 3); + + int lc = Lcode(length - 3); + literalTree.freqs[lc]++; + if (lc >= 265 && lc < 285) { + extra_bits += (lc - 261) / 4; + } + + int dc = Dcode(distance - 1); + distTree.freqs[dc]++; + if (dc >= 4) { + extra_bits += dc / 2 - 1; + } + return IsFull(); + } - - /// - /// Reverse the bits of a 16 bit value. - /// - /// Value to reverse bits - /// Value with bits reversed - public static short BitReverse(int toReverse) - { - return (short) (bit4Reverse[toReverse & 0xF] << 12 | - bit4Reverse[(toReverse >> 4) & 0xF] << 8 | - bit4Reverse[(toReverse >> 8) & 0xF] << 4 | - bit4Reverse[toReverse >> 12]); - } - - static int Lcode(int length) - { - if (length == 255) { - return 285; - } - - int code = 257; - while (length >= 8) { - code += 4; - length >>= 1; - } - return code + length; - } - - static int Dcode(int distance) - { - int code = 0; - while (distance >= 4) { - code += 2; - distance >>= 1; - } - return code + distance; - } - } + + /// + /// Reverse the bits of a 16 bit value. + /// + /// Value to reverse bits + /// Value with bits reversed + public static short BitReverse(int toReverse) + { + return (short) (bit4Reverse[toReverse & 0xF] << 12 | + bit4Reverse[(toReverse >> 4) & 0xF] << 8 | + bit4Reverse[(toReverse >> 8) & 0xF] << 4 | + bit4Reverse[toReverse >> 12]); + } + + static int Lcode(int length) + { + if (length == 255) { + return 285; + } + + int code = 257; + while (length >= 8) { + code += 4; + length >>= 1; + } + return code + length; + } + + static int Dcode(int distance) + { + int code = 0; + while (distance >= 4) { + code += 2; + distance >>= 1; + } + return code + distance; + } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterPending.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterPending.cs index 4cecc2e7c0..bf1418e73e 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterPending.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/DeflaterPending.cs @@ -39,19 +39,19 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - - /// - /// This class stores the pending output of the Deflater. - /// - /// author of the original java version : Jochen Hoenicke - /// - public class DeflaterPending : PendingBuffer - { - /// - /// Construct instance with default buffer size - /// - public DeflaterPending() : base(DeflaterConstants.PENDING_BUF_SIZE) - { - } - } + + /// + /// This class stores the pending output of the Deflater. + /// + /// author of the original java version : Jochen Hoenicke + /// + public class DeflaterPending : PendingBuffer + { + /// + /// Construct instance with default buffer size + /// + public DeflaterPending() : base(DeflaterConstants.PENDING_BUF_SIZE) + { + } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/Inflater.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/Inflater.cs index 16c3ef6cbb..9183596754 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/Inflater.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/Inflater.cs @@ -44,821 +44,821 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - /// - /// Inflater is used to decompress data that has been compressed according - /// to the "deflate" standard described in rfc1951. - /// - /// By default Zlib (rfc1950) headers and footers are expected in the input. - /// You can use constructor public Inflater(bool noHeader) passing true - /// if there is no Zlib header information - /// - /// The usage is as following. First you have to set some input with - /// SetInput(), then Inflate() it. If inflate doesn't - /// inflate any bytes there may be three reasons: - ///
      - ///
    • IsNeedingInput() returns true because the input buffer is empty. - /// You have to provide more input with SetInput(). - /// NOTE: IsNeedingInput() also returns true when, the stream is finished. - ///
    • - ///
    • IsNeedingDictionary() returns true, you have to provide a preset - /// dictionary with SetDictionary().
    • - ///
    • IsFinished returns true, the inflater has finished.
    • - ///
    - /// Once the first output byte is produced, a dictionary will not be - /// needed at a later stage. - /// - /// author of the original java version : John Leuner, Jochen Hoenicke - ///
    - public class Inflater - { - #region Constants/Readonly - /// - /// Copy lengths for literal codes 257..285 - /// - static readonly int[] CPLENS = { - 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, - 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 - }; - - /// - /// Extra bits for literal codes 257..285 - /// - static readonly int[] CPLEXT = { - 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, - 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 - }; - - /// - /// Copy offsets for distance codes 0..29 - /// - static readonly int[] CPDIST = { - 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, - 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, - 8193, 12289, 16385, 24577 - }; - - /// - /// Extra bits for distance codes - /// - static readonly int[] CPDEXT = { - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, - 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, - 12, 12, 13, 13 - }; - - /// - /// These are the possible states for an inflater - /// - const int DECODE_HEADER = 0; - const int DECODE_DICT = 1; - const int DECODE_BLOCKS = 2; - const int DECODE_STORED_LEN1 = 3; - const int DECODE_STORED_LEN2 = 4; - const int DECODE_STORED = 5; - const int DECODE_DYN_HEADER = 6; - const int DECODE_HUFFMAN = 7; - const int DECODE_HUFFMAN_LENBITS = 8; - const int DECODE_HUFFMAN_DIST = 9; - const int DECODE_HUFFMAN_DISTBITS = 10; - const int DECODE_CHKSUM = 11; - const int FINISHED = 12; - #endregion + /// + /// Inflater is used to decompress data that has been compressed according + /// to the "deflate" standard described in rfc1951. + /// + /// By default Zlib (rfc1950) headers and footers are expected in the input. + /// You can use constructor public Inflater(bool noHeader) passing true + /// if there is no Zlib header information + /// + /// The usage is as following. First you have to set some input with + /// SetInput(), then Inflate() it. If inflate doesn't + /// inflate any bytes there may be three reasons: + ///
      + ///
    • IsNeedingInput() returns true because the input buffer is empty. + /// You have to provide more input with SetInput(). + /// NOTE: IsNeedingInput() also returns true when, the stream is finished. + ///
    • + ///
    • IsNeedingDictionary() returns true, you have to provide a preset + /// dictionary with SetDictionary().
    • + ///
    • IsFinished returns true, the inflater has finished.
    • + ///
    + /// Once the first output byte is produced, a dictionary will not be + /// needed at a later stage. + /// + /// author of the original java version : John Leuner, Jochen Hoenicke + ///
    + public class Inflater + { + #region Constants/Readonly + /// + /// Copy lengths for literal codes 257..285 + /// + static readonly int[] CPLENS = { + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 + }; + + /// + /// Extra bits for literal codes 257..285 + /// + static readonly int[] CPLEXT = { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, + 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 + }; + + /// + /// Copy offsets for distance codes 0..29 + /// + static readonly int[] CPDIST = { + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577 + }; + + /// + /// Extra bits for distance codes + /// + static readonly int[] CPDEXT = { + 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, + 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, + 12, 12, 13, 13 + }; + + /// + /// These are the possible states for an inflater + /// + const int DECODE_HEADER = 0; + const int DECODE_DICT = 1; + const int DECODE_BLOCKS = 2; + const int DECODE_STORED_LEN1 = 3; + const int DECODE_STORED_LEN2 = 4; + const int DECODE_STORED = 5; + const int DECODE_DYN_HEADER = 6; + const int DECODE_HUFFMAN = 7; + const int DECODE_HUFFMAN_LENBITS = 8; + const int DECODE_HUFFMAN_DIST = 9; + const int DECODE_HUFFMAN_DISTBITS = 10; + const int DECODE_CHKSUM = 11; + const int FINISHED = 12; + #endregion - #region Instance Fields - /// - /// This variable contains the current state. - /// - int mode; - - /// - /// The adler checksum of the dictionary or of the decompressed - /// stream, as it is written in the header resp. footer of the - /// compressed stream. - /// Only valid if mode is DECODE_DICT or DECODE_CHKSUM. - /// - int readAdler; - - /// - /// The number of bits needed to complete the current state. This - /// is valid, if mode is DECODE_DICT, DECODE_CHKSUM, - /// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS. - /// - int neededBits; - int repLength; - int repDist; - int uncomprLen; - - /// - /// True, if the last block flag was set in the last block of the - /// inflated stream. This means that the stream ends after the - /// current block. - /// - bool isLastBlock; - - /// - /// The total number of inflated bytes. - /// - long totalOut; - - /// - /// The total number of bytes set with setInput(). This is not the - /// value returned by the TotalIn property, since this also includes the - /// unprocessed input. - /// - long totalIn; - - /// - /// This variable stores the noHeader flag that was given to the constructor. - /// True means, that the inflated stream doesn't contain a Zlib header or - /// footer. - /// - bool noHeader; - - StreamManipulator input; - OutputWindow outputWindow; - InflaterDynHeader dynHeader; - InflaterHuffmanTree litlenTree, distTree; - Adler32 adler; - #endregion - - #region Constructors - /// - /// Creates a new inflater or RFC1951 decompressor - /// RFC1950/Zlib headers and footers will be expected in the input data - /// - public Inflater() : this(false) - { - } - - /// - /// Creates a new inflater. - /// - /// - /// True if no RFC1950/Zlib header and footer fields are expected in the input data - /// - /// This is used for GZIPed/Zipped input. - /// - /// For compatibility with - /// Sun JDK you should provide one byte of input more than needed in - /// this case. - /// - public Inflater(bool noHeader) - { - this.noHeader = noHeader; - this.adler = new Adler32(); - input = new StreamManipulator(); - outputWindow = new OutputWindow(); - mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; - } - #endregion + #region Instance Fields + /// + /// This variable contains the current state. + /// + int mode; + + /// + /// The adler checksum of the dictionary or of the decompressed + /// stream, as it is written in the header resp. footer of the + /// compressed stream. + /// Only valid if mode is DECODE_DICT or DECODE_CHKSUM. + /// + int readAdler; + + /// + /// The number of bits needed to complete the current state. This + /// is valid, if mode is DECODE_DICT, DECODE_CHKSUM, + /// DECODE_HUFFMAN_LENBITS or DECODE_HUFFMAN_DISTBITS. + /// + int neededBits; + int repLength; + int repDist; + int uncomprLen; + + /// + /// True, if the last block flag was set in the last block of the + /// inflated stream. This means that the stream ends after the + /// current block. + /// + bool isLastBlock; + + /// + /// The total number of inflated bytes. + /// + long totalOut; + + /// + /// The total number of bytes set with setInput(). This is not the + /// value returned by the TotalIn property, since this also includes the + /// unprocessed input. + /// + long totalIn; + + /// + /// This variable stores the noHeader flag that was given to the constructor. + /// True means, that the inflated stream doesn't contain a Zlib header or + /// footer. + /// + bool noHeader; + + StreamManipulator input; + OutputWindow outputWindow; + InflaterDynHeader dynHeader; + InflaterHuffmanTree litlenTree, distTree; + Adler32 adler; + #endregion + + #region Constructors + /// + /// Creates a new inflater or RFC1951 decompressor + /// RFC1950/Zlib headers and footers will be expected in the input data + /// + public Inflater() : this(false) + { + } + + /// + /// Creates a new inflater. + /// + /// + /// True if no RFC1950/Zlib header and footer fields are expected in the input data + /// + /// This is used for GZIPed/Zipped input. + /// + /// For compatibility with + /// Sun JDK you should provide one byte of input more than needed in + /// this case. + /// + public Inflater(bool noHeader) + { + this.noHeader = noHeader; + this.adler = new Adler32(); + input = new StreamManipulator(); + outputWindow = new OutputWindow(); + mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; + } + #endregion - /// - /// Resets the inflater so that a new stream can be decompressed. All - /// pending input and output will be discarded. - /// - public void Reset() - { - mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; - totalIn = 0; - totalOut = 0; - input.Reset(); - outputWindow.Reset(); - dynHeader = null; - litlenTree = null; - distTree = null; - isLastBlock = false; - adler.Reset(); - } - - /// - /// Decodes a zlib/RFC1950 header. - /// - /// - /// False if more input is needed. - /// - /// - /// The header is invalid. - /// - private bool DecodeHeader() - { - int header = input.PeekBits(16); - if (header < 0) { - return false; - } - input.DropBits(16); - - // The header is written in "wrong" byte order - header = ((header << 8) | (header >> 8)) & 0xffff; - if (header % 31 != 0) { - throw new SharpZipBaseException("Header checksum illegal"); - } - - if ((header & 0x0f00) != (Deflater.DEFLATED << 8)) { - throw new SharpZipBaseException("Compression Method unknown"); - } - - /* Maximum size of the backwards window in bits. - * We currently ignore this, but we could use it to make the - * inflater window more space efficient. On the other hand the - * full window (15 bits) is needed most times, anyway. - int max_wbits = ((header & 0x7000) >> 12) + 8; - */ - - if ((header & 0x0020) == 0) { // Dictionary flag? - mode = DECODE_BLOCKS; - } else { - mode = DECODE_DICT; - neededBits = 32; - } - return true; - } - - /// - /// Decodes the dictionary checksum after the deflate header. - /// - /// - /// False if more input is needed. - /// - private bool DecodeDict() - { - while (neededBits > 0) { - int dictByte = input.PeekBits(8); - if (dictByte < 0) { - return false; - } - input.DropBits(8); - readAdler = (readAdler << 8) | dictByte; - neededBits -= 8; - } - return false; - } - - /// - /// Decodes the huffman encoded symbols in the input stream. - /// - /// - /// false if more input is needed, true if output window is - /// full or the current block ends. - /// - /// - /// if deflated stream is invalid. - /// - private bool DecodeHuffman() - { - int free = outputWindow.GetFreeSpace(); - while (free >= 258) - { - int symbol; - switch (mode) - { - case DECODE_HUFFMAN: - // This is the inner loop so it is optimized a bit - while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0) - { - outputWindow.Write(symbol); - if (--free < 258) - { - return true; - } - } - - if (symbol < 257) - { - if (symbol < 0) - { - return false; - } - else - { - // symbol == 256: end of block - distTree = null; - litlenTree = null; - mode = DECODE_BLOCKS; - return true; - } - } - - try - { - repLength = CPLENS[symbol - 257]; - neededBits = CPLEXT[symbol - 257]; - } - catch (Exception) - { - throw new SharpZipBaseException("Illegal rep length code"); - } - goto case DECODE_HUFFMAN_LENBITS; // fall through - - case DECODE_HUFFMAN_LENBITS: - if (neededBits > 0) - { - mode = DECODE_HUFFMAN_LENBITS; - int i = input.PeekBits(neededBits); - if (i < 0) - { - return false; - } - input.DropBits(neededBits); - repLength += i; - } - mode = DECODE_HUFFMAN_DIST; - goto case DECODE_HUFFMAN_DIST; // fall through - - case DECODE_HUFFMAN_DIST: - symbol = distTree.GetSymbol(input); - if (symbol < 0) - { - return false; - } - - try - { - repDist = CPDIST[symbol]; - neededBits = CPDEXT[symbol]; - } - catch (Exception) - { - throw new SharpZipBaseException("Illegal rep dist code"); - } - - goto case DECODE_HUFFMAN_DISTBITS; // fall through - - case DECODE_HUFFMAN_DISTBITS: - if (neededBits > 0) - { - mode = DECODE_HUFFMAN_DISTBITS; - int i = input.PeekBits(neededBits); - if (i < 0) - { - return false; - } - input.DropBits(neededBits); - repDist += i; - } - - outputWindow.Repeat(repLength, repDist); - free -= repLength; - mode = DECODE_HUFFMAN; - break; - - default: - throw new SharpZipBaseException("Inflater unknown mode"); - } - } - return true; - } - - /// - /// Decodes the adler checksum after the deflate stream. - /// - /// - /// false if more input is needed. - /// - /// - /// If checksum doesn't match. - /// - private bool DecodeChksum() - { - while (neededBits > 0) { - int chkByte = input.PeekBits(8); - if (chkByte < 0) { - return false; - } - input.DropBits(8); - readAdler = (readAdler << 8) | chkByte; - neededBits -= 8; - } + /// + /// Resets the inflater so that a new stream can be decompressed. All + /// pending input and output will be discarded. + /// + public void Reset() + { + mode = noHeader ? DECODE_BLOCKS : DECODE_HEADER; + totalIn = 0; + totalOut = 0; + input.Reset(); + outputWindow.Reset(); + dynHeader = null; + litlenTree = null; + distTree = null; + isLastBlock = false; + adler.Reset(); + } + + /// + /// Decodes a zlib/RFC1950 header. + /// + /// + /// False if more input is needed. + /// + /// + /// The header is invalid. + /// + private bool DecodeHeader() + { + int header = input.PeekBits(16); + if (header < 0) { + return false; + } + input.DropBits(16); + + // The header is written in "wrong" byte order + header = ((header << 8) | (header >> 8)) & 0xffff; + if (header % 31 != 0) { + throw new SharpZipBaseException("Header checksum illegal"); + } + + if ((header & 0x0f00) != (Deflater.DEFLATED << 8)) { + throw new SharpZipBaseException("Compression Method unknown"); + } + + /* Maximum size of the backwards window in bits. + * We currently ignore this, but we could use it to make the + * inflater window more space efficient. On the other hand the + * full window (15 bits) is needed most times, anyway. + int max_wbits = ((header & 0x7000) >> 12) + 8; + */ + + if ((header & 0x0020) == 0) { // Dictionary flag? + mode = DECODE_BLOCKS; + } else { + mode = DECODE_DICT; + neededBits = 32; + } + return true; + } + + /// + /// Decodes the dictionary checksum after the deflate header. + /// + /// + /// False if more input is needed. + /// + private bool DecodeDict() + { + while (neededBits > 0) { + int dictByte = input.PeekBits(8); + if (dictByte < 0) { + return false; + } + input.DropBits(8); + readAdler = (readAdler << 8) | dictByte; + neededBits -= 8; + } + return false; + } + + /// + /// Decodes the huffman encoded symbols in the input stream. + /// + /// + /// false if more input is needed, true if output window is + /// full or the current block ends. + /// + /// + /// if deflated stream is invalid. + /// + private bool DecodeHuffman() + { + int free = outputWindow.GetFreeSpace(); + while (free >= 258) + { + int symbol; + switch (mode) + { + case DECODE_HUFFMAN: + // This is the inner loop so it is optimized a bit + while (((symbol = litlenTree.GetSymbol(input)) & ~0xff) == 0) + { + outputWindow.Write(symbol); + if (--free < 258) + { + return true; + } + } + + if (symbol < 257) + { + if (symbol < 0) + { + return false; + } + else + { + // symbol == 256: end of block + distTree = null; + litlenTree = null; + mode = DECODE_BLOCKS; + return true; + } + } + + try + { + repLength = CPLENS[symbol - 257]; + neededBits = CPLEXT[symbol - 257]; + } + catch (Exception) + { + throw new SharpZipBaseException("Illegal rep length code"); + } + goto case DECODE_HUFFMAN_LENBITS; // fall through + + case DECODE_HUFFMAN_LENBITS: + if (neededBits > 0) + { + mode = DECODE_HUFFMAN_LENBITS; + int i = input.PeekBits(neededBits); + if (i < 0) + { + return false; + } + input.DropBits(neededBits); + repLength += i; + } + mode = DECODE_HUFFMAN_DIST; + goto case DECODE_HUFFMAN_DIST; // fall through + + case DECODE_HUFFMAN_DIST: + symbol = distTree.GetSymbol(input); + if (symbol < 0) + { + return false; + } + + try + { + repDist = CPDIST[symbol]; + neededBits = CPDEXT[symbol]; + } + catch (Exception) + { + throw new SharpZipBaseException("Illegal rep dist code"); + } + + goto case DECODE_HUFFMAN_DISTBITS; // fall through + + case DECODE_HUFFMAN_DISTBITS: + if (neededBits > 0) + { + mode = DECODE_HUFFMAN_DISTBITS; + int i = input.PeekBits(neededBits); + if (i < 0) + { + return false; + } + input.DropBits(neededBits); + repDist += i; + } + + outputWindow.Repeat(repLength, repDist); + free -= repLength; + mode = DECODE_HUFFMAN; + break; + + default: + throw new SharpZipBaseException("Inflater unknown mode"); + } + } + return true; + } + + /// + /// Decodes the adler checksum after the deflate stream. + /// + /// + /// false if more input is needed. + /// + /// + /// If checksum doesn't match. + /// + private bool DecodeChksum() + { + while (neededBits > 0) { + int chkByte = input.PeekBits(8); + if (chkByte < 0) { + return false; + } + input.DropBits(8); + readAdler = (readAdler << 8) | chkByte; + neededBits -= 8; + } - if ((int) adler.Value != readAdler) { - throw new SharpZipBaseException("Adler chksum doesn't match: " + (int)adler.Value + " vs. " + readAdler); - } + if ((int) adler.Value != readAdler) { + throw new SharpZipBaseException("Adler chksum doesn't match: " + (int)adler.Value + " vs. " + readAdler); + } - mode = FINISHED; - return false; - } - - /// - /// Decodes the deflated stream. - /// - /// - /// false if more input is needed, or if finished. - /// - /// - /// if deflated stream is invalid. - /// - private bool Decode() - { - switch (mode) { - case DECODE_HEADER: - return DecodeHeader(); + mode = FINISHED; + return false; + } + + /// + /// Decodes the deflated stream. + /// + /// + /// false if more input is needed, or if finished. + /// + /// + /// if deflated stream is invalid. + /// + private bool Decode() + { + switch (mode) { + case DECODE_HEADER: + return DecodeHeader(); - case DECODE_DICT: - return DecodeDict(); + case DECODE_DICT: + return DecodeDict(); - case DECODE_CHKSUM: - return DecodeChksum(); - - case DECODE_BLOCKS: - if (isLastBlock) { - if (noHeader) { - mode = FINISHED; - return false; - } else { - input.SkipToByteBoundary(); - neededBits = 32; - mode = DECODE_CHKSUM; - return true; - } - } - - int type = input.PeekBits(3); - if (type < 0) { - return false; - } - input.DropBits(3); - - if ((type & 1) != 0) { - isLastBlock = true; - } - switch (type >> 1){ - case DeflaterConstants.STORED_BLOCK: - input.SkipToByteBoundary(); - mode = DECODE_STORED_LEN1; - break; - case DeflaterConstants.STATIC_TREES: - litlenTree = InflaterHuffmanTree.defLitLenTree; - distTree = InflaterHuffmanTree.defDistTree; - mode = DECODE_HUFFMAN; - break; - case DeflaterConstants.DYN_TREES: - dynHeader = new InflaterDynHeader(); - mode = DECODE_DYN_HEADER; - break; - default: - throw new SharpZipBaseException("Unknown block type " + type); - } - return true; - - case DECODE_STORED_LEN1: - { - if ((uncomprLen = input.PeekBits(16)) < 0) { - return false; - } - input.DropBits(16); - mode = DECODE_STORED_LEN2; - } - goto case DECODE_STORED_LEN2; // fall through - - case DECODE_STORED_LEN2: - { - int nlen = input.PeekBits(16); - if (nlen < 0) { - return false; - } - input.DropBits(16); - if (nlen != (uncomprLen ^ 0xffff)) { - throw new SharpZipBaseException("broken uncompressed block"); - } - mode = DECODE_STORED; - } - goto case DECODE_STORED; // fall through - - case DECODE_STORED: - { - int more = outputWindow.CopyStored(input, uncomprLen); - uncomprLen -= more; - if (uncomprLen == 0) { - mode = DECODE_BLOCKS; - return true; - } - return !input.IsNeedingInput; - } - - case DECODE_DYN_HEADER: - if (!dynHeader.Decode(input)) { - return false; - } - - litlenTree = dynHeader.BuildLitLenTree(); - distTree = dynHeader.BuildDistTree(); - mode = DECODE_HUFFMAN; - goto case DECODE_HUFFMAN; // fall through - - case DECODE_HUFFMAN: - case DECODE_HUFFMAN_LENBITS: - case DECODE_HUFFMAN_DIST: - case DECODE_HUFFMAN_DISTBITS: - return DecodeHuffman(); - - case FINISHED: - return false; - - default: - throw new SharpZipBaseException("Inflater.Decode unknown mode"); - } - } - - /// - /// Sets the preset dictionary. This should only be called, if - /// needsDictionary() returns true and it should set the same - /// dictionary, that was used for deflating. The getAdler() - /// function returns the checksum of the dictionary needed. - /// - /// - /// The dictionary. - /// - public void SetDictionary(byte[] buffer) - { - SetDictionary(buffer, 0, buffer.Length); - } - - /// - /// Sets the preset dictionary. This should only be called, if - /// needsDictionary() returns true and it should set the same - /// dictionary, that was used for deflating. The getAdler() - /// function returns the checksum of the dictionary needed. - /// - /// - /// The dictionary. - /// - /// - /// The index into buffer where the dictionary starts. - /// - /// - /// The number of bytes in the dictionary. - /// - /// - /// No dictionary is needed. - /// - /// - /// The adler checksum for the buffer is invalid - /// - public void SetDictionary(byte[] buffer, int index, int count) - { - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } + case DECODE_CHKSUM: + return DecodeChksum(); + + case DECODE_BLOCKS: + if (isLastBlock) { + if (noHeader) { + mode = FINISHED; + return false; + } else { + input.SkipToByteBoundary(); + neededBits = 32; + mode = DECODE_CHKSUM; + return true; + } + } + + int type = input.PeekBits(3); + if (type < 0) { + return false; + } + input.DropBits(3); + + if ((type & 1) != 0) { + isLastBlock = true; + } + switch (type >> 1){ + case DeflaterConstants.STORED_BLOCK: + input.SkipToByteBoundary(); + mode = DECODE_STORED_LEN1; + break; + case DeflaterConstants.STATIC_TREES: + litlenTree = InflaterHuffmanTree.defLitLenTree; + distTree = InflaterHuffmanTree.defDistTree; + mode = DECODE_HUFFMAN; + break; + case DeflaterConstants.DYN_TREES: + dynHeader = new InflaterDynHeader(); + mode = DECODE_DYN_HEADER; + break; + default: + throw new SharpZipBaseException("Unknown block type " + type); + } + return true; + + case DECODE_STORED_LEN1: + { + if ((uncomprLen = input.PeekBits(16)) < 0) { + return false; + } + input.DropBits(16); + mode = DECODE_STORED_LEN2; + } + goto case DECODE_STORED_LEN2; // fall through + + case DECODE_STORED_LEN2: + { + int nlen = input.PeekBits(16); + if (nlen < 0) { + return false; + } + input.DropBits(16); + if (nlen != (uncomprLen ^ 0xffff)) { + throw new SharpZipBaseException("broken uncompressed block"); + } + mode = DECODE_STORED; + } + goto case DECODE_STORED; // fall through + + case DECODE_STORED: + { + int more = outputWindow.CopyStored(input, uncomprLen); + uncomprLen -= more; + if (uncomprLen == 0) { + mode = DECODE_BLOCKS; + return true; + } + return !input.IsNeedingInput; + } + + case DECODE_DYN_HEADER: + if (!dynHeader.Decode(input)) { + return false; + } + + litlenTree = dynHeader.BuildLitLenTree(); + distTree = dynHeader.BuildDistTree(); + mode = DECODE_HUFFMAN; + goto case DECODE_HUFFMAN; // fall through + + case DECODE_HUFFMAN: + case DECODE_HUFFMAN_LENBITS: + case DECODE_HUFFMAN_DIST: + case DECODE_HUFFMAN_DISTBITS: + return DecodeHuffman(); + + case FINISHED: + return false; + + default: + throw new SharpZipBaseException("Inflater.Decode unknown mode"); + } + } + + /// + /// Sets the preset dictionary. This should only be called, if + /// needsDictionary() returns true and it should set the same + /// dictionary, that was used for deflating. The getAdler() + /// function returns the checksum of the dictionary needed. + /// + /// + /// The dictionary. + /// + public void SetDictionary(byte[] buffer) + { + SetDictionary(buffer, 0, buffer.Length); + } + + /// + /// Sets the preset dictionary. This should only be called, if + /// needsDictionary() returns true and it should set the same + /// dictionary, that was used for deflating. The getAdler() + /// function returns the checksum of the dictionary needed. + /// + /// + /// The dictionary. + /// + /// + /// The index into buffer where the dictionary starts. + /// + /// + /// The number of bytes in the dictionary. + /// + /// + /// No dictionary is needed. + /// + /// + /// The adler checksum for the buffer is invalid + /// + public void SetDictionary(byte[] buffer, int index, int count) + { + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } - if ( index < 0 ) { - throw new ArgumentOutOfRangeException("index"); - } + if ( index < 0 ) { + throw new ArgumentOutOfRangeException("index"); + } - if ( count < 0 ) { - throw new ArgumentOutOfRangeException("count"); - } + if ( count < 0 ) { + throw new ArgumentOutOfRangeException("count"); + } - if (!IsNeedingDictionary) { - throw new InvalidOperationException("Dictionary is not needed"); - } - - adler.Update(buffer, index, count); + if (!IsNeedingDictionary) { + throw new InvalidOperationException("Dictionary is not needed"); + } + + adler.Update(buffer, index, count); - if ((int)adler.Value != readAdler) { - throw new SharpZipBaseException("Wrong adler checksum"); - } - adler.Reset(); - outputWindow.CopyDict(buffer, index, count); - mode = DECODE_BLOCKS; - } - - /// - /// Sets the input. This should only be called, if needsInput() - /// returns true. - /// - /// - /// the input. - /// - public void SetInput(byte[] buffer) - { - SetInput(buffer, 0, buffer.Length); - } - - /// - /// Sets the input. This should only be called, if needsInput() - /// returns true. - /// - /// - /// The source of input data - /// - /// - /// The index into buffer where the input starts. - /// - /// - /// The number of bytes of input to use. - /// - /// - /// No input is needed. - /// - /// - /// The index and/or count are wrong. - /// - public void SetInput(byte[] buffer, int index, int count) - { - input.SetInput(buffer, index, count); - totalIn += (long)count; - } - - /// - /// Inflates the compressed stream to the output buffer. If this - /// returns 0, you should check, whether IsNeedingDictionary(), - /// IsNeedingInput() or IsFinished() returns true, to determine why no - /// further output is produced. - /// - /// - /// the output buffer. - /// - /// - /// The number of bytes written to the buffer, 0 if no further - /// output can be produced. - /// - /// - /// if buffer has length 0. - /// - /// - /// if deflated stream is invalid. - /// - public int Inflate(byte[] buffer) - { - if ( buffer == null ) - { - throw new ArgumentNullException("buffer"); - } + if ((int)adler.Value != readAdler) { + throw new SharpZipBaseException("Wrong adler checksum"); + } + adler.Reset(); + outputWindow.CopyDict(buffer, index, count); + mode = DECODE_BLOCKS; + } + + /// + /// Sets the input. This should only be called, if needsInput() + /// returns true. + /// + /// + /// the input. + /// + public void SetInput(byte[] buffer) + { + SetInput(buffer, 0, buffer.Length); + } + + /// + /// Sets the input. This should only be called, if needsInput() + /// returns true. + /// + /// + /// The source of input data + /// + /// + /// The index into buffer where the input starts. + /// + /// + /// The number of bytes of input to use. + /// + /// + /// No input is needed. + /// + /// + /// The index and/or count are wrong. + /// + public void SetInput(byte[] buffer, int index, int count) + { + input.SetInput(buffer, index, count); + totalIn += (long)count; + } + + /// + /// Inflates the compressed stream to the output buffer. If this + /// returns 0, you should check, whether IsNeedingDictionary(), + /// IsNeedingInput() or IsFinished() returns true, to determine why no + /// further output is produced. + /// + /// + /// the output buffer. + /// + /// + /// The number of bytes written to the buffer, 0 if no further + /// output can be produced. + /// + /// + /// if buffer has length 0. + /// + /// + /// if deflated stream is invalid. + /// + public int Inflate(byte[] buffer) + { + if ( buffer == null ) + { + throw new ArgumentNullException("buffer"); + } - return Inflate(buffer, 0, buffer.Length); - } - - /// - /// Inflates the compressed stream to the output buffer. If this - /// returns 0, you should check, whether needsDictionary(), - /// needsInput() or finished() returns true, to determine why no - /// further output is produced. - /// - /// - /// the output buffer. - /// - /// - /// the offset in buffer where storing starts. - /// - /// - /// the maximum number of bytes to output. - /// - /// - /// the number of bytes written to the buffer, 0 if no further output can be produced. - /// - /// - /// if count is less than 0. - /// - /// - /// if the index and / or count are wrong. - /// - /// - /// if deflated stream is invalid. - /// - public int Inflate(byte[] buffer, int offset, int count) - { - if ( buffer == null ) - { - throw new ArgumentNullException("buffer"); - } + return Inflate(buffer, 0, buffer.Length); + } + + /// + /// Inflates the compressed stream to the output buffer. If this + /// returns 0, you should check, whether needsDictionary(), + /// needsInput() or finished() returns true, to determine why no + /// further output is produced. + /// + /// + /// the output buffer. + /// + /// + /// the offset in buffer where storing starts. + /// + /// + /// the maximum number of bytes to output. + /// + /// + /// the number of bytes written to the buffer, 0 if no further output can be produced. + /// + /// + /// if count is less than 0. + /// + /// + /// if the index and / or count are wrong. + /// + /// + /// if deflated stream is invalid. + /// + public int Inflate(byte[] buffer, int offset, int count) + { + if ( buffer == null ) + { + throw new ArgumentNullException("buffer"); + } - if ( count < 0 ) { + if ( count < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "count cannot be negative"); + throw new ArgumentOutOfRangeException("count", "count cannot be negative"); #endif - } + } - if ( offset < 0 ) { + if ( offset < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "offset cannot be negative"); + throw new ArgumentOutOfRangeException("offset", "offset cannot be negative"); #endif - } + } - if ( offset + count > buffer.Length ) { - throw new ArgumentException("count exceeds buffer bounds"); - } + if ( offset + count > buffer.Length ) { + throw new ArgumentException("count exceeds buffer bounds"); + } - // Special case: count may be zero - if (count == 0) - { - if (!IsFinished) { // -jr- 08-Nov-2003 INFLATE_BUG fix.. - Decode(); - } - return 0; - } + // Special case: count may be zero + if (count == 0) + { + if (!IsFinished) { // -jr- 08-Nov-2003 INFLATE_BUG fix.. + Decode(); + } + return 0; + } - int bytesCopied = 0; + int bytesCopied = 0; - do { - if (mode != DECODE_CHKSUM) { - /* Don't give away any output, if we are waiting for the - * checksum in the input stream. - * - * With this trick we have always: - * IsNeedingInput() and not IsFinished() - * implies more output can be produced. - */ - int more = outputWindow.CopyOutput(buffer, offset, count); - if ( more > 0 ) { - adler.Update(buffer, offset, more); - offset += more; - bytesCopied += more; - totalOut += (long)more; - count -= more; - if (count == 0) { - return bytesCopied; - } - } - } - } while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM))); - return bytesCopied; - } - - /// - /// Returns true, if the input buffer is empty. - /// You should then call setInput(). - /// NOTE: This method also returns true when the stream is finished. - /// - public bool IsNeedingInput { - get { - return input.IsNeedingInput; - } - } - - /// - /// Returns true, if a preset dictionary is needed to inflate the input. - /// - public bool IsNeedingDictionary { - get { - return mode == DECODE_DICT && neededBits == 0; - } - } - - /// - /// Returns true, if the inflater has finished. This means, that no - /// input is needed and no output can be produced. - /// - public bool IsFinished { - get { - return mode == FINISHED && outputWindow.GetAvailable() == 0; - } - } - - /// - /// Gets the adler checksum. This is either the checksum of all - /// uncompressed bytes returned by inflate(), or if needsDictionary() - /// returns true (and thus no output was yet produced) this is the - /// adler checksum of the expected dictionary. - /// - /// - /// the adler checksum. - /// - public int Adler { - get { - return IsNeedingDictionary ? readAdler : (int) adler.Value; - } - } - - /// - /// Gets the total number of output bytes returned by Inflate(). - /// - /// - /// the total number of output bytes. - /// - public long TotalOut { - get { - return totalOut; - } - } - - /// - /// Gets the total number of processed compressed input bytes. - /// - /// - /// The total number of bytes of processed input bytes. - /// - public long TotalIn { - get { - return totalIn - (long)RemainingInput; - } - } - - /// - /// Gets the number of unprocessed input bytes. Useful, if the end of the - /// stream is reached and you want to further process the bytes after - /// the deflate stream. - /// - /// - /// The number of bytes of the input which have not been processed. - /// - public int RemainingInput { - // TODO: This should be a long? - get { - return input.AvailableBytes; - } - } - } + do { + if (mode != DECODE_CHKSUM) { + /* Don't give away any output, if we are waiting for the + * checksum in the input stream. + * + * With this trick we have always: + * IsNeedingInput() and not IsFinished() + * implies more output can be produced. + */ + int more = outputWindow.CopyOutput(buffer, offset, count); + if ( more > 0 ) { + adler.Update(buffer, offset, more); + offset += more; + bytesCopied += more; + totalOut += (long)more; + count -= more; + if (count == 0) { + return bytesCopied; + } + } + } + } while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM))); + return bytesCopied; + } + + /// + /// Returns true, if the input buffer is empty. + /// You should then call setInput(). + /// NOTE: This method also returns true when the stream is finished. + /// + public bool IsNeedingInput { + get { + return input.IsNeedingInput; + } + } + + /// + /// Returns true, if a preset dictionary is needed to inflate the input. + /// + public bool IsNeedingDictionary { + get { + return mode == DECODE_DICT && neededBits == 0; + } + } + + /// + /// Returns true, if the inflater has finished. This means, that no + /// input is needed and no output can be produced. + /// + public bool IsFinished { + get { + return mode == FINISHED && outputWindow.GetAvailable() == 0; + } + } + + /// + /// Gets the adler checksum. This is either the checksum of all + /// uncompressed bytes returned by inflate(), or if needsDictionary() + /// returns true (and thus no output was yet produced) this is the + /// adler checksum of the expected dictionary. + /// + /// + /// the adler checksum. + /// + public int Adler { + get { + return IsNeedingDictionary ? readAdler : (int) adler.Value; + } + } + + /// + /// Gets the total number of output bytes returned by Inflate(). + /// + /// + /// the total number of output bytes. + /// + public long TotalOut { + get { + return totalOut; + } + } + + /// + /// Gets the total number of processed compressed input bytes. + /// + /// + /// The total number of bytes of processed input bytes. + /// + public long TotalIn { + get { + return totalIn - (long)RemainingInput; + } + } + + /// + /// Gets the number of unprocessed input bytes. Useful, if the end of the + /// stream is reached and you want to further process the bytes after + /// the deflate stream. + /// + /// + /// The number of bytes of the input which have not been processed. + /// + public int RemainingInput { + // TODO: This should be a long? + get { + return input.AvailableBytes; + } + } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/InflaterDynHeader.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/InflaterDynHeader.cs index 77e87accd7..3f32336bd2 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/InflaterDynHeader.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/InflaterDynHeader.cs @@ -41,178 +41,178 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - - class InflaterDynHeader - { - #region Constants - const int LNUM = 0; - const int DNUM = 1; - const int BLNUM = 2; - const int BLLENS = 3; - const int LENS = 4; - const int REPS = 5; - - static readonly int[] repMin = { 3, 3, 11 }; - static readonly int[] repBits = { 2, 3, 7 }; + + class InflaterDynHeader + { + #region Constants + const int LNUM = 0; + const int DNUM = 1; + const int BLNUM = 2; + const int BLLENS = 3; + const int LENS = 4; + const int REPS = 5; + + static readonly int[] repMin = { 3, 3, 11 }; + static readonly int[] repBits = { 2, 3, 7 }; - static readonly int[] BL_ORDER = - { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; - - #endregion + static readonly int[] BL_ORDER = + { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + + #endregion - #region Constructors - public InflaterDynHeader() - { - } - #endregion - - public bool Decode(StreamManipulator input) - { - decode_loop: - for (;;) { - switch (mode) { - case LNUM: - lnum = input.PeekBits(5); - if (lnum < 0) { - return false; - } - lnum += 257; - input.DropBits(5); - // System.err.println("LNUM: "+lnum); - mode = DNUM; - goto case DNUM; // fall through - case DNUM: - dnum = input.PeekBits(5); - if (dnum < 0) { - return false; - } - dnum++; - input.DropBits(5); - // System.err.println("DNUM: "+dnum); - num = lnum+dnum; - litdistLens = new byte[num]; - mode = BLNUM; - goto case BLNUM; // fall through - case BLNUM: - blnum = input.PeekBits(4); - if (blnum < 0) { - return false; - } - blnum += 4; - input.DropBits(4); - blLens = new byte[19]; - ptr = 0; - // System.err.println("BLNUM: "+blnum); - mode = BLLENS; - goto case BLLENS; // fall through - case BLLENS: - while (ptr < blnum) { - int len = input.PeekBits(3); - if (len < 0) { - return false; - } - input.DropBits(3); - // System.err.println("blLens["+BL_ORDER[ptr]+"]: "+len); - blLens[BL_ORDER[ptr]] = (byte) len; - ptr++; - } - blTree = new InflaterHuffmanTree(blLens); - blLens = null; - ptr = 0; - mode = LENS; - goto case LENS; // fall through - case LENS: - { - int symbol; - while (((symbol = blTree.GetSymbol(input)) & ~15) == 0) { - /* Normal case: symbol in [0..15] */ - - // System.err.println("litdistLens["+ptr+"]: "+symbol); - litdistLens[ptr++] = lastLen = (byte)symbol; - - if (ptr == num) { - /* Finished */ - return true; - } - } - - /* need more input ? */ - if (symbol < 0) { - return false; - } - - /* otherwise repeat code */ - if (symbol >= 17) { - /* repeat zero */ - // System.err.println("repeating zero"); - lastLen = 0; - } else { - if (ptr == 0) { - throw new SharpZipBaseException(); - } - } - repSymbol = symbol-16; - } - mode = REPS; - goto case REPS; // fall through - case REPS: - { - int bits = repBits[repSymbol]; - int count = input.PeekBits(bits); - if (count < 0) { - return false; - } - input.DropBits(bits); - count += repMin[repSymbol]; - // System.err.println("litdistLens repeated: "+count); - - if (ptr + count > num) { - throw new SharpZipBaseException(); - } - while (count-- > 0) { - litdistLens[ptr++] = lastLen; - } - - if (ptr == num) { - /* Finished */ - return true; - } - } - mode = LENS; - goto decode_loop; - } - } - } - - public InflaterHuffmanTree BuildLitLenTree() - { - byte[] litlenLens = new byte[lnum]; - Array.Copy(litdistLens, 0, litlenLens, 0, lnum); - return new InflaterHuffmanTree(litlenLens); - } - - public InflaterHuffmanTree BuildDistTree() - { - byte[] distLens = new byte[dnum]; - Array.Copy(litdistLens, lnum, distLens, 0, dnum); - return new InflaterHuffmanTree(distLens); - } + #region Constructors + public InflaterDynHeader() + { + } + #endregion + + public bool Decode(StreamManipulator input) + { + decode_loop: + for (;;) { + switch (mode) { + case LNUM: + lnum = input.PeekBits(5); + if (lnum < 0) { + return false; + } + lnum += 257; + input.DropBits(5); + // System.err.println("LNUM: "+lnum); + mode = DNUM; + goto case DNUM; // fall through + case DNUM: + dnum = input.PeekBits(5); + if (dnum < 0) { + return false; + } + dnum++; + input.DropBits(5); + // System.err.println("DNUM: "+dnum); + num = lnum+dnum; + litdistLens = new byte[num]; + mode = BLNUM; + goto case BLNUM; // fall through + case BLNUM: + blnum = input.PeekBits(4); + if (blnum < 0) { + return false; + } + blnum += 4; + input.DropBits(4); + blLens = new byte[19]; + ptr = 0; + // System.err.println("BLNUM: "+blnum); + mode = BLLENS; + goto case BLLENS; // fall through + case BLLENS: + while (ptr < blnum) { + int len = input.PeekBits(3); + if (len < 0) { + return false; + } + input.DropBits(3); + // System.err.println("blLens["+BL_ORDER[ptr]+"]: "+len); + blLens[BL_ORDER[ptr]] = (byte) len; + ptr++; + } + blTree = new InflaterHuffmanTree(blLens); + blLens = null; + ptr = 0; + mode = LENS; + goto case LENS; // fall through + case LENS: + { + int symbol; + while (((symbol = blTree.GetSymbol(input)) & ~15) == 0) { + /* Normal case: symbol in [0..15] */ + + // System.err.println("litdistLens["+ptr+"]: "+symbol); + litdistLens[ptr++] = lastLen = (byte)symbol; + + if (ptr == num) { + /* Finished */ + return true; + } + } + + /* need more input ? */ + if (symbol < 0) { + return false; + } + + /* otherwise repeat code */ + if (symbol >= 17) { + /* repeat zero */ + // System.err.println("repeating zero"); + lastLen = 0; + } else { + if (ptr == 0) { + throw new SharpZipBaseException(); + } + } + repSymbol = symbol-16; + } + mode = REPS; + goto case REPS; // fall through + case REPS: + { + int bits = repBits[repSymbol]; + int count = input.PeekBits(bits); + if (count < 0) { + return false; + } + input.DropBits(bits); + count += repMin[repSymbol]; + // System.err.println("litdistLens repeated: "+count); + + if (ptr + count > num) { + throw new SharpZipBaseException(); + } + while (count-- > 0) { + litdistLens[ptr++] = lastLen; + } + + if (ptr == num) { + /* Finished */ + return true; + } + } + mode = LENS; + goto decode_loop; + } + } + } + + public InflaterHuffmanTree BuildLitLenTree() + { + byte[] litlenLens = new byte[lnum]; + Array.Copy(litdistLens, 0, litlenLens, 0, lnum); + return new InflaterHuffmanTree(litlenLens); + } + + public InflaterHuffmanTree BuildDistTree() + { + byte[] distLens = new byte[dnum]; + Array.Copy(litdistLens, lnum, distLens, 0, dnum); + return new InflaterHuffmanTree(distLens); + } - #region Instance Fields - byte[] blLens; - byte[] litdistLens; + #region Instance Fields + byte[] blLens; + byte[] litdistLens; - InflaterHuffmanTree blTree; + InflaterHuffmanTree blTree; /// /// The current decode mode /// - int mode; - int lnum, dnum, blnum, num; - int repSymbol; - byte lastLen; - int ptr; - #endregion + int mode; + int lnum, dnum, blnum, num; + int repSymbol; + byte lastLen; + int ptr; + #endregion - } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/InflaterHuffmanTree.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/InflaterHuffmanTree.cs index 2f61118303..acc0aa304d 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/InflaterHuffmanTree.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/InflaterHuffmanTree.cs @@ -41,192 +41,192 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - - /// - /// Huffman tree used for inflation - /// - public class InflaterHuffmanTree - { - #region Constants - const int MAX_BITLEN = 15; - #endregion + + /// + /// Huffman tree used for inflation + /// + public class InflaterHuffmanTree + { + #region Constants + const int MAX_BITLEN = 15; + #endregion - #region Instance Fields - short[] tree; - #endregion + #region Instance Fields + short[] tree; + #endregion - /// - /// Literal length tree - /// - public static InflaterHuffmanTree defLitLenTree; - - /// - /// Distance tree - /// - public static InflaterHuffmanTree defDistTree; - - static InflaterHuffmanTree() - { - try { - byte[] codeLengths = new byte[288]; - int i = 0; - while (i < 144) { - codeLengths[i++] = 8; - } - while (i < 256) { - codeLengths[i++] = 9; - } - while (i < 280) { - codeLengths[i++] = 7; - } - while (i < 288) { - codeLengths[i++] = 8; - } - defLitLenTree = new InflaterHuffmanTree(codeLengths); - - codeLengths = new byte[32]; - i = 0; - while (i < 32) { - codeLengths[i++] = 5; - } - defDistTree = new InflaterHuffmanTree(codeLengths); - } catch (Exception) { - throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal"); - } - } + /// + /// Literal length tree + /// + public static InflaterHuffmanTree defLitLenTree; + + /// + /// Distance tree + /// + public static InflaterHuffmanTree defDistTree; + + static InflaterHuffmanTree() + { + try { + byte[] codeLengths = new byte[288]; + int i = 0; + while (i < 144) { + codeLengths[i++] = 8; + } + while (i < 256) { + codeLengths[i++] = 9; + } + while (i < 280) { + codeLengths[i++] = 7; + } + while (i < 288) { + codeLengths[i++] = 8; + } + defLitLenTree = new InflaterHuffmanTree(codeLengths); + + codeLengths = new byte[32]; + i = 0; + while (i < 32) { + codeLengths[i++] = 5; + } + defDistTree = new InflaterHuffmanTree(codeLengths); + } catch (Exception) { + throw new SharpZipBaseException("InflaterHuffmanTree: static tree length illegal"); + } + } - #region Constructors - /// - /// Constructs a Huffman tree from the array of code lengths. - /// - /// - /// the array of code lengths - /// - public InflaterHuffmanTree(byte[] codeLengths) - { - BuildTree(codeLengths); - } - #endregion + #region Constructors + /// + /// Constructs a Huffman tree from the array of code lengths. + /// + /// + /// the array of code lengths + /// + public InflaterHuffmanTree(byte[] codeLengths) + { + BuildTree(codeLengths); + } + #endregion - void BuildTree(byte[] codeLengths) - { - int[] blCount = new int[MAX_BITLEN + 1]; - int[] nextCode = new int[MAX_BITLEN + 1]; - - for (int i = 0; i < codeLengths.Length; i++) { - int bits = codeLengths[i]; - if (bits > 0) { - blCount[bits]++; - } - } - - int code = 0; - int treeSize = 512; - for (int bits = 1; bits <= MAX_BITLEN; bits++) { - nextCode[bits] = code; - code += blCount[bits] << (16 - bits); - if (bits >= 10) { - /* We need an extra table for bit lengths >= 10. */ - int start = nextCode[bits] & 0x1ff80; - int end = code & 0x1ff80; - treeSize += (end - start) >> (16 - bits); - } - } - + void BuildTree(byte[] codeLengths) + { + int[] blCount = new int[MAX_BITLEN + 1]; + int[] nextCode = new int[MAX_BITLEN + 1]; + + for (int i = 0; i < codeLengths.Length; i++) { + int bits = codeLengths[i]; + if (bits > 0) { + blCount[bits]++; + } + } + + int code = 0; + int treeSize = 512; + for (int bits = 1; bits <= MAX_BITLEN; bits++) { + nextCode[bits] = code; + code += blCount[bits] << (16 - bits); + if (bits >= 10) { + /* We need an extra table for bit lengths >= 10. */ + int start = nextCode[bits] & 0x1ff80; + int end = code & 0x1ff80; + treeSize += (end - start) >> (16 - bits); + } + } + /* -jr comment this out! doesnt work for dynamic trees and pkzip 2.04g - if (code != 65536) - { - throw new SharpZipBaseException("Code lengths don't add up properly."); - } + if (code != 65536) + { + throw new SharpZipBaseException("Code lengths don't add up properly."); + } */ - /* Now create and fill the extra tables from longest to shortest - * bit len. This way the sub trees will be aligned. - */ - tree = new short[treeSize]; - int treePtr = 512; - for (int bits = MAX_BITLEN; bits >= 10; bits--) { - int end = code & 0x1ff80; - code -= blCount[bits] << (16 - bits); - int start = code & 0x1ff80; - for (int i = start; i < end; i += 1 << 7) { - tree[DeflaterHuffman.BitReverse(i)] = (short) ((-treePtr << 4) | bits); - treePtr += 1 << (bits-9); - } - } - - for (int i = 0; i < codeLengths.Length; i++) { - int bits = codeLengths[i]; - if (bits == 0) { - continue; - } - code = nextCode[bits]; - int revcode = DeflaterHuffman.BitReverse(code); - if (bits <= 9) { - do { - tree[revcode] = (short) ((i << 4) | bits); - revcode += 1 << bits; - } while (revcode < 512); - } else { - int subTree = tree[revcode & 511]; - int treeLen = 1 << (subTree & 15); - subTree = -(subTree >> 4); - do { - tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits); - revcode += 1 << bits; - } while (revcode < treeLen); - } - nextCode[bits] = code + (1 << (16 - bits)); - } - - } - - /// - /// Reads the next symbol from input. The symbol is encoded using the - /// huffman tree. - /// - /// - /// input the input source. - /// - /// - /// the next symbol, or -1 if not enough input is available. - /// - public int GetSymbol(StreamManipulator input) - { - int lookahead, symbol; - if ((lookahead = input.PeekBits(9)) >= 0) { - if ((symbol = tree[lookahead]) >= 0) { - input.DropBits(symbol & 15); - return symbol >> 4; - } - int subtree = -(symbol >> 4); - int bitlen = symbol & 15; - if ((lookahead = input.PeekBits(bitlen)) >= 0) { - symbol = tree[subtree | (lookahead >> 9)]; - input.DropBits(symbol & 15); - return symbol >> 4; - } else { - int bits = input.AvailableBits; - lookahead = input.PeekBits(bits); - symbol = tree[subtree | (lookahead >> 9)]; - if ((symbol & 15) <= bits) { - input.DropBits(symbol & 15); - return symbol >> 4; - } else { - return -1; - } - } - } else { - int bits = input.AvailableBits; - lookahead = input.PeekBits(bits); - symbol = tree[lookahead]; - if (symbol >= 0 && (symbol & 15) <= bits) { - input.DropBits(symbol & 15); - return symbol >> 4; - } else { - return -1; - } - } - } - } + /* Now create and fill the extra tables from longest to shortest + * bit len. This way the sub trees will be aligned. + */ + tree = new short[treeSize]; + int treePtr = 512; + for (int bits = MAX_BITLEN; bits >= 10; bits--) { + int end = code & 0x1ff80; + code -= blCount[bits] << (16 - bits); + int start = code & 0x1ff80; + for (int i = start; i < end; i += 1 << 7) { + tree[DeflaterHuffman.BitReverse(i)] = (short) ((-treePtr << 4) | bits); + treePtr += 1 << (bits-9); + } + } + + for (int i = 0; i < codeLengths.Length; i++) { + int bits = codeLengths[i]; + if (bits == 0) { + continue; + } + code = nextCode[bits]; + int revcode = DeflaterHuffman.BitReverse(code); + if (bits <= 9) { + do { + tree[revcode] = (short) ((i << 4) | bits); + revcode += 1 << bits; + } while (revcode < 512); + } else { + int subTree = tree[revcode & 511]; + int treeLen = 1 << (subTree & 15); + subTree = -(subTree >> 4); + do { + tree[subTree | (revcode >> 9)] = (short) ((i << 4) | bits); + revcode += 1 << bits; + } while (revcode < treeLen); + } + nextCode[bits] = code + (1 << (16 - bits)); + } + + } + + /// + /// Reads the next symbol from input. The symbol is encoded using the + /// huffman tree. + /// + /// + /// input the input source. + /// + /// + /// the next symbol, or -1 if not enough input is available. + /// + public int GetSymbol(StreamManipulator input) + { + int lookahead, symbol; + if ((lookahead = input.PeekBits(9)) >= 0) { + if ((symbol = tree[lookahead]) >= 0) { + input.DropBits(symbol & 15); + return symbol >> 4; + } + int subtree = -(symbol >> 4); + int bitlen = symbol & 15; + if ((lookahead = input.PeekBits(bitlen)) >= 0) { + symbol = tree[subtree | (lookahead >> 9)]; + input.DropBits(symbol & 15); + return symbol >> 4; + } else { + int bits = input.AvailableBits; + lookahead = input.PeekBits(bits); + symbol = tree[subtree | (lookahead >> 9)]; + if ((symbol & 15) <= bits) { + input.DropBits(symbol & 15); + return symbol >> 4; + } else { + return -1; + } + } + } else { + int bits = input.AvailableBits; + lookahead = input.PeekBits(bits); + symbol = tree[lookahead]; + if (symbol >= 0 && (symbol & 15) <= bits) { + input.DropBits(symbol & 15); + return symbol >> 4; + } else { + return -1; + } + } + } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/PendingBuffer.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/PendingBuffer.cs index d205845243..a210252053 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/PendingBuffer.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/PendingBuffer.cs @@ -41,255 +41,255 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression { - - /// - /// This class is general purpose class for writing data to a buffer. - /// - /// It allows you to write bits as well as bytes - /// Based on DeflaterPending.java - /// - /// author of the original java version : Jochen Hoenicke - /// - public class PendingBuffer - { - #region Instance Fields - /// - /// Internal work buffer - /// - byte[] buffer_; - - int start; - int end; - - uint bits; - int bitCount; - #endregion + + /// + /// This class is general purpose class for writing data to a buffer. + /// + /// It allows you to write bits as well as bytes + /// Based on DeflaterPending.java + /// + /// author of the original java version : Jochen Hoenicke + /// + public class PendingBuffer + { + #region Instance Fields + /// + /// Internal work buffer + /// + byte[] buffer_; + + int start; + int end; + + uint bits; + int bitCount; + #endregion - #region Constructors - /// - /// construct instance using default buffer size of 4096 - /// - public PendingBuffer() : this( 4096 ) - { - } - - /// - /// construct instance using specified buffer size - /// - /// - /// size to use for internal buffer - /// - public PendingBuffer(int bufferSize) - { - buffer_ = new byte[bufferSize]; - } + #region Constructors + /// + /// construct instance using default buffer size of 4096 + /// + public PendingBuffer() : this( 4096 ) + { + } + + /// + /// construct instance using specified buffer size + /// + /// + /// size to use for internal buffer + /// + public PendingBuffer(int bufferSize) + { + buffer_ = new byte[bufferSize]; + } - #endregion + #endregion - /// - /// Clear internal state/buffers - /// - public void Reset() - { - start = end = bitCount = 0; - } + /// + /// Clear internal state/buffers + /// + public void Reset() + { + start = end = bitCount = 0; + } - /// - /// Write a byte to buffer - /// - /// - /// The value to write - /// - public void WriteByte(int value) - { + /// + /// Write a byte to buffer + /// + /// + /// The value to write + /// + public void WriteByte(int value) + { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (start != 0) ) - { - throw new SharpZipBaseException("Debug check: start != 0"); - } + if (DeflaterConstants.DEBUGGING && (start != 0) ) + { + throw new SharpZipBaseException("Debug check: start != 0"); + } #endif - buffer_[end++] = unchecked((byte) value); - } + buffer_[end++] = unchecked((byte) value); + } - /// - /// Write a short value to buffer LSB first - /// - /// - /// The value to write. - /// - public void WriteShort(int value) - { + /// + /// Write a short value to buffer LSB first + /// + /// + /// The value to write. + /// + public void WriteShort(int value) + { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (start != 0) ) - { - throw new SharpZipBaseException("Debug check: start != 0"); - } + if (DeflaterConstants.DEBUGGING && (start != 0) ) + { + throw new SharpZipBaseException("Debug check: start != 0"); + } #endif - buffer_[end++] = unchecked((byte) value); - buffer_[end++] = unchecked((byte) (value >> 8)); - } + buffer_[end++] = unchecked((byte) value); + buffer_[end++] = unchecked((byte) (value >> 8)); + } - /// - /// write an integer LSB first - /// - /// The value to write. - public void WriteInt(int value) - { + /// + /// write an integer LSB first + /// + /// The value to write. + public void WriteInt(int value) + { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (start != 0) ) - { - throw new SharpZipBaseException("Debug check: start != 0"); - } + if (DeflaterConstants.DEBUGGING && (start != 0) ) + { + throw new SharpZipBaseException("Debug check: start != 0"); + } #endif - buffer_[end++] = unchecked((byte) value); - buffer_[end++] = unchecked((byte) (value >> 8)); - buffer_[end++] = unchecked((byte) (value >> 16)); - buffer_[end++] = unchecked((byte) (value >> 24)); - } - - /// - /// Write a block of data to buffer - /// - /// data to write - /// offset of first byte to write - /// number of bytes to write - public void WriteBlock(byte[] block, int offset, int length) - { + buffer_[end++] = unchecked((byte) value); + buffer_[end++] = unchecked((byte) (value >> 8)); + buffer_[end++] = unchecked((byte) (value >> 16)); + buffer_[end++] = unchecked((byte) (value >> 24)); + } + + /// + /// Write a block of data to buffer + /// + /// data to write + /// offset of first byte to write + /// number of bytes to write + public void WriteBlock(byte[] block, int offset, int length) + { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (start != 0) ) - { - throw new SharpZipBaseException("Debug check: start != 0"); - } + if (DeflaterConstants.DEBUGGING && (start != 0) ) + { + throw new SharpZipBaseException("Debug check: start != 0"); + } #endif - System.Array.Copy(block, offset, buffer_, end, length); - end += length; - } + System.Array.Copy(block, offset, buffer_, end, length); + end += length; + } - /// - /// The number of bits written to the buffer - /// - public int BitCount { - get { - return bitCount; - } - } - - /// - /// Align internal buffer on a byte boundary - /// - public void AlignToByte() - { + /// + /// The number of bits written to the buffer + /// + public int BitCount { + get { + return bitCount; + } + } + + /// + /// Align internal buffer on a byte boundary + /// + public void AlignToByte() + { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (start != 0) ) - { - throw new SharpZipBaseException("Debug check: start != 0"); - } + if (DeflaterConstants.DEBUGGING && (start != 0) ) + { + throw new SharpZipBaseException("Debug check: start != 0"); + } #endif - if (bitCount > 0) - { - buffer_[end++] = unchecked((byte) bits); - if (bitCount > 8) { - buffer_[end++] = unchecked((byte) (bits >> 8)); - } - } - bits = 0; - bitCount = 0; - } + if (bitCount > 0) + { + buffer_[end++] = unchecked((byte) bits); + if (bitCount > 8) { + buffer_[end++] = unchecked((byte) (bits >> 8)); + } + } + bits = 0; + bitCount = 0; + } - /// - /// Write bits to internal buffer - /// - /// source of bits - /// number of bits to write - public void WriteBits(int b, int count) - { + /// + /// Write bits to internal buffer + /// + /// source of bits + /// number of bits to write + public void WriteBits(int b, int count) + { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (start != 0) ) - { - throw new SharpZipBaseException("Debug check: start != 0"); - } + if (DeflaterConstants.DEBUGGING && (start != 0) ) + { + throw new SharpZipBaseException("Debug check: start != 0"); + } - // if (DeflaterConstants.DEBUGGING) { - // //Console.WriteLine("writeBits("+b+","+count+")"); - // } + // if (DeflaterConstants.DEBUGGING) { + // //Console.WriteLine("writeBits("+b+","+count+")"); + // } #endif - bits |= (uint)(b << bitCount); - bitCount += count; - if (bitCount >= 16) { - buffer_[end++] = unchecked((byte) bits); - buffer_[end++] = unchecked((byte) (bits >> 8)); - bits >>= 16; - bitCount -= 16; - } - } + bits |= (uint)(b << bitCount); + bitCount += count; + if (bitCount >= 16) { + buffer_[end++] = unchecked((byte) bits); + buffer_[end++] = unchecked((byte) (bits >> 8)); + bits >>= 16; + bitCount -= 16; + } + } - /// - /// Write a short value to internal buffer most significant byte first - /// - /// value to write - public void WriteShortMSB(int s) - { + /// + /// Write a short value to internal buffer most significant byte first + /// + /// value to write + public void WriteShortMSB(int s) + { #if DebugDeflation - if (DeflaterConstants.DEBUGGING && (start != 0) ) - { - throw new SharpZipBaseException("Debug check: start != 0"); - } + if (DeflaterConstants.DEBUGGING && (start != 0) ) + { + throw new SharpZipBaseException("Debug check: start != 0"); + } #endif - buffer_[end++] = unchecked((byte) (s >> 8)); - buffer_[end++] = unchecked((byte) s); - } - - /// - /// Indicates if buffer has been flushed - /// - public bool IsFlushed { - get { - return end == 0; - } - } - - /// - /// Flushes the pending buffer into the given output array. If the - /// output array is to small, only a partial flush is done. - /// - /// The output array. - /// The offset into output array. - /// The maximum number of bytes to store. - /// The number of bytes flushed. - public int Flush(byte[] output, int offset, int length) - { - if (bitCount >= 8) { - buffer_[end++] = unchecked((byte) bits); - bits >>= 8; - bitCount -= 8; - } + buffer_[end++] = unchecked((byte) (s >> 8)); + buffer_[end++] = unchecked((byte) s); + } + + /// + /// Indicates if buffer has been flushed + /// + public bool IsFlushed { + get { + return end == 0; + } + } + + /// + /// Flushes the pending buffer into the given output array. If the + /// output array is to small, only a partial flush is done. + /// + /// The output array. + /// The offset into output array. + /// The maximum number of bytes to store. + /// The number of bytes flushed. + public int Flush(byte[] output, int offset, int length) + { + if (bitCount >= 8) { + buffer_[end++] = unchecked((byte) bits); + bits >>= 8; + bitCount -= 8; + } - if (length > end - start) { - length = end - start; - System.Array.Copy(buffer_, start, output, offset, length); - start = 0; - end = 0; - } else { - System.Array.Copy(buffer_, start, output, offset, length); - start += length; - } - return length; - } + if (length > end - start) { + length = end - start; + System.Array.Copy(buffer_, start, output, offset, length); + start = 0; + end = 0; + } else { + System.Array.Copy(buffer_, start, output, offset, length); + start += length; + } + return length; + } - /// - /// Convert internal buffer to byte array. - /// Buffer is empty on completion - /// - /// - /// The internal buffer contents converted to a byte array. - /// - public byte[] ToByteArray() - { - byte[] result = new byte[end - start]; - System.Array.Copy(buffer_, start, result, 0, result.Length); - start = 0; - end = 0; - return result; - } - } -} + /// + /// Convert internal buffer to byte array. + /// Buffer is empty on completion + /// + /// + /// The internal buffer contents converted to a byte array. + /// + public byte[] ToByteArray() + { + byte[] result = new byte[end - start]; + System.Array.Copy(buffer_, start, result, 0, result.Length); + start = 0; + end = 0; + return result; + } + } +} diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs index 55bdb05a45..0f1dfc8962 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/DeflaterOutputStream.cs @@ -37,7 +37,7 @@ // exception statement from your version. // HISTORY -// 22-12-2009 DavidPierson Added AES support +// 22-12-2009 DavidPierson Added AES support using System; using System.IO; @@ -49,554 +49,554 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { - /// - /// A special stream deflating or compressing the bytes that are - /// written to it. It uses a Deflater to perform actual deflating.
    - /// Authors of the original java version : Tom Tromey, Jochen Hoenicke - ///
    - public class DeflaterOutputStream : Stream - { - #region Constructors - /// - /// Creates a new DeflaterOutputStream with a default Deflater and default buffer size. - /// - /// - /// the output stream where deflated output should be written. - /// - public DeflaterOutputStream(Stream baseOutputStream) - : this(baseOutputStream, new Deflater(), 512) - { - } - - /// - /// Creates a new DeflaterOutputStream with the given Deflater and - /// default buffer size. - /// - /// - /// the output stream where deflated output should be written. - /// - /// - /// the underlying deflater. - /// - public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater) - : this(baseOutputStream, deflater, 512) - { - } - - /// - /// Creates a new DeflaterOutputStream with the given Deflater and - /// buffer size. - /// - /// - /// The output stream where deflated output is written. - /// - /// - /// The underlying deflater to use - /// - /// - /// The buffer size in bytes to use when deflating (minimum value 512) - /// - /// - /// bufsize is less than or equal to zero. - /// - /// - /// baseOutputStream does not support writing - /// - /// - /// deflater instance is null - /// - public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufferSize) - { - if ( baseOutputStream == null ) { - throw new ArgumentNullException("baseOutputStream"); - } + /// + /// A special stream deflating or compressing the bytes that are + /// written to it. It uses a Deflater to perform actual deflating.
    + /// Authors of the original java version : Tom Tromey, Jochen Hoenicke + ///
    + public class DeflaterOutputStream : Stream + { + #region Constructors + /// + /// Creates a new DeflaterOutputStream with a default Deflater and default buffer size. + /// + /// + /// the output stream where deflated output should be written. + /// + public DeflaterOutputStream(Stream baseOutputStream) + : this(baseOutputStream, new Deflater(), 512) + { + } + + /// + /// Creates a new DeflaterOutputStream with the given Deflater and + /// default buffer size. + /// + /// + /// the output stream where deflated output should be written. + /// + /// + /// the underlying deflater. + /// + public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater) + : this(baseOutputStream, deflater, 512) + { + } + + /// + /// Creates a new DeflaterOutputStream with the given Deflater and + /// buffer size. + /// + /// + /// The output stream where deflated output is written. + /// + /// + /// The underlying deflater to use + /// + /// + /// The buffer size in bytes to use when deflating (minimum value 512) + /// + /// + /// bufsize is less than or equal to zero. + /// + /// + /// baseOutputStream does not support writing + /// + /// + /// deflater instance is null + /// + public DeflaterOutputStream(Stream baseOutputStream, Deflater deflater, int bufferSize) + { + if ( baseOutputStream == null ) { + throw new ArgumentNullException("baseOutputStream"); + } - if (baseOutputStream.CanWrite == false) { - throw new ArgumentException("Must support writing", "baseOutputStream"); - } + if (baseOutputStream.CanWrite == false) { + throw new ArgumentException("Must support writing", "baseOutputStream"); + } - if (deflater == null) { - throw new ArgumentNullException("deflater"); - } - - if (bufferSize < 512) { - throw new ArgumentOutOfRangeException("bufferSize"); - } - - baseOutputStream_ = baseOutputStream; - buffer_ = new byte[bufferSize]; - deflater_ = deflater; - } - #endregion - - #region Public API - /// - /// Finishes the stream by calling finish() on the deflater. - /// - /// - /// Not all input is deflated - /// - public virtual void Finish() - { - deflater_.Finish(); - while (!deflater_.IsFinished) { - int len = deflater_.Deflate(buffer_, 0, buffer_.Length); - if (len <= 0) { - break; - } + if (deflater == null) { + throw new ArgumentNullException("deflater"); + } + + if (bufferSize < 512) { + throw new ArgumentOutOfRangeException("bufferSize"); + } + + baseOutputStream_ = baseOutputStream; + buffer_ = new byte[bufferSize]; + deflater_ = deflater; + } + #endregion + + #region Public API + /// + /// Finishes the stream by calling finish() on the deflater. + /// + /// + /// Not all input is deflated + /// + public virtual void Finish() + { + deflater_.Finish(); + while (!deflater_.IsFinished) { + int len = deflater_.Deflate(buffer_, 0, buffer_.Length); + if (len <= 0) { + break; + } #if NETCF_1_0 - if ( keys != null ) { + if ( keys != null ) { #else - if (cryptoTransform_ != null) { -#endif - EncryptBlock(buffer_, 0, len); - } - - baseOutputStream_.Write(buffer_, 0, len); - } + if (cryptoTransform_ != null) { +#endif + EncryptBlock(buffer_, 0, len); + } + + baseOutputStream_.Write(buffer_, 0, len); + } - if (!deflater_.IsFinished) { - throw new SharpZipBaseException("Can't deflate all input?"); - } + if (!deflater_.IsFinished) { + throw new SharpZipBaseException("Can't deflate all input?"); + } - baseOutputStream_.Flush(); - + baseOutputStream_.Flush(); + #if NETCF_1_0 - if ( keys != null ) { - keys = null; - } + if ( keys != null ) { + keys = null; + } #else - if (cryptoTransform_ != null) { + if (cryptoTransform_ != null) { #if !NET_1_1 && !NETCF_2_0 - if (cryptoTransform_ is ZipAESTransform) { - AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); - } + if (cryptoTransform_ is ZipAESTransform) { + AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); + } #endif - cryptoTransform_.Dispose(); - cryptoTransform_ = null; - } -#endif - } - - /// - /// Get/set flag indicating ownership of the underlying stream. - /// When the flag is true will close the underlying stream also. - /// - public bool IsStreamOwner - { - get { return isStreamOwner_; } - set { isStreamOwner_ = value; } - } - - /// - /// Allows client to determine if an entry can be patched after its added - /// - public bool CanPatchEntries { - get { - return baseOutputStream_.CanSeek; - } - } - - #endregion - - #region Encryption - - string password; - + cryptoTransform_.Dispose(); + cryptoTransform_ = null; + } +#endif + } + + /// + /// Get/set flag indicating ownership of the underlying stream. + /// When the flag is true will close the underlying stream also. + /// + public bool IsStreamOwner + { + get { return isStreamOwner_; } + set { isStreamOwner_ = value; } + } + + /// + /// Allows client to determine if an entry can be patched after its added + /// + public bool CanPatchEntries { + get { + return baseOutputStream_.CanSeek; + } + } + + #endregion + + #region Encryption + + string password; + #if NETCF_1_0 - uint[] keys; + uint[] keys; #else - ICryptoTransform cryptoTransform_; + ICryptoTransform cryptoTransform_; - /// - /// Returns the 10 byte AUTH CODE to be appended immediately following the AES data stream. - /// - protected byte[] AESAuthCode; + /// + /// Returns the 10 byte AUTH CODE to be appended immediately following the AES data stream. + /// + protected byte[] AESAuthCode; #endif - - /// - /// Get/set the password used for encryption. - /// - /// When set to null or if the password is empty no encryption is performed - public string Password { - get { - return password; - } - set { - if ( (value != null) && (value.Length == 0) ) { - password = null; - } else { - password = value; - } - } - } + + /// + /// Get/set the password used for encryption. + /// + /// When set to null or if the password is empty no encryption is performed + public string Password { + get { + return password; + } + set { + if ( (value != null) && (value.Length == 0) ) { + password = null; + } else { + password = value; + } + } + } - /// - /// Encrypt a block of data - /// - /// - /// Data to encrypt. NOTE the original contents of the buffer are lost - /// - /// - /// Offset of first byte in buffer to encrypt - /// - /// - /// Number of bytes in buffer to encrypt - /// - protected void EncryptBlock(byte[] buffer, int offset, int length) - { + /// + /// Encrypt a block of data + /// + /// + /// Data to encrypt. NOTE the original contents of the buffer are lost + /// + /// + /// Offset of first byte in buffer to encrypt + /// + /// + /// Number of bytes in buffer to encrypt + /// + protected void EncryptBlock(byte[] buffer, int offset, int length) + { #if NETCF_1_0 - for (int i = offset; i < offset + length; ++i) { - byte oldbyte = buffer[i]; - buffer[i] ^= EncryptByte(); - UpdateKeys(oldbyte); - } + for (int i = offset; i < offset + length; ++i) { + byte oldbyte = buffer[i]; + buffer[i] ^= EncryptByte(); + UpdateKeys(oldbyte); + } #else - cryptoTransform_.TransformBlock(buffer, 0, length, buffer, 0); + cryptoTransform_.TransformBlock(buffer, 0, length, buffer, 0); #endif - } + } - /// - /// Initializes encryption keys based on given . - /// - /// The password. - protected void InitializePassword(string password) - { + /// + /// Initializes encryption keys based on given . + /// + /// The password. + protected void InitializePassword(string password) + { #if NETCF_1_0 - keys = new uint[] { - 0x12345678, - 0x23456789, - 0x34567890 - }; - - byte[] rawPassword = ZipConstants.ConvertToArray(password); - - for (int i = 0; i < rawPassword.Length; ++i) { - UpdateKeys((byte)rawPassword[i]); - } - -#else - PkzipClassicManaged pkManaged = new PkzipClassicManaged(); - byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); - cryptoTransform_ = pkManaged.CreateEncryptor(key, null); + keys = new uint[] { + 0x12345678, + 0x23456789, + 0x34567890 + }; + + byte[] rawPassword = ZipConstants.ConvertToArray(password); + + for (int i = 0; i < rawPassword.Length; ++i) { + UpdateKeys((byte)rawPassword[i]); + } + +#else + PkzipClassicManaged pkManaged = new PkzipClassicManaged(); + byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); + cryptoTransform_ = pkManaged.CreateEncryptor(key, null); #endif - } + } #if !NET_1_1 && !NETCF_2_0 - /// - /// Initializes encryption keys based on given password. - /// - protected void InitializeAESPassword(ZipEntry entry, string rawPassword, - out byte[] salt, out byte[] pwdVerifier) { - salt = new byte[entry.AESSaltLen]; - // Salt needs to be cryptographically random, and unique per file - if (_aesRnd == null) - _aesRnd = new RNGCryptoServiceProvider(); - _aesRnd.GetBytes(salt); - int blockSize = entry.AESKeySize / 8; // bits to bytes + /// + /// Initializes encryption keys based on given password. + /// + protected void InitializeAESPassword(ZipEntry entry, string rawPassword, + out byte[] salt, out byte[] pwdVerifier) { + salt = new byte[entry.AESSaltLen]; + // Salt needs to be cryptographically random, and unique per file + if (_aesRnd == null) + _aesRnd = new RNGCryptoServiceProvider(); + _aesRnd.GetBytes(salt); + int blockSize = entry.AESKeySize / 8; // bits to bytes - cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); - pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; - } + cryptoTransform_ = new ZipAESTransform(rawPassword, salt, blockSize, true); + pwdVerifier = ((ZipAESTransform)cryptoTransform_).PwdVerifier; + } #endif #if NETCF_1_0 - - /// - /// Encrypt a single byte - /// - /// - /// The encrypted value - /// - protected byte EncryptByte() - { - uint temp = ((keys[2] & 0xFFFF) | 2); - return (byte)((temp * (temp ^ 1)) >> 8); - } + + /// + /// Encrypt a single byte + /// + /// + /// The encrypted value + /// + protected byte EncryptByte() + { + uint temp = ((keys[2] & 0xFFFF) | 2); + return (byte)((temp * (temp ^ 1)) >> 8); + } - /// - /// Update encryption keys - /// - protected void UpdateKeys(byte ch) - { - keys[0] = Crc32.ComputeCrc32(keys[0], ch); - keys[1] = keys[1] + (byte)keys[0]; - keys[1] = keys[1] * 134775813 + 1; - keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24)); - } + /// + /// Update encryption keys + /// + protected void UpdateKeys(byte ch) + { + keys[0] = Crc32.ComputeCrc32(keys[0], ch); + keys[1] = keys[1] + (byte)keys[0]; + keys[1] = keys[1] * 134775813 + 1; + keys[2] = Crc32.ComputeCrc32(keys[2], (byte)(keys[1] >> 24)); + } #endif - #endregion + #endregion - #region Deflation Support - /// - /// Deflates everything in the input buffers. This will call - /// def.deflate() until all bytes from the input buffers - /// are processed. - /// - protected void Deflate() - { - while (!deflater_.IsNeedingInput) - { - int deflateCount = deflater_.Deflate(buffer_, 0, buffer_.Length); - - if (deflateCount <= 0) { - break; - } + #region Deflation Support + /// + /// Deflates everything in the input buffers. This will call + /// def.deflate() until all bytes from the input buffers + /// are processed. + /// + protected void Deflate() + { + while (!deflater_.IsNeedingInput) + { + int deflateCount = deflater_.Deflate(buffer_, 0, buffer_.Length); + + if (deflateCount <= 0) { + break; + } #if NETCF_1_0 - if (keys != null) + if (keys != null) #else - if (cryptoTransform_ != null) + if (cryptoTransform_ != null) #endif - { - EncryptBlock(buffer_, 0, deflateCount); - } - - baseOutputStream_.Write(buffer_, 0, deflateCount); - } - - if (!deflater_.IsNeedingInput) { - throw new SharpZipBaseException("DeflaterOutputStream can't deflate all input?"); - } - } - #endregion - - #region Stream Overrides - /// - /// Gets value indicating stream can be read from - /// - public override bool CanRead - { - get { - return false; - } - } - - /// - /// Gets a value indicating if seeking is supported for this stream - /// This property always returns false - /// - public override bool CanSeek { - get { - return false; - } - } - - /// - /// Get value indicating if this stream supports writing - /// - public override bool CanWrite { - get { - return baseOutputStream_.CanWrite; - } - } - - /// - /// Get current length of stream - /// - public override long Length { - get { - return baseOutputStream_.Length; - } - } - - /// - /// Gets the current position within the stream. - /// - /// Any attempt to set position - public override long Position { - get { - return baseOutputStream_.Position; - } - set { - throw new NotSupportedException("Position property not supported"); - } - } - - /// - /// Sets the current position of this stream to the given value. Not supported by this class! - /// - /// The offset relative to the to seek. - /// The to seek from. - /// The new position in the stream. - /// Any access - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException("DeflaterOutputStream Seek not supported"); - } - - /// - /// Sets the length of this stream to the given value. Not supported by this class! - /// - /// The new stream length. - /// Any access - public override void SetLength(long value) - { - throw new NotSupportedException("DeflaterOutputStream SetLength not supported"); - } - - /// - /// Read a byte from stream advancing position by one - /// - /// The byte read cast to an int. THe value is -1 if at the end of the stream. - /// Any access - public override int ReadByte() - { - throw new NotSupportedException("DeflaterOutputStream ReadByte not supported"); - } - - /// - /// Read a block of bytes from stream - /// - /// The buffer to store read data in. - /// The offset to start storing at. - /// The maximum number of bytes to read. - /// The actual number of bytes read. Zero if end of stream is detected. - /// Any access - public override int Read(byte[] buffer, int offset, int count) - { - throw new NotSupportedException("DeflaterOutputStream Read not supported"); - } - - /// - /// Asynchronous reads are not supported a NotSupportedException is always thrown - /// - /// The buffer to read into. - /// The offset to start storing data at. - /// The number of bytes to read - /// The async callback to use. - /// The state to use. - /// Returns an - /// Any access - public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - throw new NotSupportedException("DeflaterOutputStream BeginRead not currently supported"); - } - - /// - /// Asynchronous writes arent supported, a NotSupportedException is always thrown - /// - /// The buffer to write. - /// The offset to begin writing at. - /// The number of bytes to write. - /// The to use. - /// The state object. - /// Returns an IAsyncResult. - /// Any access - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - throw new NotSupportedException("BeginWrite is not supported"); - } - - /// - /// Flushes the stream by calling Flush on the deflater and then - /// on the underlying stream. This ensures that all bytes are flushed. - /// - public override void Flush() - { - deflater_.Flush(); - Deflate(); - baseOutputStream_.Flush(); - } - - /// - /// Calls and closes the underlying - /// stream when is true. - /// - public override void Close() - { - if ( !isClosed_ ) { - isClosed_ = true; + { + EncryptBlock(buffer_, 0, deflateCount); + } + + baseOutputStream_.Write(buffer_, 0, deflateCount); + } + + if (!deflater_.IsNeedingInput) { + throw new SharpZipBaseException("DeflaterOutputStream can't deflate all input?"); + } + } + #endregion + + #region Stream Overrides + /// + /// Gets value indicating stream can be read from + /// + public override bool CanRead + { + get { + return false; + } + } + + /// + /// Gets a value indicating if seeking is supported for this stream + /// This property always returns false + /// + public override bool CanSeek { + get { + return false; + } + } + + /// + /// Get value indicating if this stream supports writing + /// + public override bool CanWrite { + get { + return baseOutputStream_.CanWrite; + } + } + + /// + /// Get current length of stream + /// + public override long Length { + get { + return baseOutputStream_.Length; + } + } + + /// + /// Gets the current position within the stream. + /// + /// Any attempt to set position + public override long Position { + get { + return baseOutputStream_.Position; + } + set { + throw new NotSupportedException("Position property not supported"); + } + } + + /// + /// Sets the current position of this stream to the given value. Not supported by this class! + /// + /// The offset relative to the to seek. + /// The to seek from. + /// The new position in the stream. + /// Any access + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException("DeflaterOutputStream Seek not supported"); + } + + /// + /// Sets the length of this stream to the given value. Not supported by this class! + /// + /// The new stream length. + /// Any access + public override void SetLength(long value) + { + throw new NotSupportedException("DeflaterOutputStream SetLength not supported"); + } + + /// + /// Read a byte from stream advancing position by one + /// + /// The byte read cast to an int. THe value is -1 if at the end of the stream. + /// Any access + public override int ReadByte() + { + throw new NotSupportedException("DeflaterOutputStream ReadByte not supported"); + } + + /// + /// Read a block of bytes from stream + /// + /// The buffer to store read data in. + /// The offset to start storing at. + /// The maximum number of bytes to read. + /// The actual number of bytes read. Zero if end of stream is detected. + /// Any access + public override int Read(byte[] buffer, int offset, int count) + { + throw new NotSupportedException("DeflaterOutputStream Read not supported"); + } + + /// + /// Asynchronous reads are not supported a NotSupportedException is always thrown + /// + /// The buffer to read into. + /// The offset to start storing data at. + /// The number of bytes to read + /// The async callback to use. + /// The state to use. + /// Returns an + /// Any access + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + throw new NotSupportedException("DeflaterOutputStream BeginRead not currently supported"); + } + + /// + /// Asynchronous writes arent supported, a NotSupportedException is always thrown + /// + /// The buffer to write. + /// The offset to begin writing at. + /// The number of bytes to write. + /// The to use. + /// The state object. + /// Returns an IAsyncResult. + /// Any access + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + throw new NotSupportedException("BeginWrite is not supported"); + } + + /// + /// Flushes the stream by calling Flush on the deflater and then + /// on the underlying stream. This ensures that all bytes are flushed. + /// + public override void Flush() + { + deflater_.Flush(); + Deflate(); + baseOutputStream_.Flush(); + } + + /// + /// Calls and closes the underlying + /// stream when is true. + /// + public override void Close() + { + if ( !isClosed_ ) { + isClosed_ = true; - try { - Finish(); + try { + Finish(); #if NETCF_1_0 - keys=null; + keys=null; #else - if ( cryptoTransform_ != null ) { - GetAuthCodeIfAES(); - cryptoTransform_.Dispose(); - cryptoTransform_ = null; - } + if ( cryptoTransform_ != null ) { + GetAuthCodeIfAES(); + cryptoTransform_.Dispose(); + cryptoTransform_ = null; + } #endif - } - finally { - if( isStreamOwner_ ) { - baseOutputStream_.Close(); - } - } - } - } + } + finally { + if( isStreamOwner_ ) { + baseOutputStream_.Close(); + } + } + } + } - private void GetAuthCodeIfAES() { + private void GetAuthCodeIfAES() { #if !NET_1_1 && !NETCF_2_0 - if (cryptoTransform_ is ZipAESTransform) { - AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); - } + if (cryptoTransform_ is ZipAESTransform) { + AESAuthCode = ((ZipAESTransform)cryptoTransform_).GetAuthCode(); + } #endif - } + } - /// - /// Writes a single byte to the compressed output stream. - /// - /// - /// The byte value. - /// - public override void WriteByte(byte value) - { - byte[] b = new byte[1]; - b[0] = value; - Write(b, 0, 1); - } - - /// - /// Writes bytes from an array to the compressed stream. - /// - /// - /// The byte array - /// - /// - /// The offset into the byte array where to start. - /// - /// - /// The number of bytes to write. - /// - public override void Write(byte[] buffer, int offset, int count) - { - deflater_.SetInput(buffer, offset, count); - Deflate(); - } - #endregion - - #region Instance Fields - /// - /// This buffer is used temporarily to retrieve the bytes from the - /// deflater and write them to the underlying output stream. - /// - byte[] buffer_; - - /// - /// The deflater which is used to deflate the stream. - /// - protected Deflater deflater_; - - /// - /// Base stream the deflater depends on. - /// - protected Stream baseOutputStream_; + /// + /// Writes a single byte to the compressed output stream. + /// + /// + /// The byte value. + /// + public override void WriteByte(byte value) + { + byte[] b = new byte[1]; + b[0] = value; + Write(b, 0, 1); + } + + /// + /// Writes bytes from an array to the compressed stream. + /// + /// + /// The byte array + /// + /// + /// The offset into the byte array where to start. + /// + /// + /// The number of bytes to write. + /// + public override void Write(byte[] buffer, int offset, int count) + { + deflater_.SetInput(buffer, offset, count); + Deflate(); + } + #endregion + + #region Instance Fields + /// + /// This buffer is used temporarily to retrieve the bytes from the + /// deflater and write them to the underlying output stream. + /// + byte[] buffer_; + + /// + /// The deflater which is used to deflate the stream. + /// + protected Deflater deflater_; + + /// + /// Base stream the deflater depends on. + /// + protected Stream baseOutputStream_; - bool isClosed_; - - bool isStreamOwner_ = true; - #endregion + bool isClosed_; + + bool isStreamOwner_ = true; + #endregion - #region Static Fields + #region Static Fields #if !NET_1_1 && !NETCF_2_0 - // Static to help ensure that multiple files within a zip will get different random salt - private static RNGCryptoServiceProvider _aesRnd; + // Static to help ensure that multiple files within a zip will get different random salt + private static RNGCryptoServiceProvider _aesRnd; #endif - #endregion - } + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/InflaterInputStream.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/InflaterInputStream.cs index 669944441c..24be12320f 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/InflaterInputStream.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/InflaterInputStream.cs @@ -38,7 +38,7 @@ // exception statement from your version. // HISTORY -// 11-08-2009 GeoffHart T9121 Added Multi-member gzip support +// 11-08-2009 GeoffHart T9121 Added Multi-member gzip support using System; using System.IO; @@ -50,683 +50,683 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { - /// - /// An input buffer customised for use by - /// - /// - /// The buffer supports decryption of incoming data. - /// - public class InflaterInputBuffer - { - #region Constructors - /// - /// Initialise a new instance of with a default buffer size - /// - /// The stream to buffer. - public InflaterInputBuffer(Stream stream) : this(stream , 4096) - { - } - - /// - /// Initialise a new instance of - /// - /// The stream to buffer. - /// The size to use for the buffer - /// A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB. - public InflaterInputBuffer(Stream stream, int bufferSize) - { - inputStream = stream; - if ( bufferSize < 1024 ) { - bufferSize = 1024; - } - rawData = new byte[bufferSize]; - clearText = rawData; - } - #endregion + /// + /// An input buffer customised for use by + /// + /// + /// The buffer supports decryption of incoming data. + /// + public class InflaterInputBuffer + { + #region Constructors + /// + /// Initialise a new instance of with a default buffer size + /// + /// The stream to buffer. + public InflaterInputBuffer(Stream stream) : this(stream , 4096) + { + } + + /// + /// Initialise a new instance of + /// + /// The stream to buffer. + /// The size to use for the buffer + /// A minimum buffer size of 1KB is permitted. Lower sizes are treated as 1KB. + public InflaterInputBuffer(Stream stream, int bufferSize) + { + inputStream = stream; + if ( bufferSize < 1024 ) { + bufferSize = 1024; + } + rawData = new byte[bufferSize]; + clearText = rawData; + } + #endregion - /// - /// Get the length of bytes bytes in the - /// - public int RawLength - { - get { - return rawLength; - } - } - - /// - /// Get the contents of the raw data buffer. - /// - /// This may contain encrypted data. - public byte[] RawData - { - get { - return rawData; - } - } - - /// - /// Get the number of useable bytes in - /// - public int ClearTextLength - { - get { - return clearTextLength; - } - } - - /// - /// Get the contents of the clear text buffer. - /// - public byte[] ClearText - { - get { - return clearText; - } - } - - /// - /// Get/set the number of bytes available - /// - public int Available - { - get { return available; } - set { available = value; } - } + /// + /// Get the length of bytes bytes in the + /// + public int RawLength + { + get { + return rawLength; + } + } + + /// + /// Get the contents of the raw data buffer. + /// + /// This may contain encrypted data. + public byte[] RawData + { + get { + return rawData; + } + } + + /// + /// Get the number of useable bytes in + /// + public int ClearTextLength + { + get { + return clearTextLength; + } + } + + /// + /// Get the contents of the clear text buffer. + /// + public byte[] ClearText + { + get { + return clearText; + } + } + + /// + /// Get/set the number of bytes available + /// + public int Available + { + get { return available; } + set { available = value; } + } - /// - /// Call passing the current clear text buffer contents. - /// - /// The inflater to set input for. - public void SetInflaterInput(Inflater inflater) - { - if ( available > 0 ) { - inflater.SetInput(clearText, clearTextLength - available, available); - available = 0; - } - } + /// + /// Call passing the current clear text buffer contents. + /// + /// The inflater to set input for. + public void SetInflaterInput(Inflater inflater) + { + if ( available > 0 ) { + inflater.SetInput(clearText, clearTextLength - available, available); + available = 0; + } + } - /// - /// Fill the buffer from the underlying input stream. - /// - public void Fill() - { - rawLength = 0; - int toRead = rawData.Length; - - while (toRead > 0) { - int count = inputStream.Read(rawData, rawLength, toRead); - if ( count <= 0 ) { - break; - } - rawLength += count; - toRead -= count; - } - + /// + /// Fill the buffer from the underlying input stream. + /// + public void Fill() + { + rawLength = 0; + int toRead = rawData.Length; + + while (toRead > 0) { + int count = inputStream.Read(rawData, rawLength, toRead); + if ( count <= 0 ) { + break; + } + rawLength += count; + toRead -= count; + } + #if !NETCF_1_0 - if ( cryptoTransform != null ) { - clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0); - } - else -#endif - { - clearTextLength = rawLength; - } + if ( cryptoTransform != null ) { + clearTextLength = cryptoTransform.TransformBlock(rawData, 0, rawLength, clearText, 0); + } + else +#endif + { + clearTextLength = rawLength; + } - available = clearTextLength; - } - - /// - /// Read a buffer directly from the input stream - /// - /// The buffer to fill - /// Returns the number of bytes read. - public int ReadRawBuffer(byte[] buffer) - { - return ReadRawBuffer(buffer, 0, buffer.Length); - } + available = clearTextLength; + } + + /// + /// Read a buffer directly from the input stream + /// + /// The buffer to fill + /// Returns the number of bytes read. + public int ReadRawBuffer(byte[] buffer) + { + return ReadRawBuffer(buffer, 0, buffer.Length); + } - /// - /// Read a buffer directly from the input stream - /// - /// The buffer to read into - /// The offset to start reading data into. - /// The number of bytes to read. - /// Returns the number of bytes read. - public int ReadRawBuffer(byte[] outBuffer, int offset, int length) - { - if ( length < 0 ) { - throw new ArgumentOutOfRangeException("length"); - } - - int currentOffset = offset; - int currentLength = length; - - while ( currentLength > 0 ) { - if ( available <= 0 ) { - Fill(); - if (available <= 0) { - return 0; - } - } - int toCopy = Math.Min(currentLength, available); - System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy); - currentOffset += toCopy; - currentLength -= toCopy; - available -= toCopy; - } - return length; - } - - /// - /// Read clear text data from the input stream. - /// - /// The buffer to add data to. - /// The offset to start adding data at. - /// The number of bytes to read. - /// Returns the number of bytes actually read. - public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length) - { - if ( length < 0 ) { - throw new ArgumentOutOfRangeException("length"); - } - - int currentOffset = offset; - int currentLength = length; - - while ( currentLength > 0 ) { - if ( available <= 0 ) { - Fill(); - if (available <= 0) { - return 0; - } - } - - int toCopy = Math.Min(currentLength, available); - Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy); - currentOffset += toCopy; - currentLength -= toCopy; - available -= toCopy; - } - return length; - } - - /// - /// Read a from the input stream. - /// - /// Returns the byte read. - public int ReadLeByte() - { - if (available <= 0) { - Fill(); - if (available <= 0) { - throw new ZipException("EOF in header"); - } - } - byte result = rawData[rawLength - available]; - available -= 1; - return result; - } - - /// - /// Read an in little endian byte order. - /// - /// The short value read case to an int. - public int ReadLeShort() - { - return ReadLeByte() | (ReadLeByte() << 8); - } - - /// - /// Read an in little endian byte order. - /// - /// The int value read. - public int ReadLeInt() - { - return ReadLeShort() | (ReadLeShort() << 16); - } - - /// - /// Read a in little endian byte order. - /// - /// The long value read. - public long ReadLeLong() - { - return (uint)ReadLeInt() | ((long)ReadLeInt() << 32); - } + /// + /// Read a buffer directly from the input stream + /// + /// The buffer to read into + /// The offset to start reading data into. + /// The number of bytes to read. + /// Returns the number of bytes read. + public int ReadRawBuffer(byte[] outBuffer, int offset, int length) + { + if ( length < 0 ) { + throw new ArgumentOutOfRangeException("length"); + } + + int currentOffset = offset; + int currentLength = length; + + while ( currentLength > 0 ) { + if ( available <= 0 ) { + Fill(); + if (available <= 0) { + return 0; + } + } + int toCopy = Math.Min(currentLength, available); + System.Array.Copy(rawData, rawLength - (int)available, outBuffer, currentOffset, toCopy); + currentOffset += toCopy; + currentLength -= toCopy; + available -= toCopy; + } + return length; + } + + /// + /// Read clear text data from the input stream. + /// + /// The buffer to add data to. + /// The offset to start adding data at. + /// The number of bytes to read. + /// Returns the number of bytes actually read. + public int ReadClearTextBuffer(byte[] outBuffer, int offset, int length) + { + if ( length < 0 ) { + throw new ArgumentOutOfRangeException("length"); + } + + int currentOffset = offset; + int currentLength = length; + + while ( currentLength > 0 ) { + if ( available <= 0 ) { + Fill(); + if (available <= 0) { + return 0; + } + } + + int toCopy = Math.Min(currentLength, available); + Array.Copy(clearText, clearTextLength - (int)available, outBuffer, currentOffset, toCopy); + currentOffset += toCopy; + currentLength -= toCopy; + available -= toCopy; + } + return length; + } + + /// + /// Read a from the input stream. + /// + /// Returns the byte read. + public int ReadLeByte() + { + if (available <= 0) { + Fill(); + if (available <= 0) { + throw new ZipException("EOF in header"); + } + } + byte result = rawData[rawLength - available]; + available -= 1; + return result; + } + + /// + /// Read an in little endian byte order. + /// + /// The short value read case to an int. + public int ReadLeShort() + { + return ReadLeByte() | (ReadLeByte() << 8); + } + + /// + /// Read an in little endian byte order. + /// + /// The int value read. + public int ReadLeInt() + { + return ReadLeShort() | (ReadLeShort() << 16); + } + + /// + /// Read a in little endian byte order. + /// + /// The long value read. + public long ReadLeLong() + { + return (uint)ReadLeInt() | ((long)ReadLeInt() << 32); + } #if !NETCF_1_0 - /// - /// Get/set the to apply to any data. - /// - /// Set this value to null to have no transform applied. - public ICryptoTransform CryptoTransform - { - set { - cryptoTransform = value; - if ( cryptoTransform != null ) { - if ( rawData == clearText ) { - if ( internalClearText == null ) { - internalClearText = new byte[rawData.Length]; - } - clearText = internalClearText; - } - clearTextLength = rawLength; - if ( available > 0 ) { - cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available); - } - } else { - clearText = rawData; - clearTextLength = rawLength; - } - } - } + /// + /// Get/set the to apply to any data. + /// + /// Set this value to null to have no transform applied. + public ICryptoTransform CryptoTransform + { + set { + cryptoTransform = value; + if ( cryptoTransform != null ) { + if ( rawData == clearText ) { + if ( internalClearText == null ) { + internalClearText = new byte[rawData.Length]; + } + clearText = internalClearText; + } + clearTextLength = rawLength; + if ( available > 0 ) { + cryptoTransform.TransformBlock(rawData, rawLength - available, available, clearText, rawLength - available); + } + } else { + clearText = rawData; + clearTextLength = rawLength; + } + } + } #endif - #region Instance Fields - int rawLength; - byte[] rawData; - - int clearTextLength; - byte[] clearText; -#if !NETCF_1_0 - byte[] internalClearText; + #region Instance Fields + int rawLength; + byte[] rawData; + + int clearTextLength; + byte[] clearText; +#if !NETCF_1_0 + byte[] internalClearText; #endif - - int available; - + + int available; + #if !NETCF_1_0 - ICryptoTransform cryptoTransform; -#endif - Stream inputStream; - #endregion - } - - /// - /// This filter stream is used to decompress data compressed using the "deflate" - /// format. The "deflate" format is described in RFC 1951. - /// - /// This stream may form the basis for other decompression filters, such - /// as the GZipInputStream. - /// - /// Author of the original java version : John Leuner. - /// - public class InflaterInputStream : Stream - { - #region Constructors - /// - /// Create an InflaterInputStream with the default decompressor - /// and a default buffer size of 4KB. - /// - /// - /// The InputStream to read bytes from - /// - public InflaterInputStream(Stream baseInputStream) - : this(baseInputStream, new Inflater(), 4096) - { - } - - /// - /// Create an InflaterInputStream with the specified decompressor - /// and a default buffer size of 4KB. - /// - /// - /// The source of input data - /// - /// - /// The decompressor used to decompress data read from baseInputStream - /// - public InflaterInputStream(Stream baseInputStream, Inflater inf) - : this(baseInputStream, inf, 4096) - { - } - - /// - /// Create an InflaterInputStream with the specified decompressor - /// and the specified buffer size. - /// - /// - /// The InputStream to read bytes from - /// - /// - /// The decompressor to use - /// - /// - /// Size of the buffer to use - /// - public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize) - { - if (baseInputStream == null) { - throw new ArgumentNullException("baseInputStream"); - } - - if (inflater == null) { - throw new ArgumentNullException("inflater"); - } - - if (bufferSize <= 0) { - throw new ArgumentOutOfRangeException("bufferSize"); - } - - this.baseInputStream = baseInputStream; - this.inf = inflater; - - inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize); - } - - #endregion + ICryptoTransform cryptoTransform; +#endif + Stream inputStream; + #endregion + } + + /// + /// This filter stream is used to decompress data compressed using the "deflate" + /// format. The "deflate" format is described in RFC 1951. + /// + /// This stream may form the basis for other decompression filters, such + /// as the GZipInputStream. + /// + /// Author of the original java version : John Leuner. + /// + public class InflaterInputStream : Stream + { + #region Constructors + /// + /// Create an InflaterInputStream with the default decompressor + /// and a default buffer size of 4KB. + /// + /// + /// The InputStream to read bytes from + /// + public InflaterInputStream(Stream baseInputStream) + : this(baseInputStream, new Inflater(), 4096) + { + } + + /// + /// Create an InflaterInputStream with the specified decompressor + /// and a default buffer size of 4KB. + /// + /// + /// The source of input data + /// + /// + /// The decompressor used to decompress data read from baseInputStream + /// + public InflaterInputStream(Stream baseInputStream, Inflater inf) + : this(baseInputStream, inf, 4096) + { + } + + /// + /// Create an InflaterInputStream with the specified decompressor + /// and the specified buffer size. + /// + /// + /// The InputStream to read bytes from + /// + /// + /// The decompressor to use + /// + /// + /// Size of the buffer to use + /// + public InflaterInputStream(Stream baseInputStream, Inflater inflater, int bufferSize) + { + if (baseInputStream == null) { + throw new ArgumentNullException("baseInputStream"); + } + + if (inflater == null) { + throw new ArgumentNullException("inflater"); + } + + if (bufferSize <= 0) { + throw new ArgumentOutOfRangeException("bufferSize"); + } + + this.baseInputStream = baseInputStream; + this.inf = inflater; + + inputBuffer = new InflaterInputBuffer(baseInputStream, bufferSize); + } + + #endregion - /// - /// Get/set flag indicating ownership of underlying stream. - /// When the flag is true will close the underlying stream also. - /// - /// - /// The default value is true. - /// - public bool IsStreamOwner - { - get { return isStreamOwner; } - set { isStreamOwner = value; } - } - - /// - /// Skip specified number of bytes of uncompressed data - /// - /// - /// Number of bytes to skip - /// - /// - /// The number of bytes skipped, zero if the end of - /// stream has been reached - /// - /// - /// The number of bytes to skip is less than or equal to zero. - /// - public long Skip(long count) - { - if (count <= 0) { - throw new ArgumentOutOfRangeException("count"); - } - - // v0.80 Skip by seeking if underlying stream supports it... - if (baseInputStream.CanSeek) { - baseInputStream.Seek(count, SeekOrigin.Current); - return count; - } - else { - int length = 2048; - if (count < length) { - length = (int) count; - } + /// + /// Get/set flag indicating ownership of underlying stream. + /// When the flag is true will close the underlying stream also. + /// + /// + /// The default value is true. + /// + public bool IsStreamOwner + { + get { return isStreamOwner; } + set { isStreamOwner = value; } + } + + /// + /// Skip specified number of bytes of uncompressed data + /// + /// + /// Number of bytes to skip + /// + /// + /// The number of bytes skipped, zero if the end of + /// stream has been reached + /// + /// + /// The number of bytes to skip is less than or equal to zero. + /// + public long Skip(long count) + { + if (count <= 0) { + throw new ArgumentOutOfRangeException("count"); + } + + // v0.80 Skip by seeking if underlying stream supports it... + if (baseInputStream.CanSeek) { + baseInputStream.Seek(count, SeekOrigin.Current); + return count; + } + else { + int length = 2048; + if (count < length) { + length = (int) count; + } - byte[] tmp = new byte[length]; - int readCount = 1; - long toSkip = count; + byte[] tmp = new byte[length]; + int readCount = 1; + long toSkip = count; - while ((toSkip > 0) && (readCount > 0) ) { - if (toSkip < length) { - length = (int)toSkip; - } + while ((toSkip > 0) && (readCount > 0) ) { + if (toSkip < length) { + length = (int)toSkip; + } - readCount = baseInputStream.Read(tmp, 0, length); - toSkip -= readCount; - } + readCount = baseInputStream.Read(tmp, 0, length); + toSkip -= readCount; + } - return count - toSkip; - } - } - - /// - /// Clear any cryptographic state. - /// - protected void StopDecrypting() - { -#if !NETCF_1_0 - inputBuffer.CryptoTransform = null; -#endif - } + return count - toSkip; + } + } + + /// + /// Clear any cryptographic state. + /// + protected void StopDecrypting() + { +#if !NETCF_1_0 + inputBuffer.CryptoTransform = null; +#endif + } - /// - /// Returns 0 once the end of the stream (EOF) has been reached. - /// Otherwise returns 1. - /// - public virtual int Available - { - get { - return inf.IsFinished ? 0 : 1; - } - } - - /// - /// Fills the buffer with more data to decompress. - /// - /// - /// Stream ends early - /// - protected void Fill() - { - // Protect against redundant calls - if (inputBuffer.Available <= 0) { - inputBuffer.Fill(); - if (inputBuffer.Available <= 0) { - throw new SharpZipBaseException("Unexpected EOF"); - } - } - inputBuffer.SetInflaterInput(inf); - } + /// + /// Returns 0 once the end of the stream (EOF) has been reached. + /// Otherwise returns 1. + /// + public virtual int Available + { + get { + return inf.IsFinished ? 0 : 1; + } + } + + /// + /// Fills the buffer with more data to decompress. + /// + /// + /// Stream ends early + /// + protected void Fill() + { + // Protect against redundant calls + if (inputBuffer.Available <= 0) { + inputBuffer.Fill(); + if (inputBuffer.Available <= 0) { + throw new SharpZipBaseException("Unexpected EOF"); + } + } + inputBuffer.SetInflaterInput(inf); + } - #region Stream Overrides - /// - /// Gets a value indicating whether the current stream supports reading - /// - public override bool CanRead - { - get { - return baseInputStream.CanRead; - } - } - - /// - /// Gets a value of false indicating seeking is not supported for this stream. - /// - public override bool CanSeek { - get { - return false; - } - } - - /// - /// Gets a value of false indicating that this stream is not writeable. - /// - public override bool CanWrite { - get { - return false; - } - } - - /// - /// A value representing the length of the stream in bytes. - /// - public override long Length { - get { - return inputBuffer.RawLength; - } - } - - /// - /// The current position within the stream. - /// Throws a NotSupportedException when attempting to set the position - /// - /// Attempting to set the position - public override long Position { - get { - return baseInputStream.Position; - } - set { - throw new NotSupportedException("InflaterInputStream Position not supported"); - } - } - - /// - /// Flushes the baseInputStream - /// - public override void Flush() - { - baseInputStream.Flush(); - } - - /// - /// Sets the position within the current stream - /// Always throws a NotSupportedException - /// - /// The relative offset to seek to. - /// The defining where to seek from. - /// The new position in the stream. - /// Any access - public override long Seek(long offset, SeekOrigin origin) - { - throw new NotSupportedException("Seek not supported"); - } - - /// - /// Set the length of the current stream - /// Always throws a NotSupportedException - /// - /// The new length value for the stream. - /// Any access - public override void SetLength(long value) - { - throw new NotSupportedException("InflaterInputStream SetLength not supported"); - } - - /// - /// Writes a sequence of bytes to stream and advances the current position - /// This method always throws a NotSupportedException - /// - /// Thew buffer containing data to write. - /// The offset of the first byte to write. - /// The number of bytes to write. - /// Any access - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotSupportedException("InflaterInputStream Write not supported"); - } - - /// - /// Writes one byte to the current stream and advances the current position - /// Always throws a NotSupportedException - /// - /// The byte to write. - /// Any access - public override void WriteByte(byte value) - { - throw new NotSupportedException("InflaterInputStream WriteByte not supported"); - } - - /// - /// Entry point to begin an asynchronous write. Always throws a NotSupportedException. - /// - /// The buffer to write data from - /// Offset of first byte to write - /// The maximum number of bytes to write - /// The method to be called when the asynchronous write operation is completed - /// A user-provided object that distinguishes this particular asynchronous write request from other requests - /// An IAsyncResult that references the asynchronous write - /// Any access - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) - { - throw new NotSupportedException("InflaterInputStream BeginWrite not supported"); - } - - /// - /// Closes the input stream. When - /// is true the underlying stream is also closed. - /// - public override void Close() - { - if ( !isClosed ) { - isClosed = true; - if ( isStreamOwner ) { - baseInputStream.Close(); - } - } - } + #region Stream Overrides + /// + /// Gets a value indicating whether the current stream supports reading + /// + public override bool CanRead + { + get { + return baseInputStream.CanRead; + } + } + + /// + /// Gets a value of false indicating seeking is not supported for this stream. + /// + public override bool CanSeek { + get { + return false; + } + } + + /// + /// Gets a value of false indicating that this stream is not writeable. + /// + public override bool CanWrite { + get { + return false; + } + } + + /// + /// A value representing the length of the stream in bytes. + /// + public override long Length { + get { + return inputBuffer.RawLength; + } + } + + /// + /// The current position within the stream. + /// Throws a NotSupportedException when attempting to set the position + /// + /// Attempting to set the position + public override long Position { + get { + return baseInputStream.Position; + } + set { + throw new NotSupportedException("InflaterInputStream Position not supported"); + } + } + + /// + /// Flushes the baseInputStream + /// + public override void Flush() + { + baseInputStream.Flush(); + } + + /// + /// Sets the position within the current stream + /// Always throws a NotSupportedException + /// + /// The relative offset to seek to. + /// The defining where to seek from. + /// The new position in the stream. + /// Any access + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException("Seek not supported"); + } + + /// + /// Set the length of the current stream + /// Always throws a NotSupportedException + /// + /// The new length value for the stream. + /// Any access + public override void SetLength(long value) + { + throw new NotSupportedException("InflaterInputStream SetLength not supported"); + } + + /// + /// Writes a sequence of bytes to stream and advances the current position + /// This method always throws a NotSupportedException + /// + /// Thew buffer containing data to write. + /// The offset of the first byte to write. + /// The number of bytes to write. + /// Any access + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException("InflaterInputStream Write not supported"); + } + + /// + /// Writes one byte to the current stream and advances the current position + /// Always throws a NotSupportedException + /// + /// The byte to write. + /// Any access + public override void WriteByte(byte value) + { + throw new NotSupportedException("InflaterInputStream WriteByte not supported"); + } + + /// + /// Entry point to begin an asynchronous write. Always throws a NotSupportedException. + /// + /// The buffer to write data from + /// Offset of first byte to write + /// The maximum number of bytes to write + /// The method to be called when the asynchronous write operation is completed + /// A user-provided object that distinguishes this particular asynchronous write request from other requests + /// An IAsyncResult that references the asynchronous write + /// Any access + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + throw new NotSupportedException("InflaterInputStream BeginWrite not supported"); + } + + /// + /// Closes the input stream. When + /// is true the underlying stream is also closed. + /// + public override void Close() + { + if ( !isClosed ) { + isClosed = true; + if ( isStreamOwner ) { + baseInputStream.Close(); + } + } + } - /// - /// Reads decompressed data into the provided buffer byte array - /// - /// - /// The array to read and decompress data into - /// - /// - /// The offset indicating where the data should be placed - /// - /// - /// The number of bytes to decompress - /// - /// The number of bytes read. Zero signals the end of stream - /// - /// Inflater needs a dictionary - /// - public override int Read(byte[] buffer, int offset, int count) - { - if (inf.IsNeedingDictionary) - { - throw new SharpZipBaseException("Need a dictionary"); - } + /// + /// Reads decompressed data into the provided buffer byte array + /// + /// + /// The array to read and decompress data into + /// + /// + /// The offset indicating where the data should be placed + /// + /// + /// The number of bytes to decompress + /// + /// The number of bytes read. Zero signals the end of stream + /// + /// Inflater needs a dictionary + /// + public override int Read(byte[] buffer, int offset, int count) + { + if (inf.IsNeedingDictionary) + { + throw new SharpZipBaseException("Need a dictionary"); + } - int remainingBytes = count; - while (true) { - int bytesRead = inf.Inflate(buffer, offset, remainingBytes); - offset += bytesRead; - remainingBytes -= bytesRead; + int remainingBytes = count; + while (true) { + int bytesRead = inf.Inflate(buffer, offset, remainingBytes); + offset += bytesRead; + remainingBytes -= bytesRead; - if (remainingBytes == 0 || inf.IsFinished) { - break; - } + if (remainingBytes == 0 || inf.IsFinished) { + break; + } - if ( inf.IsNeedingInput ) { - Fill(); - } - else if ( bytesRead == 0 ) { - throw new ZipException("Dont know what to do"); - } - } - return count - remainingBytes; - } - #endregion + if ( inf.IsNeedingInput ) { + Fill(); + } + else if ( bytesRead == 0 ) { + throw new ZipException("Dont know what to do"); + } + } + return count - remainingBytes; + } + #endregion - #region Instance Fields - /// - /// Decompressor for this stream - /// - protected Inflater inf; + #region Instance Fields + /// + /// Decompressor for this stream + /// + protected Inflater inf; - /// - /// Input buffer for this stream. - /// - protected InflaterInputBuffer inputBuffer; + /// + /// Input buffer for this stream. + /// + protected InflaterInputBuffer inputBuffer; - /// - /// Base stream the inflater reads from. - /// - private Stream baseInputStream; - - /// - /// The compressed size - /// - protected long csize; + /// + /// Base stream the inflater reads from. + /// + private Stream baseInputStream; + + /// + /// The compressed size + /// + protected long csize; - /// - /// Flag indicating wether this instance has been closed or not. - /// - bool isClosed; + /// + /// Flag indicating wether this instance has been closed or not. + /// + bool isClosed; - /// - /// Flag indicating wether this instance is designated the stream owner. - /// When closing if this flag is true the underlying stream is closed. - /// - bool isStreamOwner = true; - #endregion - } + /// + /// Flag indicating wether this instance is designated the stream owner. + /// When closing if this flag is true the underlying stream is closed. + /// + bool isStreamOwner = true; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/OutputWindow.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/OutputWindow.cs index be828e2d85..6a96f5e10a 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/OutputWindow.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/OutputWindow.cs @@ -41,195 +41,195 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { - - /// - /// Contains the output from the Inflation process. - /// We need to have a window so that we can refer backwards into the output stream - /// to repeat stuff.
    - /// Author of the original java version : John Leuner - ///
    - public class OutputWindow - { - #region Constants - const int WindowSize = 1 << 15; - const int WindowMask = WindowSize - 1; - #endregion - - #region Instance Fields - byte[] window = new byte[WindowSize]; //The window is 2^15 bytes - int windowEnd; - int windowFilled; - #endregion - - /// - /// Write a byte to this output window - /// - /// value to write - /// - /// if window is full - /// - public void Write(int value) - { - if (windowFilled++ == WindowSize) { - throw new InvalidOperationException("Window full"); - } - window[windowEnd++] = (byte) value; - windowEnd &= WindowMask; - } - - - private void SlowRepeat(int repStart, int length, int distance) - { - while (length-- > 0) { - window[windowEnd++] = window[repStart++]; - windowEnd &= WindowMask; - repStart &= WindowMask; - } - } - - /// - /// Append a byte pattern already in the window itself - /// - /// length of pattern to copy - /// distance from end of window pattern occurs - /// - /// If the repeated data overflows the window - /// - public void Repeat(int length, int distance) - { - if ((windowFilled += length) > WindowSize) { - throw new InvalidOperationException("Window full"); - } - - int repStart = (windowEnd - distance) & WindowMask; - int border = WindowSize - length; - if ( (repStart <= border) && (windowEnd < border) ) { - if (length <= distance) { - System.Array.Copy(window, repStart, window, windowEnd, length); - windowEnd += length; - } else { - // We have to copy manually, since the repeat pattern overlaps. - while (length-- > 0) { - window[windowEnd++] = window[repStart++]; - } - } - } else { - SlowRepeat(repStart, length, distance); - } - } - - /// - /// Copy from input manipulator to internal window - /// - /// source of data - /// length of data to copy - /// the number of bytes copied - public int CopyStored(StreamManipulator input, int length) - { - length = Math.Min(Math.Min(length, WindowSize - windowFilled), input.AvailableBytes); - int copied; - - int tailLen = WindowSize - windowEnd; - if (length > tailLen) { - copied = input.CopyBytes(window, windowEnd, tailLen); - if (copied == tailLen) { - copied += input.CopyBytes(window, 0, length - tailLen); - } - } else { - copied = input.CopyBytes(window, windowEnd, length); - } - - windowEnd = (windowEnd + copied) & WindowMask; - windowFilled += copied; - return copied; - } - - /// - /// Copy dictionary to window - /// - /// source dictionary - /// offset of start in source dictionary - /// length of dictionary - /// - /// If window isnt empty - /// - public void CopyDict(byte[] dictionary, int offset, int length) - { - if ( dictionary == null ) { - throw new ArgumentNullException("dictionary"); - } + + /// + /// Contains the output from the Inflation process. + /// We need to have a window so that we can refer backwards into the output stream + /// to repeat stuff.
    + /// Author of the original java version : John Leuner + ///
    + public class OutputWindow + { + #region Constants + const int WindowSize = 1 << 15; + const int WindowMask = WindowSize - 1; + #endregion + + #region Instance Fields + byte[] window = new byte[WindowSize]; //The window is 2^15 bytes + int windowEnd; + int windowFilled; + #endregion + + /// + /// Write a byte to this output window + /// + /// value to write + /// + /// if window is full + /// + public void Write(int value) + { + if (windowFilled++ == WindowSize) { + throw new InvalidOperationException("Window full"); + } + window[windowEnd++] = (byte) value; + windowEnd &= WindowMask; + } + + + private void SlowRepeat(int repStart, int length, int distance) + { + while (length-- > 0) { + window[windowEnd++] = window[repStart++]; + windowEnd &= WindowMask; + repStart &= WindowMask; + } + } + + /// + /// Append a byte pattern already in the window itself + /// + /// length of pattern to copy + /// distance from end of window pattern occurs + /// + /// If the repeated data overflows the window + /// + public void Repeat(int length, int distance) + { + if ((windowFilled += length) > WindowSize) { + throw new InvalidOperationException("Window full"); + } + + int repStart = (windowEnd - distance) & WindowMask; + int border = WindowSize - length; + if ( (repStart <= border) && (windowEnd < border) ) { + if (length <= distance) { + System.Array.Copy(window, repStart, window, windowEnd, length); + windowEnd += length; + } else { + // We have to copy manually, since the repeat pattern overlaps. + while (length-- > 0) { + window[windowEnd++] = window[repStart++]; + } + } + } else { + SlowRepeat(repStart, length, distance); + } + } + + /// + /// Copy from input manipulator to internal window + /// + /// source of data + /// length of data to copy + /// the number of bytes copied + public int CopyStored(StreamManipulator input, int length) + { + length = Math.Min(Math.Min(length, WindowSize - windowFilled), input.AvailableBytes); + int copied; + + int tailLen = WindowSize - windowEnd; + if (length > tailLen) { + copied = input.CopyBytes(window, windowEnd, tailLen); + if (copied == tailLen) { + copied += input.CopyBytes(window, 0, length - tailLen); + } + } else { + copied = input.CopyBytes(window, windowEnd, length); + } + + windowEnd = (windowEnd + copied) & WindowMask; + windowFilled += copied; + return copied; + } + + /// + /// Copy dictionary to window + /// + /// source dictionary + /// offset of start in source dictionary + /// length of dictionary + /// + /// If window isnt empty + /// + public void CopyDict(byte[] dictionary, int offset, int length) + { + if ( dictionary == null ) { + throw new ArgumentNullException("dictionary"); + } - if (windowFilled > 0) { - throw new InvalidOperationException(); - } - - if (length > WindowSize) { - offset += length - WindowSize; - length = WindowSize; - } - System.Array.Copy(dictionary, offset, window, 0, length); - windowEnd = length & WindowMask; - } + if (windowFilled > 0) { + throw new InvalidOperationException(); + } + + if (length > WindowSize) { + offset += length - WindowSize; + length = WindowSize; + } + System.Array.Copy(dictionary, offset, window, 0, length); + windowEnd = length & WindowMask; + } - /// - /// Get remaining unfilled space in window - /// - /// Number of bytes left in window - public int GetFreeSpace() - { - return WindowSize - windowFilled; - } - - /// - /// Get bytes available for output in window - /// - /// Number of bytes filled - public int GetAvailable() - { - return windowFilled; - } + /// + /// Get remaining unfilled space in window + /// + /// Number of bytes left in window + public int GetFreeSpace() + { + return WindowSize - windowFilled; + } + + /// + /// Get bytes available for output in window + /// + /// Number of bytes filled + public int GetAvailable() + { + return windowFilled; + } - /// - /// Copy contents of window to output - /// - /// buffer to copy to - /// offset to start at - /// number of bytes to count - /// The number of bytes copied - /// - /// If a window underflow occurs - /// - public int CopyOutput(byte[] output, int offset, int len) - { - int copyEnd = windowEnd; - if (len > windowFilled) { - len = windowFilled; - } else { - copyEnd = (windowEnd - windowFilled + len) & WindowMask; - } - - int copied = len; - int tailLen = len - copyEnd; - - if (tailLen > 0) { - System.Array.Copy(window, WindowSize - tailLen, output, offset, tailLen); - offset += tailLen; - len = copyEnd; - } - System.Array.Copy(window, copyEnd - len, output, offset, len); - windowFilled -= copied; - if (windowFilled < 0) { - throw new InvalidOperationException(); - } - return copied; - } + /// + /// Copy contents of window to output + /// + /// buffer to copy to + /// offset to start at + /// number of bytes to count + /// The number of bytes copied + /// + /// If a window underflow occurs + /// + public int CopyOutput(byte[] output, int offset, int len) + { + int copyEnd = windowEnd; + if (len > windowFilled) { + len = windowFilled; + } else { + copyEnd = (windowEnd - windowFilled + len) & WindowMask; + } + + int copied = len; + int tailLen = len - copyEnd; + + if (tailLen > 0) { + System.Array.Copy(window, WindowSize - tailLen, output, offset, tailLen); + offset += tailLen; + len = copyEnd; + } + System.Array.Copy(window, copyEnd - len, output, offset, len); + windowFilled -= copied; + if (windowFilled < 0) { + throw new InvalidOperationException(); + } + return copied; + } - /// - /// Reset by clearing window so GetAvailable returns 0 - /// - public void Reset() - { - windowFilled = windowEnd = 0; - } - } + /// + /// Reset by clearing window so GetAvailable returns 0 + /// + public void Reset() + { + windowFilled = windowEnd = 0; + } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/StreamManipulator.cs b/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/StreamManipulator.cs index ac57e1ed46..9bf6927d04 100644 --- a/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/StreamManipulator.cs +++ b/External/Tools/AppMan/ZipLib/Zip/Compression/Streams/StreamManipulator.cs @@ -40,258 +40,258 @@ namespace ICSharpCode.SharpZipLib.Zip.Compression.Streams { - - /// - /// This class allows us to retrieve a specified number of bits from - /// the input buffer, as well as copy big byte blocks. - /// - /// It uses an int buffer to store up to 31 bits for direct - /// manipulation. This guarantees that we can get at least 16 bits, - /// but we only need at most 15, so this is all safe. - /// - /// There are some optimizations in this class, for example, you must - /// never peek more than 8 bits more than needed, and you must first - /// peek bits before you may drop them. This is not a general purpose - /// class but optimized for the behaviour of the Inflater. - /// - /// authors of the original java version : John Leuner, Jochen Hoenicke - /// - public class StreamManipulator - { - #region Constructors - /// - /// Constructs a default StreamManipulator with all buffers empty - /// - public StreamManipulator() - { - } - #endregion + + /// + /// This class allows us to retrieve a specified number of bits from + /// the input buffer, as well as copy big byte blocks. + /// + /// It uses an int buffer to store up to 31 bits for direct + /// manipulation. This guarantees that we can get at least 16 bits, + /// but we only need at most 15, so this is all safe. + /// + /// There are some optimizations in this class, for example, you must + /// never peek more than 8 bits more than needed, and you must first + /// peek bits before you may drop them. This is not a general purpose + /// class but optimized for the behaviour of the Inflater. + /// + /// authors of the original java version : John Leuner, Jochen Hoenicke + /// + public class StreamManipulator + { + #region Constructors + /// + /// Constructs a default StreamManipulator with all buffers empty + /// + public StreamManipulator() + { + } + #endregion - /// - /// Get the next sequence of bits but don't increase input pointer. bitCount must be - /// less or equal 16 and if this call succeeds, you must drop - /// at least n - 8 bits in the next call. - /// - /// The number of bits to peek. - /// - /// the value of the bits, or -1 if not enough bits available. */ - /// - public int PeekBits(int bitCount) - { - if (bitsInBuffer_ < bitCount) { - if (windowStart_ == windowEnd_) { - return -1; // ok - } - buffer_ |= (uint)((window_[windowStart_++] & 0xff | - (window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_); - bitsInBuffer_ += 16; - } - return (int)(buffer_ & ((1 << bitCount) - 1)); - } - - /// - /// Drops the next n bits from the input. You should have called PeekBits - /// with a bigger or equal n before, to make sure that enough bits are in - /// the bit buffer. - /// - /// The number of bits to drop. - public void DropBits(int bitCount) - { - buffer_ >>= bitCount; - bitsInBuffer_ -= bitCount; - } - - /// - /// Gets the next n bits and increases input pointer. This is equivalent - /// to followed by , except for correct error handling. - /// - /// The number of bits to retrieve. - /// - /// the value of the bits, or -1 if not enough bits available. - /// - public int GetBits(int bitCount) - { - int bits = PeekBits(bitCount); - if (bits >= 0) { - DropBits(bitCount); - } - return bits; - } - - /// - /// Gets the number of bits available in the bit buffer. This must be - /// only called when a previous PeekBits() returned -1. - /// - /// - /// the number of bits available. - /// - public int AvailableBits { - get { - return bitsInBuffer_; - } - } - - /// - /// Gets the number of bytes available. - /// - /// - /// The number of bytes available. - /// - public int AvailableBytes { - get { - return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3); - } - } - - /// - /// Skips to the next byte boundary. - /// - public void SkipToByteBoundary() - { - buffer_ >>= (bitsInBuffer_ & 7); - bitsInBuffer_ &= ~7; - } + /// + /// Get the next sequence of bits but don't increase input pointer. bitCount must be + /// less or equal 16 and if this call succeeds, you must drop + /// at least n - 8 bits in the next call. + /// + /// The number of bits to peek. + /// + /// the value of the bits, or -1 if not enough bits available. */ + /// + public int PeekBits(int bitCount) + { + if (bitsInBuffer_ < bitCount) { + if (windowStart_ == windowEnd_) { + return -1; // ok + } + buffer_ |= (uint)((window_[windowStart_++] & 0xff | + (window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_); + bitsInBuffer_ += 16; + } + return (int)(buffer_ & ((1 << bitCount) - 1)); + } + + /// + /// Drops the next n bits from the input. You should have called PeekBits + /// with a bigger or equal n before, to make sure that enough bits are in + /// the bit buffer. + /// + /// The number of bits to drop. + public void DropBits(int bitCount) + { + buffer_ >>= bitCount; + bitsInBuffer_ -= bitCount; + } + + /// + /// Gets the next n bits and increases input pointer. This is equivalent + /// to followed by , except for correct error handling. + /// + /// The number of bits to retrieve. + /// + /// the value of the bits, or -1 if not enough bits available. + /// + public int GetBits(int bitCount) + { + int bits = PeekBits(bitCount); + if (bits >= 0) { + DropBits(bitCount); + } + return bits; + } + + /// + /// Gets the number of bits available in the bit buffer. This must be + /// only called when a previous PeekBits() returned -1. + /// + /// + /// the number of bits available. + /// + public int AvailableBits { + get { + return bitsInBuffer_; + } + } + + /// + /// Gets the number of bytes available. + /// + /// + /// The number of bytes available. + /// + public int AvailableBytes { + get { + return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3); + } + } + + /// + /// Skips to the next byte boundary. + /// + public void SkipToByteBoundary() + { + buffer_ >>= (bitsInBuffer_ & 7); + bitsInBuffer_ &= ~7; + } - /// - /// Returns true when SetInput can be called - /// - public bool IsNeedingInput { - get { - return windowStart_ == windowEnd_; - } - } - - /// - /// Copies bytes from input buffer to output buffer starting - /// at output[offset]. You have to make sure, that the buffer is - /// byte aligned. If not enough bytes are available, copies fewer - /// bytes. - /// - /// - /// The buffer to copy bytes to. - /// - /// - /// The offset in the buffer at which copying starts - /// - /// - /// The length to copy, 0 is allowed. - /// - /// - /// The number of bytes copied, 0 if no bytes were available. - /// - /// - /// Length is less than zero - /// - /// - /// Bit buffer isnt byte aligned - /// - public int CopyBytes(byte[] output, int offset, int length) - { - if (length < 0) { - throw new ArgumentOutOfRangeException("length"); - } + /// + /// Returns true when SetInput can be called + /// + public bool IsNeedingInput { + get { + return windowStart_ == windowEnd_; + } + } + + /// + /// Copies bytes from input buffer to output buffer starting + /// at output[offset]. You have to make sure, that the buffer is + /// byte aligned. If not enough bytes are available, copies fewer + /// bytes. + /// + /// + /// The buffer to copy bytes to. + /// + /// + /// The offset in the buffer at which copying starts + /// + /// + /// The length to copy, 0 is allowed. + /// + /// + /// The number of bytes copied, 0 if no bytes were available. + /// + /// + /// Length is less than zero + /// + /// + /// Bit buffer isnt byte aligned + /// + public int CopyBytes(byte[] output, int offset, int length) + { + if (length < 0) { + throw new ArgumentOutOfRangeException("length"); + } - if ((bitsInBuffer_ & 7) != 0) { - // bits_in_buffer may only be 0 or a multiple of 8 - throw new InvalidOperationException("Bit buffer is not byte aligned!"); - } - - int count = 0; - while ((bitsInBuffer_ > 0) && (length > 0)) { - output[offset++] = (byte) buffer_; - buffer_ >>= 8; - bitsInBuffer_ -= 8; - length--; - count++; - } - - if (length == 0) { - return count; - } - - int avail = windowEnd_ - windowStart_; - if (length > avail) { - length = avail; - } - System.Array.Copy(window_, windowStart_, output, offset, length); - windowStart_ += length; - - if (((windowStart_ - windowEnd_) & 1) != 0) { - // We always want an even number of bytes in input, see peekBits - buffer_ = (uint)(window_[windowStart_++] & 0xff); - bitsInBuffer_ = 8; - } - return count + length; - } - - /// - /// Resets state and empties internal buffers - /// - public void Reset() - { - buffer_ = 0; - windowStart_ = windowEnd_ = bitsInBuffer_ = 0; - } + if ((bitsInBuffer_ & 7) != 0) { + // bits_in_buffer may only be 0 or a multiple of 8 + throw new InvalidOperationException("Bit buffer is not byte aligned!"); + } + + int count = 0; + while ((bitsInBuffer_ > 0) && (length > 0)) { + output[offset++] = (byte) buffer_; + buffer_ >>= 8; + bitsInBuffer_ -= 8; + length--; + count++; + } + + if (length == 0) { + return count; + } + + int avail = windowEnd_ - windowStart_; + if (length > avail) { + length = avail; + } + System.Array.Copy(window_, windowStart_, output, offset, length); + windowStart_ += length; + + if (((windowStart_ - windowEnd_) & 1) != 0) { + // We always want an even number of bytes in input, see peekBits + buffer_ = (uint)(window_[windowStart_++] & 0xff); + bitsInBuffer_ = 8; + } + return count + length; + } + + /// + /// Resets state and empties internal buffers + /// + public void Reset() + { + buffer_ = 0; + windowStart_ = windowEnd_ = bitsInBuffer_ = 0; + } - /// - /// Add more input for consumption. - /// Only call when IsNeedingInput returns true - /// - /// data to be input - /// offset of first byte of input - /// number of bytes of input to add. - public void SetInput(byte[] buffer, int offset, int count) - { - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } + /// + /// Add more input for consumption. + /// Only call when IsNeedingInput returns true + /// + /// data to be input + /// offset of first byte of input + /// number of bytes of input to add. + public void SetInput(byte[] buffer, int offset, int count) + { + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } - if ( offset < 0 ) { + if ( offset < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); -#endif - } + throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); +#endif + } - if ( count < 0 ) { + if ( count < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "Cannot be negative"); -#endif - } + throw new ArgumentOutOfRangeException("count", "Cannot be negative"); +#endif + } - if (windowStart_ < windowEnd_) { - throw new InvalidOperationException("Old input was not completely processed"); - } - - int end = offset + count; - - // We want to throw an ArrayIndexOutOfBoundsException early. - // Note the check also handles integer wrap around. - if ((offset > end) || (end > buffer.Length) ) { - throw new ArgumentOutOfRangeException("count"); - } - - if ((count & 1) != 0) { - // We always want an even number of bytes in input, see PeekBits - buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_); - bitsInBuffer_ += 8; - } - - window_ = buffer; - windowStart_ = offset; - windowEnd_ = end; - } + if (windowStart_ < windowEnd_) { + throw new InvalidOperationException("Old input was not completely processed"); + } + + int end = offset + count; + + // We want to throw an ArrayIndexOutOfBoundsException early. + // Note the check also handles integer wrap around. + if ((offset > end) || (end > buffer.Length) ) { + throw new ArgumentOutOfRangeException("count"); + } + + if ((count & 1) != 0) { + // We always want an even number of bytes in input, see PeekBits + buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_); + bitsInBuffer_ += 8; + } + + window_ = buffer; + windowStart_ = offset; + windowEnd_ = end; + } - #region Instance Fields - private byte[] window_; - private int windowStart_; - private int windowEnd_; + #region Instance Fields + private byte[] window_; + private int windowStart_; + private int windowEnd_; - private uint buffer_; - private int bitsInBuffer_; - #endregion - } + private uint buffer_; + private int bitsInBuffer_; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/FastZip.cs b/External/Tools/AppMan/ZipLib/Zip/FastZip.cs index 623eea00c2..521ebe4d2e 100644 --- a/External/Tools/AppMan/ZipLib/Zip/FastZip.cs +++ b/External/Tools/AppMan/ZipLib/Zip/FastZip.cs @@ -39,245 +39,245 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// FastZipEvents supports all events applicable to FastZip operations. - /// - public class FastZipEvents - { - /// - /// Delegate to invoke when processing directories. - /// - public ProcessDirectoryHandler ProcessDirectory; - - /// - /// Delegate to invoke when processing files. - /// - public ProcessFileHandler ProcessFile; - - /// - /// Delegate to invoke during processing of files. - /// - public ProgressHandler Progress; - - /// - /// Delegate to invoke when processing for a file has been completed. - /// - public CompletedFileHandler CompletedFile; - - /// - /// Delegate to invoke when processing directory failures. - /// - public DirectoryFailureHandler DirectoryFailure; - - /// - /// Delegate to invoke when processing file failures. - /// - public FileFailureHandler FileFailure; - - /// - /// Raise the directory failure event. - /// - /// The directory causing the failure. - /// The exception for this event. - /// A boolean indicating if execution should continue or not. - public bool OnDirectoryFailure(string directory, Exception e) - { - bool result = false; - DirectoryFailureHandler handler = DirectoryFailure; - - if ( handler != null ) { - ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); - handler(this, args); - result = args.ContinueRunning; - } - return result; - } - - /// - /// Fires the file failure handler delegate. - /// - /// The file causing the failure. - /// The exception for this failure. - /// A boolean indicating if execution should continue or not. - public bool OnFileFailure(string file, Exception e) - { - FileFailureHandler handler = FileFailure; + /// + /// FastZipEvents supports all events applicable to FastZip operations. + /// + public class FastZipEvents + { + /// + /// Delegate to invoke when processing directories. + /// + public ProcessDirectoryHandler ProcessDirectory; + + /// + /// Delegate to invoke when processing files. + /// + public ProcessFileHandler ProcessFile; + + /// + /// Delegate to invoke during processing of files. + /// + public ProgressHandler Progress; + + /// + /// Delegate to invoke when processing for a file has been completed. + /// + public CompletedFileHandler CompletedFile; + + /// + /// Delegate to invoke when processing directory failures. + /// + public DirectoryFailureHandler DirectoryFailure; + + /// + /// Delegate to invoke when processing file failures. + /// + public FileFailureHandler FileFailure; + + /// + /// Raise the directory failure event. + /// + /// The directory causing the failure. + /// The exception for this event. + /// A boolean indicating if execution should continue or not. + public bool OnDirectoryFailure(string directory, Exception e) + { + bool result = false; + DirectoryFailureHandler handler = DirectoryFailure; + + if ( handler != null ) { + ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); + handler(this, args); + result = args.ContinueRunning; + } + return result; + } + + /// + /// Fires the file failure handler delegate. + /// + /// The file causing the failure. + /// The exception for this failure. + /// A boolean indicating if execution should continue or not. + public bool OnFileFailure(string file, Exception e) + { + FileFailureHandler handler = FileFailure; bool result = (handler != null); - if ( result ) { - ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); - handler(this, args); - result = args.ContinueRunning; - } - return result; - } - - /// - /// Fires the ProcessFile delegate. - /// - /// The file being processed. - /// A boolean indicating if execution should continue or not. - public bool OnProcessFile(string file) - { - bool result = true; - ProcessFileHandler handler = ProcessFile; - - if ( handler != null ) { - ScanEventArgs args = new ScanEventArgs(file); - handler(this, args); - result = args.ContinueRunning; - } - return result; - } - - /// + if ( result ) { + ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); + handler(this, args); + result = args.ContinueRunning; + } + return result; + } + + /// + /// Fires the ProcessFile delegate. + /// + /// The file being processed. + /// A boolean indicating if execution should continue or not. + public bool OnProcessFile(string file) + { + bool result = true; + ProcessFileHandler handler = ProcessFile; + + if ( handler != null ) { + ScanEventArgs args = new ScanEventArgs(file); + handler(this, args); + result = args.ContinueRunning; + } + return result; + } + + /// /// Fires the delegate - /// - /// The file whose processing has been completed. - /// A boolean indicating if execution should continue or not. - public bool OnCompletedFile(string file) - { - bool result = true; - CompletedFileHandler handler = CompletedFile; - if ( handler != null ) { - ScanEventArgs args = new ScanEventArgs(file); - handler(this, args); - result = args.ContinueRunning; - } - return result; - } - - /// - /// Fires the process directory delegate. - /// - /// The directory being processed. - /// Flag indicating if the directory has matching files as determined by the current filter. - /// A of true if the operation should continue; false otherwise. - public bool OnProcessDirectory(string directory, bool hasMatchingFiles) - { - bool result = true; - ProcessDirectoryHandler handler = ProcessDirectory; - if ( handler != null ) { - DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); - handler(this, args); - result = args.ContinueRunning; - } - return result; - } - - /// - /// The minimum timespan between events. - /// - /// The minimum period of time between events. - /// + /// + /// The file whose processing has been completed. + /// A boolean indicating if execution should continue or not. + public bool OnCompletedFile(string file) + { + bool result = true; + CompletedFileHandler handler = CompletedFile; + if ( handler != null ) { + ScanEventArgs args = new ScanEventArgs(file); + handler(this, args); + result = args.ContinueRunning; + } + return result; + } + + /// + /// Fires the process directory delegate. + /// + /// The directory being processed. + /// Flag indicating if the directory has matching files as determined by the current filter. + /// A of true if the operation should continue; false otherwise. + public bool OnProcessDirectory(string directory, bool hasMatchingFiles) + { + bool result = true; + ProcessDirectoryHandler handler = ProcessDirectory; + if ( handler != null ) { + DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); + handler(this, args); + result = args.ContinueRunning; + } + return result; + } + + /// + /// The minimum timespan between events. + /// + /// The minimum period of time between events. + /// /// The default interval is three seconds. - public TimeSpan ProgressInterval - { - get { return progressInterval_; } - set { progressInterval_ = value; } - } - - #region Instance Fields - TimeSpan progressInterval_ = TimeSpan.FromSeconds(3); - #endregion - } - - /// - /// FastZip provides facilities for creating and extracting zip files. - /// - public class FastZip - { - #region Enumerations - /// - /// Defines the desired handling when overwriting files during extraction. - /// - public enum Overwrite - { - /// - /// Prompt the user to confirm overwriting - /// - Prompt, - /// - /// Never overwrite files. - /// - Never, - /// - /// Always overwrite files. - /// - Always - } - #endregion - - #region Constructors - /// - /// Initialise a default instance of . - /// - public FastZip() - { - } - - /// - /// Initialise a new instance of - /// - /// The events to use during operations. - public FastZip(FastZipEvents events) - { - events_ = events; - } - #endregion - - #region Properties - /// - /// Get/set a value indicating wether empty directories should be created. - /// - public bool CreateEmptyDirectories - { - get { return createEmptyDirectories_; } - set { createEmptyDirectories_ = value; } - } + public TimeSpan ProgressInterval + { + get { return progressInterval_; } + set { progressInterval_ = value; } + } + + #region Instance Fields + TimeSpan progressInterval_ = TimeSpan.FromSeconds(3); + #endregion + } + + /// + /// FastZip provides facilities for creating and extracting zip files. + /// + public class FastZip + { + #region Enumerations + /// + /// Defines the desired handling when overwriting files during extraction. + /// + public enum Overwrite + { + /// + /// Prompt the user to confirm overwriting + /// + Prompt, + /// + /// Never overwrite files. + /// + Never, + /// + /// Always overwrite files. + /// + Always + } + #endregion + + #region Constructors + /// + /// Initialise a default instance of . + /// + public FastZip() + { + } + + /// + /// Initialise a new instance of + /// + /// The events to use during operations. + public FastZip(FastZipEvents events) + { + events_ = events; + } + #endregion + + #region Properties + /// + /// Get/set a value indicating wether empty directories should be created. + /// + public bool CreateEmptyDirectories + { + get { return createEmptyDirectories_; } + set { createEmptyDirectories_ = value; } + } #if !NETCF_1_0 - /// - /// Get / set the password value. - /// - public string Password - { - get { return password_; } - set { password_ = value; } - } + /// + /// Get / set the password value. + /// + public string Password + { + get { return password_; } + set { password_ = value; } + } #endif - /// - /// Get or set the active when creating Zip files. - /// - /// - public INameTransform NameTransform - { - get { return entryFactory_.NameTransform; } - set { - entryFactory_.NameTransform = value; - } - } - - /// - /// Get or set the active when creating Zip files. - /// - public IEntryFactory EntryFactory - { - get { return entryFactory_; } - set { - if ( value == null ) { - entryFactory_ = new ZipEntryFactory(); - } - else { - entryFactory_ = value; - } - } - } - - /// - /// Gets or sets the setting for Zip64 handling when writing. - /// + /// + /// Get or set the active when creating Zip files. + /// + /// + public INameTransform NameTransform + { + get { return entryFactory_.NameTransform; } + set { + entryFactory_.NameTransform = value; + } + } + + /// + /// Get or set the active when creating Zip files. + /// + public IEntryFactory EntryFactory + { + get { return entryFactory_; } + set { + if ( value == null ) { + entryFactory_ = new ZipEntryFactory(); + } + else { + entryFactory_ = value; + } + } + } + + /// + /// Gets or sets the setting for Zip64 handling when writing. + /// /// /// The default value is dynamic which is not backwards compatible with old /// programs and can cause problems with XP's built in compression which cant @@ -286,231 +286,231 @@ public IEntryFactory EntryFactory /// NOTE: Setting the size for entries before they are added is the best solution! /// By default the EntryFactory used by FastZip will set fhe file size. /// - public UseZip64 UseZip64 - { - get { return useZip64_; } - set { useZip64_ = value; } - } - - /// - /// Get/set a value indicating wether file dates and times should - /// be restored when extracting files from an archive. - /// - /// The default value is false. - public bool RestoreDateTimeOnExtract - { - get { - return restoreDateTimeOnExtract_; - } - set { - restoreDateTimeOnExtract_ = value; - } - } - - /// - /// Get/set a value indicating wether file attributes should - /// be restored during extract operations - /// - public bool RestoreAttributesOnExtract - { - get { return restoreAttributesOnExtract_; } - set { restoreAttributesOnExtract_ = value; } - } - #endregion - - #region Delegates - /// - /// Delegate called when confirming overwriting of files. - /// - public delegate bool ConfirmOverwriteDelegate(string fileName); - #endregion - - #region CreateZip - /// - /// Create a zip file. - /// - /// The name of the zip file to create. - /// The directory to source files from. - /// True to recurse directories, false for no recursion. - /// The file filter to apply. - /// The directory filter to apply. - public void CreateZip(string zipFileName, string sourceDirectory, - bool recurse, string fileFilter, string directoryFilter) - { - CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, directoryFilter); - } - - /// - /// Create a zip file/archive. - /// - /// The name of the zip file to create. - /// The directory to obtain files and directories from. - /// True to recurse directories, false for no recursion. - /// The file filter to apply. - public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter) - { - CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, null); - } - - /// - /// Create a zip archive sending output to the passed. - /// - /// The stream to write archive data to. - /// The directory to source files from. - /// True to recurse directories, false for no recursion. - /// The file filter to apply. - /// The directory filter to apply. + public UseZip64 UseZip64 + { + get { return useZip64_; } + set { useZip64_ = value; } + } + + /// + /// Get/set a value indicating wether file dates and times should + /// be restored when extracting files from an archive. + /// + /// The default value is false. + public bool RestoreDateTimeOnExtract + { + get { + return restoreDateTimeOnExtract_; + } + set { + restoreDateTimeOnExtract_ = value; + } + } + + /// + /// Get/set a value indicating wether file attributes should + /// be restored during extract operations + /// + public bool RestoreAttributesOnExtract + { + get { return restoreAttributesOnExtract_; } + set { restoreAttributesOnExtract_ = value; } + } + #endregion + + #region Delegates + /// + /// Delegate called when confirming overwriting of files. + /// + public delegate bool ConfirmOverwriteDelegate(string fileName); + #endregion + + #region CreateZip + /// + /// Create a zip file. + /// + /// The name of the zip file to create. + /// The directory to source files from. + /// True to recurse directories, false for no recursion. + /// The file filter to apply. + /// The directory filter to apply. + public void CreateZip(string zipFileName, string sourceDirectory, + bool recurse, string fileFilter, string directoryFilter) + { + CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, directoryFilter); + } + + /// + /// Create a zip file/archive. + /// + /// The name of the zip file to create. + /// The directory to obtain files and directories from. + /// True to recurse directories, false for no recursion. + /// The file filter to apply. + public void CreateZip(string zipFileName, string sourceDirectory, bool recurse, string fileFilter) + { + CreateZip(File.Create(zipFileName), sourceDirectory, recurse, fileFilter, null); + } + + /// + /// Create a zip archive sending output to the passed. + /// + /// The stream to write archive data to. + /// The directory to source files from. + /// True to recurse directories, false for no recursion. + /// The file filter to apply. + /// The directory filter to apply. /// The is closed after creation. - public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) - { - NameTransform = new ZipNameTransform(sourceDirectory); - sourceDirectory_ = sourceDirectory; + public void CreateZip(Stream outputStream, string sourceDirectory, bool recurse, string fileFilter, string directoryFilter) + { + NameTransform = new ZipNameTransform(sourceDirectory); + sourceDirectory_ = sourceDirectory; - using ( outputStream_ = new ZipOutputStream(outputStream) ) { + using ( outputStream_ = new ZipOutputStream(outputStream) ) { #if !NETCF_1_0 - if ( password_ != null ) { - outputStream_.Password = password_; - } + if ( password_ != null ) { + outputStream_.Password = password_; + } #endif - outputStream_.UseZip64 = UseZip64; - FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); - scanner.ProcessFile += new ProcessFileHandler(ProcessFile); - if ( this.CreateEmptyDirectories ) { - scanner.ProcessDirectory += new ProcessDirectoryHandler(ProcessDirectory); - } - - if (events_ != null) { - if ( events_.FileFailure != null ) { - scanner.FileFailure += events_.FileFailure; - } - - if ( events_.DirectoryFailure != null ) { - scanner.DirectoryFailure += events_.DirectoryFailure; - } - } - - scanner.Scan(sourceDirectory, recurse); - } - } - - #endregion - - #region ExtractZip - /// - /// Extract the contents of a zip file. - /// - /// The zip file to extract from. - /// The directory to save extracted information in. - /// A filter to apply to files. - public void ExtractZip(string zipFileName, string targetDirectory, string fileFilter) - { - ExtractZip(zipFileName, targetDirectory, Overwrite.Always, null, fileFilter, null, restoreDateTimeOnExtract_); - } - - /// - /// Extract the contents of a zip file. - /// - /// The zip file to extract from. - /// The directory to save extracted information in. - /// The style of overwriting to apply. - /// A delegate to invoke when confirming overwriting. - /// A filter to apply to files. - /// A filter to apply to directories. - /// Flag indicating whether to restore the date and time for extracted files. - public void ExtractZip(string zipFileName, string targetDirectory, - Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, - string fileFilter, string directoryFilter, bool restoreDateTime) - { - Stream inputStream = File.Open(zipFileName, FileMode.Open, FileAccess.Read, FileShare.Read); - ExtractZip(inputStream, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter, restoreDateTime, true); - } - - /// - /// Extract the contents of a zip file held in a stream. - /// - /// The seekable input stream containing the zip to extract from. - /// The directory to save extracted information in. - /// The style of overwriting to apply. - /// A delegate to invoke when confirming overwriting. - /// A filter to apply to files. - /// A filter to apply to directories. - /// Flag indicating whether to restore the date and time for extracted files. - /// Flag indicating whether the inputStream will be closed by this method. - public void ExtractZip(Stream inputStream, string targetDirectory, - Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, - string fileFilter, string directoryFilter, bool restoreDateTime, - bool isStreamOwner) - { - if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null)) { - throw new ArgumentNullException("confirmDelegate"); - } - - continueRunning_ = true; - overwrite_ = overwrite; - confirmDelegate_ = confirmDelegate; - extractNameTransform_ = new WindowsNameTransform(targetDirectory); - - fileFilter_ = new NameFilter(fileFilter); - directoryFilter_ = new NameFilter(directoryFilter); - restoreDateTimeOnExtract_ = restoreDateTime; - - using (zipFile_ = new ZipFile(inputStream)) { + outputStream_.UseZip64 = UseZip64; + FileSystemScanner scanner = new FileSystemScanner(fileFilter, directoryFilter); + scanner.ProcessFile += new ProcessFileHandler(ProcessFile); + if ( this.CreateEmptyDirectories ) { + scanner.ProcessDirectory += new ProcessDirectoryHandler(ProcessDirectory); + } + + if (events_ != null) { + if ( events_.FileFailure != null ) { + scanner.FileFailure += events_.FileFailure; + } + + if ( events_.DirectoryFailure != null ) { + scanner.DirectoryFailure += events_.DirectoryFailure; + } + } + + scanner.Scan(sourceDirectory, recurse); + } + } + + #endregion + + #region ExtractZip + /// + /// Extract the contents of a zip file. + /// + /// The zip file to extract from. + /// The directory to save extracted information in. + /// A filter to apply to files. + public void ExtractZip(string zipFileName, string targetDirectory, string fileFilter) + { + ExtractZip(zipFileName, targetDirectory, Overwrite.Always, null, fileFilter, null, restoreDateTimeOnExtract_); + } + + /// + /// Extract the contents of a zip file. + /// + /// The zip file to extract from. + /// The directory to save extracted information in. + /// The style of overwriting to apply. + /// A delegate to invoke when confirming overwriting. + /// A filter to apply to files. + /// A filter to apply to directories. + /// Flag indicating whether to restore the date and time for extracted files. + public void ExtractZip(string zipFileName, string targetDirectory, + Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, + string fileFilter, string directoryFilter, bool restoreDateTime) + { + Stream inputStream = File.Open(zipFileName, FileMode.Open, FileAccess.Read, FileShare.Read); + ExtractZip(inputStream, targetDirectory, overwrite, confirmDelegate, fileFilter, directoryFilter, restoreDateTime, true); + } + + /// + /// Extract the contents of a zip file held in a stream. + /// + /// The seekable input stream containing the zip to extract from. + /// The directory to save extracted information in. + /// The style of overwriting to apply. + /// A delegate to invoke when confirming overwriting. + /// A filter to apply to files. + /// A filter to apply to directories. + /// Flag indicating whether to restore the date and time for extracted files. + /// Flag indicating whether the inputStream will be closed by this method. + public void ExtractZip(Stream inputStream, string targetDirectory, + Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, + string fileFilter, string directoryFilter, bool restoreDateTime, + bool isStreamOwner) + { + if ((overwrite == Overwrite.Prompt) && (confirmDelegate == null)) { + throw new ArgumentNullException("confirmDelegate"); + } + + continueRunning_ = true; + overwrite_ = overwrite; + confirmDelegate_ = confirmDelegate; + extractNameTransform_ = new WindowsNameTransform(targetDirectory); + + fileFilter_ = new NameFilter(fileFilter); + directoryFilter_ = new NameFilter(directoryFilter); + restoreDateTimeOnExtract_ = restoreDateTime; + + using (zipFile_ = new ZipFile(inputStream)) { #if !NETCF_1_0 - if (password_ != null) { - zipFile_.Password = password_; - } + if (password_ != null) { + zipFile_.Password = password_; + } #endif - zipFile_.IsStreamOwner = isStreamOwner; - System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator(); - while (continueRunning_ && enumerator.MoveNext()) { - ZipEntry entry = (ZipEntry)enumerator.Current; - if (entry.IsFile) - { - // TODO Path.GetDirectory can fail here on invalid characters. - if (directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name)) { - ExtractEntry(entry); - } - } - else if (entry.IsDirectory) { - if (directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories) { - ExtractEntry(entry); - } - } - else { - // Do nothing for volume labels etc... - } - } - } - } - #endregion - - #region Internal Processing - void ProcessDirectory(object sender, DirectoryEventArgs e) - { - if ( !e.HasMatchingFiles && CreateEmptyDirectories ) { - if ( events_ != null ) { - events_.OnProcessDirectory(e.Name, e.HasMatchingFiles); - } - - if ( e.ContinueRunning ) { - if (e.Name != sourceDirectory_) { - ZipEntry entry = entryFactory_.MakeDirectoryEntry(e.Name); - outputStream_.PutNextEntry(entry); - } - } - } - } - - void ProcessFile(object sender, ScanEventArgs e) - { - if ( (events_ != null) && (events_.ProcessFile != null) ) { - events_.ProcessFile(sender, e); - } - - if ( e.ContinueRunning ) { + zipFile_.IsStreamOwner = isStreamOwner; + System.Collections.IEnumerator enumerator = zipFile_.GetEnumerator(); + while (continueRunning_ && enumerator.MoveNext()) { + ZipEntry entry = (ZipEntry)enumerator.Current; + if (entry.IsFile) + { + // TODO Path.GetDirectory can fail here on invalid characters. + if (directoryFilter_.IsMatch(Path.GetDirectoryName(entry.Name)) && fileFilter_.IsMatch(entry.Name)) { + ExtractEntry(entry); + } + } + else if (entry.IsDirectory) { + if (directoryFilter_.IsMatch(entry.Name) && CreateEmptyDirectories) { + ExtractEntry(entry); + } + } + else { + // Do nothing for volume labels etc... + } + } + } + } + #endregion + + #region Internal Processing + void ProcessDirectory(object sender, DirectoryEventArgs e) + { + if ( !e.HasMatchingFiles && CreateEmptyDirectories ) { + if ( events_ != null ) { + events_.OnProcessDirectory(e.Name, e.HasMatchingFiles); + } + + if ( e.ContinueRunning ) { + if (e.Name != sourceDirectory_) { + ZipEntry entry = entryFactory_.MakeDirectoryEntry(e.Name); + outputStream_.PutNextEntry(entry); + } + } + } + } + + void ProcessFile(object sender, ScanEventArgs e) + { + if ( (events_ != null) && (events_.ProcessFile != null) ) { + events_.ProcessFile(sender, e); + } + + if ( e.ContinueRunning ) { try { // The open below is equivalent to OpenRead which gaurantees that if opened the // file will not be changed by subsequent openers, but precludes opening in some cases @@ -530,200 +530,200 @@ void ProcessFile(object sender, ScanEventArgs e) throw; } } - } - } - - void AddFileContents(string name, Stream stream) - { - if( stream==null ) { - throw new ArgumentNullException("stream"); - } - - if( buffer_==null ) { - buffer_=new byte[4096]; - } - - if( (events_!=null)&&(events_.Progress!=null) ) { - StreamUtils.Copy(stream, outputStream_, buffer_, - events_.Progress, events_.ProgressInterval, this, name); - } - else { - StreamUtils.Copy(stream, outputStream_, buffer_); - } - - if( events_!=null ) { - continueRunning_=events_.OnCompletedFile(name); - } - } - - void ExtractFileEntry(ZipEntry entry, string targetName) - { - bool proceed = true; - if ( overwrite_ != Overwrite.Always ) { - if ( File.Exists(targetName) ) { - if ( (overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null) ) { - proceed = confirmDelegate_(targetName); - } - else { - proceed = false; - } - } - } - - if ( proceed ) { - if ( events_ != null ) { - continueRunning_ = events_.OnProcessFile(entry.Name); - } - - if ( continueRunning_ ) { - try { - using ( FileStream outputStream = File.Create(targetName) ) { - if ( buffer_ == null ) { - buffer_ = new byte[4096]; - } - if ((events_ != null) && (events_.Progress != null)) - { - StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_, - events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size); - } - else - { - StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_); - } - - if (events_ != null) { - continueRunning_ = events_.OnCompletedFile(entry.Name); - } - } + } + } + + void AddFileContents(string name, Stream stream) + { + if( stream==null ) { + throw new ArgumentNullException("stream"); + } + + if( buffer_==null ) { + buffer_=new byte[4096]; + } + + if( (events_!=null)&&(events_.Progress!=null) ) { + StreamUtils.Copy(stream, outputStream_, buffer_, + events_.Progress, events_.ProgressInterval, this, name); + } + else { + StreamUtils.Copy(stream, outputStream_, buffer_); + } + + if( events_!=null ) { + continueRunning_=events_.OnCompletedFile(name); + } + } + + void ExtractFileEntry(ZipEntry entry, string targetName) + { + bool proceed = true; + if ( overwrite_ != Overwrite.Always ) { + if ( File.Exists(targetName) ) { + if ( (overwrite_ == Overwrite.Prompt) && (confirmDelegate_ != null) ) { + proceed = confirmDelegate_(targetName); + } + else { + proceed = false; + } + } + } + + if ( proceed ) { + if ( events_ != null ) { + continueRunning_ = events_.OnProcessFile(entry.Name); + } + + if ( continueRunning_ ) { + try { + using ( FileStream outputStream = File.Create(targetName) ) { + if ( buffer_ == null ) { + buffer_ = new byte[4096]; + } + if ((events_ != null) && (events_.Progress != null)) + { + StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_, + events_.Progress, events_.ProgressInterval, this, entry.Name, entry.Size); + } + else + { + StreamUtils.Copy(zipFile_.GetInputStream(entry), outputStream, buffer_); + } + + if (events_ != null) { + continueRunning_ = events_.OnCompletedFile(entry.Name); + } + } #if !NETCF_1_0 && !NETCF_2_0 - if ( restoreDateTimeOnExtract_ ) { - File.SetLastWriteTime(targetName, entry.DateTime); - } - - if ( RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1)) { - FileAttributes fileAttributes = (FileAttributes) entry.ExternalFileAttributes; - // TODO: FastZip - Setting of other file attributes on extraction is a little trickier. - fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden); - File.SetAttributes(targetName, fileAttributes); - } -#endif - } - catch(Exception ex) { - if ( events_ != null ) { - continueRunning_ = events_.OnFileFailure(targetName, ex); - } - else { + if ( restoreDateTimeOnExtract_ ) { + File.SetLastWriteTime(targetName, entry.DateTime); + } + + if ( RestoreAttributesOnExtract && entry.IsDOSEntry && (entry.ExternalFileAttributes != -1)) { + FileAttributes fileAttributes = (FileAttributes) entry.ExternalFileAttributes; + // TODO: FastZip - Setting of other file attributes on extraction is a little trickier. + fileAttributes &= (FileAttributes.Archive | FileAttributes.Normal | FileAttributes.ReadOnly | FileAttributes.Hidden); + File.SetAttributes(targetName, fileAttributes); + } +#endif + } + catch(Exception ex) { + if ( events_ != null ) { + continueRunning_ = events_.OnFileFailure(targetName, ex); + } + else { continueRunning_ = false; throw; - } - } - } - } - } - - void ExtractEntry(ZipEntry entry) - { - bool doExtraction = entry.IsCompressionMethodSupported(); - string targetName = entry.Name; - - if ( doExtraction ) { - if ( entry.IsFile ) { - targetName = extractNameTransform_.TransformFile(targetName); - } - else if ( entry.IsDirectory ) { - targetName = extractNameTransform_.TransformDirectory(targetName); - } - - doExtraction = !((targetName == null) || (targetName.Length == 0)); - } - - // TODO: Fire delegate/throw exception were compression method not supported, or name is invalid? - - string dirName = null; - - if ( doExtraction ) { - if ( entry.IsDirectory ) { - dirName = targetName; - } - else { - dirName = Path.GetDirectoryName(Path.GetFullPath(targetName)); - } - } - - if ( doExtraction && !Directory.Exists(dirName) ) { - if ( !entry.IsDirectory || CreateEmptyDirectories ) { - try { - Directory.CreateDirectory(dirName); - } - catch (Exception ex) { - doExtraction = false; - if ( events_ != null ) { - if ( entry.IsDirectory ) { - continueRunning_ = events_.OnDirectoryFailure(targetName, ex); - } - else { - continueRunning_ = events_.OnFileFailure(targetName, ex); - } - } - else { - continueRunning_ = false; + } + } + } + } + } + + void ExtractEntry(ZipEntry entry) + { + bool doExtraction = entry.IsCompressionMethodSupported(); + string targetName = entry.Name; + + if ( doExtraction ) { + if ( entry.IsFile ) { + targetName = extractNameTransform_.TransformFile(targetName); + } + else if ( entry.IsDirectory ) { + targetName = extractNameTransform_.TransformDirectory(targetName); + } + + doExtraction = !((targetName == null) || (targetName.Length == 0)); + } + + // TODO: Fire delegate/throw exception were compression method not supported, or name is invalid? + + string dirName = null; + + if ( doExtraction ) { + if ( entry.IsDirectory ) { + dirName = targetName; + } + else { + dirName = Path.GetDirectoryName(Path.GetFullPath(targetName)); + } + } + + if ( doExtraction && !Directory.Exists(dirName) ) { + if ( !entry.IsDirectory || CreateEmptyDirectories ) { + try { + Directory.CreateDirectory(dirName); + } + catch (Exception ex) { + doExtraction = false; + if ( events_ != null ) { + if ( entry.IsDirectory ) { + continueRunning_ = events_.OnDirectoryFailure(targetName, ex); + } + else { + continueRunning_ = events_.OnFileFailure(targetName, ex); + } + } + else { + continueRunning_ = false; throw; - } - } - } - } - - if ( doExtraction && entry.IsFile ) { - ExtractFileEntry(entry, targetName); - } - } - - static int MakeExternalAttributes(FileInfo info) - { - return (int)info.Attributes; - } - + } + } + } + } + + if ( doExtraction && entry.IsFile ) { + ExtractFileEntry(entry, targetName); + } + } + + static int MakeExternalAttributes(FileInfo info) + { + return (int)info.Attributes; + } + #if NET_1_0 || NET_1_1 || NETCF_1_0 - static bool NameIsValid(string name) - { - return (name != null) && - (name.Length > 0) && - (name.IndexOfAny(Path.InvalidPathChars) < 0); - } + static bool NameIsValid(string name) + { + return (name != null) && + (name.Length > 0) && + (name.IndexOfAny(Path.InvalidPathChars) < 0); + } #else - static bool NameIsValid(string name) - { - return (name != null) && - (name.Length > 0) && - (name.IndexOfAny(Path.GetInvalidPathChars()) < 0); - } + static bool NameIsValid(string name) + { + return (name != null) && + (name.Length > 0) && + (name.IndexOfAny(Path.GetInvalidPathChars()) < 0); + } #endif - #endregion - - #region Instance Fields - bool continueRunning_; - byte[] buffer_; - ZipOutputStream outputStream_; - ZipFile zipFile_; - string sourceDirectory_; - NameFilter fileFilter_; - NameFilter directoryFilter_; - Overwrite overwrite_; - ConfirmOverwriteDelegate confirmDelegate_; - - bool restoreDateTimeOnExtract_; - bool restoreAttributesOnExtract_; - bool createEmptyDirectories_; - FastZipEvents events_; - IEntryFactory entryFactory_ = new ZipEntryFactory(); - INameTransform extractNameTransform_; - UseZip64 useZip64_=UseZip64.Dynamic; - + #endregion + + #region Instance Fields + bool continueRunning_; + byte[] buffer_; + ZipOutputStream outputStream_; + ZipFile zipFile_; + string sourceDirectory_; + NameFilter fileFilter_; + NameFilter directoryFilter_; + Overwrite overwrite_; + ConfirmOverwriteDelegate confirmDelegate_; + + bool restoreDateTimeOnExtract_; + bool restoreAttributesOnExtract_; + bool createEmptyDirectories_; + FastZipEvents events_; + IEntryFactory entryFactory_ = new ZipEntryFactory(); + INameTransform extractNameTransform_; + UseZip64 useZip64_=UseZip64.Dynamic; + #if !NETCF_1_0 - string password_; -#endif + string password_; +#endif - #endregion - } + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/IEntryFactory.cs b/External/Tools/AppMan/ZipLib/Zip/IEntryFactory.cs index f0bcaee5d5..2934b06ced 100644 --- a/External/Tools/AppMan/ZipLib/Zip/IEntryFactory.cs +++ b/External/Tools/AppMan/ZipLib/Zip/IEntryFactory.cs @@ -39,44 +39,44 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// Defines factory methods for creating new values. - /// - public interface IEntryFactory - { - /// - /// Create a for a file given its name - /// - /// The name of the file to create an entry for. - /// Returns a file entry based on the passed. - ZipEntry MakeFileEntry(string fileName); + /// + /// Defines factory methods for creating new values. + /// + public interface IEntryFactory + { + /// + /// Create a for a file given its name + /// + /// The name of the file to create an entry for. + /// Returns a file entry based on the passed. + ZipEntry MakeFileEntry(string fileName); - /// - /// Create a for a file given its name - /// - /// The name of the file to create an entry for. - /// If true get details from the file system if the file exists. - /// Returns a file entry based on the passed. - ZipEntry MakeFileEntry(string fileName, bool useFileSystem); + /// + /// Create a for a file given its name + /// + /// The name of the file to create an entry for. + /// If true get details from the file system if the file exists. + /// Returns a file entry based on the passed. + ZipEntry MakeFileEntry(string fileName, bool useFileSystem); - /// - /// Create a for a directory given its name - /// - /// The name of the directory to create an entry for. - /// Returns a directory entry based on the passed. - ZipEntry MakeDirectoryEntry(string directoryName); + /// + /// Create a for a directory given its name + /// + /// The name of the directory to create an entry for. + /// Returns a directory entry based on the passed. + ZipEntry MakeDirectoryEntry(string directoryName); - /// - /// Create a for a directory given its name - /// - /// The name of the directory to create an entry for. - /// If true get details from the file system for this directory if it exists. - /// Returns a directory entry based on the passed. - ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem); - - /// - /// Get/set the applicable. - /// - INameTransform NameTransform { get; set; } - } + /// + /// Create a for a directory given its name + /// + /// The name of the directory to create an entry for. + /// If true get details from the file system for this directory if it exists. + /// Returns a directory entry based on the passed. + ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem); + + /// + /// Get/set the applicable. + /// + INameTransform NameTransform { get; set; } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/WindowsNameTransform.cs b/External/Tools/AppMan/ZipLib/Zip/WindowsNameTransform.cs index 31430c6487..a834c08cf5 100644 --- a/External/Tools/AppMan/ZipLib/Zip/WindowsNameTransform.cs +++ b/External/Tools/AppMan/ZipLib/Zip/WindowsNameTransform.cs @@ -41,232 +41,232 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// WindowsNameTransform transforms names to windows compatible ones. - /// - public class WindowsNameTransform : INameTransform - { - /// - /// Initialises a new instance of - /// - /// - public WindowsNameTransform(string baseDirectory) - { - if ( baseDirectory == null ) { - throw new ArgumentNullException("baseDirectory", "Directory name is invalid"); - } + /// + /// WindowsNameTransform transforms names to windows compatible ones. + /// + public class WindowsNameTransform : INameTransform + { + /// + /// Initialises a new instance of + /// + /// + public WindowsNameTransform(string baseDirectory) + { + if ( baseDirectory == null ) { + throw new ArgumentNullException("baseDirectory", "Directory name is invalid"); + } - BaseDirectory = baseDirectory; - } - - /// - /// Initialise a default instance of - /// - public WindowsNameTransform() - { - // Do nothing. - } - - /// - /// Gets or sets a value containing the target directory to prefix values with. - /// - public string BaseDirectory - { - get { return _baseDirectory; } - set { - if ( value == null ) { - throw new ArgumentNullException("value"); - } + BaseDirectory = baseDirectory; + } + + /// + /// Initialise a default instance of + /// + public WindowsNameTransform() + { + // Do nothing. + } + + /// + /// Gets or sets a value containing the target directory to prefix values with. + /// + public string BaseDirectory + { + get { return _baseDirectory; } + set { + if ( value == null ) { + throw new ArgumentNullException("value"); + } - _baseDirectory = Path.GetFullPath(value); - } - } - - /// - /// Gets or sets a value indicating wether paths on incoming values should be removed. - /// - public bool TrimIncomingPaths - { - get { return _trimIncomingPaths; } - set { _trimIncomingPaths = value; } - } - - /// - /// Transform a Zip directory name to a windows directory name. - /// - /// The directory name to transform. - /// The transformed name. - public string TransformDirectory(string name) - { - name = TransformFile(name); - if (name.Length > 0) { - while ( name.EndsWith(@"\") ) { - name = name.Remove(name.Length - 1, 1); - } - } - else { - throw new ZipException("Cannot have an empty directory name"); - } - return name; - } - - /// - /// Transform a Zip format file name to a windows style one. - /// - /// The file name to transform. - /// The transformed name. - public string TransformFile(string name) - { - if (name != null) { - name = MakeValidName(name, _replacementChar); - - if ( _trimIncomingPaths ) { - name = Path.GetFileName(name); - } - - // This may exceed windows length restrictions. - // Combine will throw a PathTooLongException in that case. - if ( _baseDirectory != null ) { - name = Path.Combine(_baseDirectory, name); - } - } - else { - name = string.Empty; - } - return name; - } - - /// - /// Test a name to see if it is a valid name for a windows filename as extracted from a Zip archive. - /// - /// The name to test. - /// Returns true if the name is a valid zip name; false otherwise. - /// The filename isnt a true windows path in some fundamental ways like no absolute paths, no rooted paths etc. - public static bool IsValidName(string name) - { - bool result = - (name != null) && - (name.Length <= MaxPath) && - (string.Compare(name, MakeValidName(name, '_')) == 0) - ; + _baseDirectory = Path.GetFullPath(value); + } + } + + /// + /// Gets or sets a value indicating wether paths on incoming values should be removed. + /// + public bool TrimIncomingPaths + { + get { return _trimIncomingPaths; } + set { _trimIncomingPaths = value; } + } + + /// + /// Transform a Zip directory name to a windows directory name. + /// + /// The directory name to transform. + /// The transformed name. + public string TransformDirectory(string name) + { + name = TransformFile(name); + if (name.Length > 0) { + while ( name.EndsWith(@"\") ) { + name = name.Remove(name.Length - 1, 1); + } + } + else { + throw new ZipException("Cannot have an empty directory name"); + } + return name; + } + + /// + /// Transform a Zip format file name to a windows style one. + /// + /// The file name to transform. + /// The transformed name. + public string TransformFile(string name) + { + if (name != null) { + name = MakeValidName(name, _replacementChar); + + if ( _trimIncomingPaths ) { + name = Path.GetFileName(name); + } + + // This may exceed windows length restrictions. + // Combine will throw a PathTooLongException in that case. + if ( _baseDirectory != null ) { + name = Path.Combine(_baseDirectory, name); + } + } + else { + name = string.Empty; + } + return name; + } + + /// + /// Test a name to see if it is a valid name for a windows filename as extracted from a Zip archive. + /// + /// The name to test. + /// Returns true if the name is a valid zip name; false otherwise. + /// The filename isnt a true windows path in some fundamental ways like no absolute paths, no rooted paths etc. + public static bool IsValidName(string name) + { + bool result = + (name != null) && + (name.Length <= MaxPath) && + (string.Compare(name, MakeValidName(name, '_')) == 0) + ; - return result; - } + return result; + } - /// - /// Initialise static class information. - /// - static WindowsNameTransform() - { - char[] invalidPathChars; + /// + /// Initialise static class information. + /// + static WindowsNameTransform() + { + char[] invalidPathChars; #if NET_1_0 || NET_1_1 || NETCF_1_0 - invalidPathChars = Path.InvalidPathChars; + invalidPathChars = Path.InvalidPathChars; #else - invalidPathChars = Path.GetInvalidPathChars(); + invalidPathChars = Path.GetInvalidPathChars(); #endif - int howMany = invalidPathChars.Length + 3; + int howMany = invalidPathChars.Length + 3; - InvalidEntryChars = new char[howMany]; - Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length); - InvalidEntryChars[howMany - 1] = '*'; - InvalidEntryChars[howMany - 2] = '?'; - InvalidEntryChars[howMany - 3] = ':'; - } + InvalidEntryChars = new char[howMany]; + Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length); + InvalidEntryChars[howMany - 1] = '*'; + InvalidEntryChars[howMany - 2] = '?'; + InvalidEntryChars[howMany - 3] = ':'; + } - /// - /// Force a name to be valid by replacing invalid characters with a fixed value - /// - /// The name to make valid - /// The replacement character to use for any invalid characters. - /// Returns a valid name - public static string MakeValidName(string name, char replacement) - { - if ( name == null ) { - throw new ArgumentNullException("name"); - } - - name = WindowsPathUtils.DropPathRoot(name.Replace("/", @"\")); + /// + /// Force a name to be valid by replacing invalid characters with a fixed value + /// + /// The name to make valid + /// The replacement character to use for any invalid characters. + /// Returns a valid name + public static string MakeValidName(string name, char replacement) + { + if ( name == null ) { + throw new ArgumentNullException("name"); + } + + name = WindowsPathUtils.DropPathRoot(name.Replace("/", @"\")); - // Drop any leading slashes. - while ( (name.Length > 0) && (name[0] == '\\')) { - name = name.Remove(0, 1); - } + // Drop any leading slashes. + while ( (name.Length > 0) && (name[0] == '\\')) { + name = name.Remove(0, 1); + } - // Drop any trailing slashes. - while ( (name.Length > 0) && (name[name.Length - 1] == '\\')) { - name = name.Remove(name.Length - 1, 1); - } + // Drop any trailing slashes. + while ( (name.Length > 0) && (name[name.Length - 1] == '\\')) { + name = name.Remove(name.Length - 1, 1); + } - // Convert consecutive \\ characters to \ - int index = name.IndexOf(@"\\"); - while (index >= 0) { - name = name.Remove(index, 1); - index = name.IndexOf(@"\\"); - } + // Convert consecutive \\ characters to \ + int index = name.IndexOf(@"\\"); + while (index >= 0) { + name = name.Remove(index, 1); + index = name.IndexOf(@"\\"); + } - // Convert any invalid characters using the replacement one. - index = name.IndexOfAny(InvalidEntryChars); - if (index >= 0) { - StringBuilder builder = new StringBuilder(name); + // Convert any invalid characters using the replacement one. + index = name.IndexOfAny(InvalidEntryChars); + if (index >= 0) { + StringBuilder builder = new StringBuilder(name); - while (index >= 0 ) { - builder[index] = replacement; + while (index >= 0 ) { + builder[index] = replacement; - if (index >= name.Length) { - index = -1; - } - else { - index = name.IndexOfAny(InvalidEntryChars, index + 1); - } - } - name = builder.ToString(); - } - - // Check for names greater than MaxPath characters. - // TODO: Were is CLR version of MaxPath defined? Can't find it in Environment. - if ( name.Length > MaxPath ) { - throw new PathTooLongException(); - } - - return name; - } + if (index >= name.Length) { + index = -1; + } + else { + index = name.IndexOfAny(InvalidEntryChars, index + 1); + } + } + name = builder.ToString(); + } + + // Check for names greater than MaxPath characters. + // TODO: Were is CLR version of MaxPath defined? Can't find it in Environment. + if ( name.Length > MaxPath ) { + throw new PathTooLongException(); + } + + return name; + } - /// - /// Gets or set the character to replace invalid characters during transformations. - /// - public char Replacement - { - get { return _replacementChar; } - set { - for ( int i = 0; i < InvalidEntryChars.Length; ++i ) { - if ( InvalidEntryChars[i] == value ) { - throw new ArgumentException("invalid path character"); - } - } + /// + /// Gets or set the character to replace invalid characters during transformations. + /// + public char Replacement + { + get { return _replacementChar; } + set { + for ( int i = 0; i < InvalidEntryChars.Length; ++i ) { + if ( InvalidEntryChars[i] == value ) { + throw new ArgumentException("invalid path character"); + } + } - if ((value == '\\') || (value == '/')) { - throw new ArgumentException("invalid replacement character"); - } - - _replacementChar = value; - } - } - - /// - /// The maximum windows path name permitted. - /// - /// This may not valid for all windows systems - CE?, etc but I cant find the equivalent in the CLR. - const int MaxPath = 260; - - #region Instance Fields - string _baseDirectory; - bool _trimIncomingPaths; - char _replacementChar = '_'; - #endregion - - #region Class Fields - static readonly char[] InvalidEntryChars; - #endregion - } + if ((value == '\\') || (value == '/')) { + throw new ArgumentException("invalid replacement character"); + } + + _replacementChar = value; + } + } + + /// + /// The maximum windows path name permitted. + /// + /// This may not valid for all windows systems - CE?, etc but I cant find the equivalent in the CLR. + const int MaxPath = 260; + + #region Instance Fields + string _baseDirectory; + bool _trimIncomingPaths; + char _replacementChar = '_'; + #endregion + + #region Class Fields + static readonly char[] InvalidEntryChars; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipConstants.cs b/External/Tools/AppMan/ZipLib/Zip/ZipConstants.cs index 3a19c5fa8d..25a083283d 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipConstants.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipConstants.cs @@ -38,7 +38,7 @@ // exception statement from your version. // HISTORY -// 22-12-2009 DavidPierson Added AES support +// 22-12-2009 DavidPierson Added AES support using System; using System.Text; @@ -51,582 +51,582 @@ namespace ICSharpCode.SharpZipLib.Zip { - #region Enumerations - - /// - /// Determines how entries are tested to see if they should use Zip64 extensions or not. - /// - public enum UseZip64 - { - /// - /// Zip64 will not be forced on entries during processing. - /// - /// An entry can have this overridden if required - Off, - /// - /// Zip64 should always be used. - /// - On, - /// - /// #ZipLib will determine use based on entry values when added to archive. - /// - Dynamic, - } - - /// - /// The kind of compression used for an entry in an archive - /// - public enum CompressionMethod - { - /// - /// A direct copy of the file contents is held in the archive - /// - Stored = 0, - - /// - /// Common Zip compression method using a sliding dictionary - /// of up to 32KB and secondary compression from Huffman/Shannon-Fano trees - /// - Deflated = 8, - - /// - /// An extension to deflate with a 64KB window. Not supported by #Zip currently - /// - Deflate64 = 9, - - /// - /// BZip2 compression. Not supported by #Zip. - /// - BZip2 = 11, - - /// - /// WinZip special for AES encryption, Now supported by #Zip. - /// - WinZipAES = 99, - - } - - /// - /// Identifies the encryption algorithm used for an entry - /// - public enum EncryptionAlgorithm - { - /// - /// No encryption has been used. - /// - None = 0, - /// - /// Encrypted using PKZIP 2.0 or 'classic' encryption. - /// - PkzipClassic = 1, - /// - /// DES encryption has been used. - /// - Des = 0x6601, - /// - /// RCS encryption has been used for encryption. - /// - RC2 = 0x6602, - /// - /// Triple DES encryption with 168 bit keys has been used for this entry. - /// - TripleDes168 = 0x6603, - /// - /// Triple DES with 112 bit keys has been used for this entry. - /// - TripleDes112 = 0x6609, - /// - /// AES 128 has been used for encryption. - /// - Aes128 = 0x660e, - /// - /// AES 192 has been used for encryption. - /// - Aes192 = 0x660f, - /// - /// AES 256 has been used for encryption. - /// - Aes256 = 0x6610, - /// - /// RC2 corrected has been used for encryption. - /// - RC2Corrected = 0x6702, - /// - /// Blowfish has been used for encryption. - /// - Blowfish = 0x6720, - /// - /// Twofish has been used for encryption. - /// - Twofish = 0x6721, - /// - /// RC4 has been used for encryption. - /// - RC4 = 0x6801, - /// - /// An unknown algorithm has been used for encryption. - /// - Unknown = 0xffff - } + #region Enumerations + + /// + /// Determines how entries are tested to see if they should use Zip64 extensions or not. + /// + public enum UseZip64 + { + /// + /// Zip64 will not be forced on entries during processing. + /// + /// An entry can have this overridden if required + Off, + /// + /// Zip64 should always be used. + /// + On, + /// + /// #ZipLib will determine use based on entry values when added to archive. + /// + Dynamic, + } + + /// + /// The kind of compression used for an entry in an archive + /// + public enum CompressionMethod + { + /// + /// A direct copy of the file contents is held in the archive + /// + Stored = 0, + + /// + /// Common Zip compression method using a sliding dictionary + /// of up to 32KB and secondary compression from Huffman/Shannon-Fano trees + /// + Deflated = 8, + + /// + /// An extension to deflate with a 64KB window. Not supported by #Zip currently + /// + Deflate64 = 9, + + /// + /// BZip2 compression. Not supported by #Zip. + /// + BZip2 = 11, + + /// + /// WinZip special for AES encryption, Now supported by #Zip. + /// + WinZipAES = 99, + + } + + /// + /// Identifies the encryption algorithm used for an entry + /// + public enum EncryptionAlgorithm + { + /// + /// No encryption has been used. + /// + None = 0, + /// + /// Encrypted using PKZIP 2.0 or 'classic' encryption. + /// + PkzipClassic = 1, + /// + /// DES encryption has been used. + /// + Des = 0x6601, + /// + /// RCS encryption has been used for encryption. + /// + RC2 = 0x6602, + /// + /// Triple DES encryption with 168 bit keys has been used for this entry. + /// + TripleDes168 = 0x6603, + /// + /// Triple DES with 112 bit keys has been used for this entry. + /// + TripleDes112 = 0x6609, + /// + /// AES 128 has been used for encryption. + /// + Aes128 = 0x660e, + /// + /// AES 192 has been used for encryption. + /// + Aes192 = 0x660f, + /// + /// AES 256 has been used for encryption. + /// + Aes256 = 0x6610, + /// + /// RC2 corrected has been used for encryption. + /// + RC2Corrected = 0x6702, + /// + /// Blowfish has been used for encryption. + /// + Blowfish = 0x6720, + /// + /// Twofish has been used for encryption. + /// + Twofish = 0x6721, + /// + /// RC4 has been used for encryption. + /// + RC4 = 0x6801, + /// + /// An unknown algorithm has been used for encryption. + /// + Unknown = 0xffff + } - /// - /// Defines the contents of the general bit flags field for an archive entry. - /// - [Flags] - public enum GeneralBitFlags : int - { - /// - /// Bit 0 if set indicates that the file is encrypted - /// - Encrypted = 0x0001, - /// - /// Bits 1 and 2 - Two bits defining the compression method (only for Method 6 Imploding and 8,9 Deflating) - /// - Method = 0x0006, - /// - /// Bit 3 if set indicates a trailing data desciptor is appended to the entry data - /// - Descriptor = 0x0008, - /// - /// Bit 4 is reserved for use with method 8 for enhanced deflation - /// - ReservedPKware4 = 0x0010, - /// - /// Bit 5 if set indicates the file contains Pkzip compressed patched data. - /// Requires version 2.7 or greater. - /// - Patched = 0x0020, - /// - /// Bit 6 if set indicates strong encryption has been used for this entry. - /// - StrongEncryption = 0x0040, - /// - /// Bit 7 is currently unused - /// - Unused7 = 0x0080, - /// - /// Bit 8 is currently unused - /// - Unused8 = 0x0100, - /// - /// Bit 9 is currently unused - /// - Unused9 = 0x0200, - /// - /// Bit 10 is currently unused - /// - Unused10 = 0x0400, - /// - /// Bit 11 if set indicates the filename and - /// comment fields for this file must be encoded using UTF-8. - /// - UnicodeText = 0x0800, - /// - /// Bit 12 is documented as being reserved by PKware for enhanced compression. - /// - EnhancedCompress = 0x1000, - /// - /// Bit 13 if set indicates that values in the local header are masked to hide - /// their actual values, and the central directory is encrypted. - /// - /// - /// Used when encrypting the central directory contents. - /// - HeaderMasked = 0x2000, - /// - /// Bit 14 is documented as being reserved for use by PKware - /// - ReservedPkware14 = 0x4000, - /// - /// Bit 15 is documented as being reserved for use by PKware - /// - ReservedPkware15 = 0x8000 - } - - #endregion + /// + /// Defines the contents of the general bit flags field for an archive entry. + /// + [Flags] + public enum GeneralBitFlags : int + { + /// + /// Bit 0 if set indicates that the file is encrypted + /// + Encrypted = 0x0001, + /// + /// Bits 1 and 2 - Two bits defining the compression method (only for Method 6 Imploding and 8,9 Deflating) + /// + Method = 0x0006, + /// + /// Bit 3 if set indicates a trailing data desciptor is appended to the entry data + /// + Descriptor = 0x0008, + /// + /// Bit 4 is reserved for use with method 8 for enhanced deflation + /// + ReservedPKware4 = 0x0010, + /// + /// Bit 5 if set indicates the file contains Pkzip compressed patched data. + /// Requires version 2.7 or greater. + /// + Patched = 0x0020, + /// + /// Bit 6 if set indicates strong encryption has been used for this entry. + /// + StrongEncryption = 0x0040, + /// + /// Bit 7 is currently unused + /// + Unused7 = 0x0080, + /// + /// Bit 8 is currently unused + /// + Unused8 = 0x0100, + /// + /// Bit 9 is currently unused + /// + Unused9 = 0x0200, + /// + /// Bit 10 is currently unused + /// + Unused10 = 0x0400, + /// + /// Bit 11 if set indicates the filename and + /// comment fields for this file must be encoded using UTF-8. + /// + UnicodeText = 0x0800, + /// + /// Bit 12 is documented as being reserved by PKware for enhanced compression. + /// + EnhancedCompress = 0x1000, + /// + /// Bit 13 if set indicates that values in the local header are masked to hide + /// their actual values, and the central directory is encrypted. + /// + /// + /// Used when encrypting the central directory contents. + /// + HeaderMasked = 0x2000, + /// + /// Bit 14 is documented as being reserved for use by PKware + /// + ReservedPkware14 = 0x4000, + /// + /// Bit 15 is documented as being reserved for use by PKware + /// + ReservedPkware15 = 0x8000 + } + + #endregion - /// - /// This class contains constants used for Zip format files - /// - public sealed class ZipConstants - { - #region Versions - /// - /// The version made by field for entries in the central header when created by this library - /// - /// - /// This is also the Zip version for the library when comparing against the version required to extract - /// for an entry. See . - /// - public const int VersionMadeBy = 51; // was 45 before AES - - /// - /// The version made by field for entries in the central header when created by this library - /// - /// - /// This is also the Zip version for the library when comparing against the version required to extract - /// for an entry. See ZipInputStream.CanDecompressEntry. - /// - [Obsolete("Use VersionMadeBy instead")] - public const int VERSION_MADE_BY = 51; - - /// - /// The minimum version required to support strong encryption - /// - public const int VersionStrongEncryption = 50; + /// + /// This class contains constants used for Zip format files + /// + public sealed class ZipConstants + { + #region Versions + /// + /// The version made by field for entries in the central header when created by this library + /// + /// + /// This is also the Zip version for the library when comparing against the version required to extract + /// for an entry. See . + /// + public const int VersionMadeBy = 51; // was 45 before AES + + /// + /// The version made by field for entries in the central header when created by this library + /// + /// + /// This is also the Zip version for the library when comparing against the version required to extract + /// for an entry. See ZipInputStream.CanDecompressEntry. + /// + [Obsolete("Use VersionMadeBy instead")] + public const int VERSION_MADE_BY = 51; + + /// + /// The minimum version required to support strong encryption + /// + public const int VersionStrongEncryption = 50; - /// - /// The minimum version required to support strong encryption - /// - [Obsolete("Use VersionStrongEncryption instead")] - public const int VERSION_STRONG_ENCRYPTION = 50; + /// + /// The minimum version required to support strong encryption + /// + [Obsolete("Use VersionStrongEncryption instead")] + public const int VERSION_STRONG_ENCRYPTION = 50; - /// - /// Version indicating AES encryption - /// - public const int VERSION_AES = 51; + /// + /// Version indicating AES encryption + /// + public const int VERSION_AES = 51; - /// - /// The version required for Zip64 extensions (4.5 or higher) - /// - public const int VersionZip64 = 45; - #endregion - - #region Header Sizes - /// - /// Size of local entry header (excluding variable length fields at end) - /// - public const int LocalHeaderBaseSize = 30; - - /// - /// Size of local entry header (excluding variable length fields at end) - /// - [Obsolete("Use LocalHeaderBaseSize instead")] - public const int LOCHDR = 30; - - /// - /// Size of Zip64 data descriptor - /// - public const int Zip64DataDescriptorSize = 24; - - /// - /// Size of data descriptor - /// - public const int DataDescriptorSize = 16; - - /// - /// Size of data descriptor - /// - [Obsolete("Use DataDescriptorSize instead")] - public const int EXTHDR = 16; - - /// - /// Size of central header entry (excluding variable fields) - /// - public const int CentralHeaderBaseSize = 46; - - /// - /// Size of central header entry - /// - [Obsolete("Use CentralHeaderBaseSize instead")] - public const int CENHDR = 46; - - /// - /// Size of end of central record (excluding variable fields) - /// - public const int EndOfCentralRecordBaseSize = 22; - - /// - /// Size of end of central record (excluding variable fields) - /// - [Obsolete("Use EndOfCentralRecordBaseSize instead")] - public const int ENDHDR = 22; - - /// - /// Size of 'classic' cryptographic header stored before any entry data - /// - public const int CryptoHeaderSize = 12; - - /// - /// Size of cryptographic header stored before entry data - /// - [Obsolete("Use CryptoHeaderSize instead")] - public const int CRYPTO_HEADER_SIZE = 12; - #endregion - - #region Header Signatures - - /// - /// Signature for local entry header - /// - public const int LocalHeaderSignature = 'P' | ('K' << 8) | (3 << 16) | (4 << 24); + /// + /// The version required for Zip64 extensions (4.5 or higher) + /// + public const int VersionZip64 = 45; + #endregion + + #region Header Sizes + /// + /// Size of local entry header (excluding variable length fields at end) + /// + public const int LocalHeaderBaseSize = 30; + + /// + /// Size of local entry header (excluding variable length fields at end) + /// + [Obsolete("Use LocalHeaderBaseSize instead")] + public const int LOCHDR = 30; + + /// + /// Size of Zip64 data descriptor + /// + public const int Zip64DataDescriptorSize = 24; + + /// + /// Size of data descriptor + /// + public const int DataDescriptorSize = 16; + + /// + /// Size of data descriptor + /// + [Obsolete("Use DataDescriptorSize instead")] + public const int EXTHDR = 16; + + /// + /// Size of central header entry (excluding variable fields) + /// + public const int CentralHeaderBaseSize = 46; + + /// + /// Size of central header entry + /// + [Obsolete("Use CentralHeaderBaseSize instead")] + public const int CENHDR = 46; + + /// + /// Size of end of central record (excluding variable fields) + /// + public const int EndOfCentralRecordBaseSize = 22; + + /// + /// Size of end of central record (excluding variable fields) + /// + [Obsolete("Use EndOfCentralRecordBaseSize instead")] + public const int ENDHDR = 22; + + /// + /// Size of 'classic' cryptographic header stored before any entry data + /// + public const int CryptoHeaderSize = 12; + + /// + /// Size of cryptographic header stored before entry data + /// + [Obsolete("Use CryptoHeaderSize instead")] + public const int CRYPTO_HEADER_SIZE = 12; + #endregion + + #region Header Signatures + + /// + /// Signature for local entry header + /// + public const int LocalHeaderSignature = 'P' | ('K' << 8) | (3 << 16) | (4 << 24); - /// - /// Signature for local entry header - /// - [Obsolete("Use LocalHeaderSignature instead")] - public const int LOCSIG = 'P' | ('K' << 8) | (3 << 16) | (4 << 24); + /// + /// Signature for local entry header + /// + [Obsolete("Use LocalHeaderSignature instead")] + public const int LOCSIG = 'P' | ('K' << 8) | (3 << 16) | (4 << 24); - /// - /// Signature for spanning entry - /// - public const int SpanningSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); - - /// - /// Signature for spanning entry - /// - [Obsolete("Use SpanningSignature instead")] - public const int SPANNINGSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); - - /// - /// Signature for temporary spanning entry - /// - public const int SpanningTempSignature = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24); - - /// - /// Signature for temporary spanning entry - /// - [Obsolete("Use SpanningTempSignature instead")] - public const int SPANTEMPSIG = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24); - - /// - /// Signature for data descriptor - /// - /// - /// This is only used where the length, Crc, or compressed size isnt known when the - /// entry is created and the output stream doesnt support seeking. - /// The local entry cannot be 'patched' with the correct values in this case - /// so the values are recorded after the data prefixed by this header, as well as in the central directory. - /// - public const int DataDescriptorSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); - - /// - /// Signature for data descriptor - /// - /// - /// This is only used where the length, Crc, or compressed size isnt known when the - /// entry is created and the output stream doesnt support seeking. - /// The local entry cannot be 'patched' with the correct values in this case - /// so the values are recorded after the data prefixed by this header, as well as in the central directory. - /// - [Obsolete("Use DataDescriptorSignature instead")] - public const int EXTSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); - - /// - /// Signature for central header - /// - [Obsolete("Use CentralHeaderSignature instead")] - public const int CENSIG = 'P' | ('K' << 8) | (1 << 16) | (2 << 24); + /// + /// Signature for spanning entry + /// + public const int SpanningSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); + + /// + /// Signature for spanning entry + /// + [Obsolete("Use SpanningSignature instead")] + public const int SPANNINGSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); + + /// + /// Signature for temporary spanning entry + /// + public const int SpanningTempSignature = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24); + + /// + /// Signature for temporary spanning entry + /// + [Obsolete("Use SpanningTempSignature instead")] + public const int SPANTEMPSIG = 'P' | ('K' << 8) | ('0' << 16) | ('0' << 24); + + /// + /// Signature for data descriptor + /// + /// + /// This is only used where the length, Crc, or compressed size isnt known when the + /// entry is created and the output stream doesnt support seeking. + /// The local entry cannot be 'patched' with the correct values in this case + /// so the values are recorded after the data prefixed by this header, as well as in the central directory. + /// + public const int DataDescriptorSignature = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); + + /// + /// Signature for data descriptor + /// + /// + /// This is only used where the length, Crc, or compressed size isnt known when the + /// entry is created and the output stream doesnt support seeking. + /// The local entry cannot be 'patched' with the correct values in this case + /// so the values are recorded after the data prefixed by this header, as well as in the central directory. + /// + [Obsolete("Use DataDescriptorSignature instead")] + public const int EXTSIG = 'P' | ('K' << 8) | (7 << 16) | (8 << 24); + + /// + /// Signature for central header + /// + [Obsolete("Use CentralHeaderSignature instead")] + public const int CENSIG = 'P' | ('K' << 8) | (1 << 16) | (2 << 24); - /// - /// Signature for central header - /// - public const int CentralHeaderSignature = 'P' | ('K' << 8) | (1 << 16) | (2 << 24); + /// + /// Signature for central header + /// + public const int CentralHeaderSignature = 'P' | ('K' << 8) | (1 << 16) | (2 << 24); - /// - /// Signature for Zip64 central file header - /// - public const int Zip64CentralFileHeaderSignature = 'P' | ('K' << 8) | (6 << 16) | (6 << 24); - - /// - /// Signature for Zip64 central file header - /// - [Obsolete("Use Zip64CentralFileHeaderSignature instead")] - public const int CENSIG64 = 'P' | ('K' << 8) | (6 << 16) | (6 << 24); - - /// - /// Signature for Zip64 central directory locator - /// - public const int Zip64CentralDirLocatorSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24); - - /// - /// Signature for archive extra data signature (were headers are encrypted). - /// - public const int ArchiveExtraDataSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24); - - /// - /// Central header digitial signature - /// - public const int CentralHeaderDigitalSignature = 'P' | ('K' << 8) | (5 << 16) | (5 << 24); - - /// - /// Central header digitial signature - /// - [Obsolete("Use CentralHeaderDigitalSignaure instead")] - public const int CENDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24); + /// + /// Signature for Zip64 central file header + /// + public const int Zip64CentralFileHeaderSignature = 'P' | ('K' << 8) | (6 << 16) | (6 << 24); + + /// + /// Signature for Zip64 central file header + /// + [Obsolete("Use Zip64CentralFileHeaderSignature instead")] + public const int CENSIG64 = 'P' | ('K' << 8) | (6 << 16) | (6 << 24); + + /// + /// Signature for Zip64 central directory locator + /// + public const int Zip64CentralDirLocatorSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24); + + /// + /// Signature for archive extra data signature (were headers are encrypted). + /// + public const int ArchiveExtraDataSignature = 'P' | ('K' << 8) | (6 << 16) | (7 << 24); + + /// + /// Central header digitial signature + /// + public const int CentralHeaderDigitalSignature = 'P' | ('K' << 8) | (5 << 16) | (5 << 24); + + /// + /// Central header digitial signature + /// + [Obsolete("Use CentralHeaderDigitalSignaure instead")] + public const int CENDIGITALSIG = 'P' | ('K' << 8) | (5 << 16) | (5 << 24); - /// - /// End of central directory record signature - /// - public const int EndOfCentralDirectorySignature = 'P' | ('K' << 8) | (5 << 16) | (6 << 24); - - /// - /// End of central directory record signature - /// - [Obsolete("Use EndOfCentralDirectorySignature instead")] - public const int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24); - #endregion - + /// + /// End of central directory record signature + /// + public const int EndOfCentralDirectorySignature = 'P' | ('K' << 8) | (5 << 16) | (6 << 24); + + /// + /// End of central directory record signature + /// + [Obsolete("Use EndOfCentralDirectorySignature instead")] + public const int ENDSIG = 'P' | ('K' << 8) | (5 << 16) | (6 << 24); + #endregion + #if NETCF_1_0 || NETCF_2_0 - // This isnt so great but is better than nothing. + // This isnt so great but is better than nothing. // Trying to work out an appropriate OEM code page would be good. // 850 is a good default for english speakers particularly in Europe. - static int defaultCodePage = CultureInfo.CurrentCulture.TextInfo.ANSICodePage; + static int defaultCodePage = CultureInfo.CurrentCulture.TextInfo.ANSICodePage; #else - static int defaultCodePage = Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage; + static int defaultCodePage = Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage; #endif - - /// - /// Default encoding used for string conversion. 0 gives the default system OEM code page. - /// Dont use unicode encodings if you want to be Zip compatible! - /// Using the default code page isnt the full solution neccessarily - /// there are many variable factors, codepage 850 is often a good choice for - /// European users, however be careful about compatability. - /// - public static int DefaultCodePage { - get { - return defaultCodePage; - } - set { - defaultCodePage = value; - } - } + + /// + /// Default encoding used for string conversion. 0 gives the default system OEM code page. + /// Dont use unicode encodings if you want to be Zip compatible! + /// Using the default code page isnt the full solution neccessarily + /// there are many variable factors, codepage 850 is often a good choice for + /// European users, however be careful about compatability. + /// + public static int DefaultCodePage { + get { + return defaultCodePage; + } + set { + defaultCodePage = value; + } + } - /// - /// Convert a portion of a byte array to a string. - /// - /// - /// Data to convert to string - /// - /// - /// Number of bytes to convert starting from index 0 - /// - /// - /// data[0]..data[length - 1] converted to a string - /// - public static string ConvertToString(byte[] data, int count) - { - if ( data == null ) { - return string.Empty; - } - - return Encoding.GetEncoding(DefaultCodePage).GetString(data, 0, count); - } - - /// - /// Convert a byte array to string - /// - /// - /// Byte array to convert - /// - /// - /// dataconverted to a string - /// - public static string ConvertToString(byte[] data) - { - if ( data == null ) { - return string.Empty; - } - return ConvertToString(data, data.Length); - } + /// + /// Convert a portion of a byte array to a string. + /// + /// + /// Data to convert to string + /// + /// + /// Number of bytes to convert starting from index 0 + /// + /// + /// data[0]..data[length - 1] converted to a string + /// + public static string ConvertToString(byte[] data, int count) + { + if ( data == null ) { + return string.Empty; + } + + return Encoding.GetEncoding(DefaultCodePage).GetString(data, 0, count); + } + + /// + /// Convert a byte array to string + /// + /// + /// Byte array to convert + /// + /// + /// dataconverted to a string + /// + public static string ConvertToString(byte[] data) + { + if ( data == null ) { + return string.Empty; + } + return ConvertToString(data, data.Length); + } - /// - /// Convert a byte array to string - /// - /// The applicable general purpose bits flags - /// - /// Byte array to convert - /// - /// The number of bytes to convert. - /// - /// dataconverted to a string - /// - public static string ConvertToStringExt(int flags, byte[] data, int count) - { - if ( data == null ) { - return string.Empty; - } - - if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) { - return Encoding.UTF8.GetString(data, 0, count); - } - else { - return ConvertToString(data, count); - } - } - - /// - /// Convert a byte array to string - /// - /// - /// Byte array to convert - /// - /// The applicable general purpose bits flags - /// - /// dataconverted to a string - /// - public static string ConvertToStringExt(int flags, byte[] data) - { - if ( data == null ) { - return string.Empty; - } - - if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) { - return Encoding.UTF8.GetString(data, 0, data.Length); - } - else { - return ConvertToString(data, data.Length); - } - } + /// + /// Convert a byte array to string + /// + /// The applicable general purpose bits flags + /// + /// Byte array to convert + /// + /// The number of bytes to convert. + /// + /// dataconverted to a string + /// + public static string ConvertToStringExt(int flags, byte[] data, int count) + { + if ( data == null ) { + return string.Empty; + } + + if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) { + return Encoding.UTF8.GetString(data, 0, count); + } + else { + return ConvertToString(data, count); + } + } + + /// + /// Convert a byte array to string + /// + /// + /// Byte array to convert + /// + /// The applicable general purpose bits flags + /// + /// dataconverted to a string + /// + public static string ConvertToStringExt(int flags, byte[] data) + { + if ( data == null ) { + return string.Empty; + } + + if ( (flags & (int)GeneralBitFlags.UnicodeText) != 0 ) { + return Encoding.UTF8.GetString(data, 0, data.Length); + } + else { + return ConvertToString(data, data.Length); + } + } - /// - /// Convert a string to a byte array - /// - /// - /// String to convert to an array - /// - /// Converted array - public static byte[] ConvertToArray(string str) - { - if ( str == null ) { - return new byte[0]; - } - - return Encoding.GetEncoding(DefaultCodePage).GetBytes(str); - } + /// + /// Convert a string to a byte array + /// + /// + /// String to convert to an array + /// + /// Converted array + public static byte[] ConvertToArray(string str) + { + if ( str == null ) { + return new byte[0]; + } + + return Encoding.GetEncoding(DefaultCodePage).GetBytes(str); + } - /// - /// Convert a string to a byte array - /// + /// + /// Convert a string to a byte array + /// /// The applicable general purpose bits flags - /// - /// String to convert to an array - /// - /// Converted array - public static byte[] ConvertToArray(int flags, string str) - { - if (str == null) { - return new byte[0]; - } + /// + /// String to convert to an array + /// + /// Converted array + public static byte[] ConvertToArray(int flags, string str) + { + if (str == null) { + return new byte[0]; + } - if ((flags & (int)GeneralBitFlags.UnicodeText) != 0) { - return Encoding.UTF8.GetBytes(str); - } - else { - return ConvertToArray(str); - } - } + if ((flags & (int)GeneralBitFlags.UnicodeText) != 0) { + return Encoding.UTF8.GetBytes(str); + } + else { + return ConvertToArray(str); + } + } - - /// - /// Initialise default instance of ZipConstants - /// - /// - /// Private to prevent instances being created. - /// - ZipConstants() - { - // Do nothing - } - } + + /// + /// Initialise default instance of ZipConstants + /// + /// + /// Private to prevent instances being created. + /// + ZipConstants() + { + // Do nothing + } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipEntry.cs b/External/Tools/AppMan/ZipLib/Zip/ZipEntry.cs index febbc207f9..5abbe00359 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipEntry.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipEntry.cs @@ -38,8 +38,8 @@ // exception statement from your version. // HISTORY -// 22-12-2009 DavidPierson Added AES support -// 02-02-2010 DavidPierson Changed NTFS Extra Data min length to 4 +// 22-12-2009 DavidPierson Added AES support +// 02-02-2010 DavidPierson Changed NTFS Extra Data min length to 4 using System; using System.IO; @@ -47,1206 +47,1206 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// Defines known values for the property. - /// - public enum HostSystemID - { - /// - /// Host system = MSDOS - /// - Msdos = 0, - /// - /// Host system = Amiga - /// - Amiga = 1, - /// - /// Host system = Open VMS - /// - OpenVms = 2, - /// - /// Host system = Unix - /// - Unix = 3, - /// - /// Host system = VMCms - /// - VMCms = 4, - /// - /// Host system = Atari ST - /// - AtariST = 5, - /// - /// Host system = OS2 - /// - OS2 = 6, - /// - /// Host system = Macintosh - /// - Macintosh = 7, - /// - /// Host system = ZSystem - /// - ZSystem = 8, - /// - /// Host system = Cpm - /// - Cpm = 9, - /// - /// Host system = Windows NT - /// - WindowsNT = 10, - /// - /// Host system = MVS - /// - MVS = 11, - /// - /// Host system = VSE - /// - Vse = 12, - /// - /// Host system = Acorn RISC - /// - AcornRisc = 13, - /// - /// Host system = VFAT - /// - Vfat = 14, - /// - /// Host system = Alternate MVS - /// - AlternateMvs = 15, - /// - /// Host system = BEOS - /// - BeOS = 16, - /// - /// Host system = Tandem - /// - Tandem = 17, - /// - /// Host system = OS400 - /// - OS400 = 18, - /// - /// Host system = OSX - /// - OSX = 19, - /// - /// Host system = WinZIP AES - /// - WinZipAES = 99, - } - - /// - /// This class represents an entry in a zip archive. This can be a file - /// or a directory - /// ZipFile and ZipInputStream will give you instances of this class as - /// information about the members in an archive. ZipOutputStream - /// uses an instance of this class when creating an entry in a Zip file. - ///
    - ///
    Author of the original java version : Jochen Hoenicke - ///
    - public class ZipEntry : ICloneable - { - [Flags] - enum Known : byte - { - None = 0, - Size = 0x01, - CompressedSize = 0x02, - Crc = 0x04, - Time = 0x08, - ExternalAttributes = 0x10, - } - - #region Constructors - /// - /// Creates a zip entry with the given name. - /// - /// - /// The name for this entry. Can include directory components. - /// The convention for names is 'unix' style paths with relative names only. - /// There are with no device names and path elements are separated by '/' characters. - /// - /// - /// The name passed is null - /// - public ZipEntry(string name) - : this(name, 0, ZipConstants.VersionMadeBy, CompressionMethod.Deflated) - { - } - - /// - /// Creates a zip entry with the given name and version required to extract - /// - /// - /// The name for this entry. Can include directory components. - /// The convention for names is 'unix' style paths with no device names and - /// path elements separated by '/' characters. This is not enforced see CleanName - /// on how to ensure names are valid if this is desired. - /// - /// - /// The minimum 'feature version' required this entry - /// - /// - /// The name passed is null - /// - internal ZipEntry(string name, int versionRequiredToExtract) - : this(name, versionRequiredToExtract, ZipConstants.VersionMadeBy, - CompressionMethod.Deflated) - { - } - - /// - /// Initializes an entry with the given name and made by information - /// - /// Name for this entry - /// Version and HostSystem Information - /// Minimum required zip feature version required to extract this entry - /// Compression method for this entry. - /// - /// The name passed is null - /// - /// - /// versionRequiredToExtract should be 0 (auto-calculate) or > 10 - /// - /// - /// This constructor is used by the ZipFile class when reading from the central header - /// It is not generally useful, use the constructor specifying the name only. - /// - internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo, - CompressionMethod method) - { - if (name == null) { - throw new System.ArgumentNullException("name"); - } - - if ( name.Length > 0xffff ) { - throw new ArgumentException("Name is too long", "name"); - } - - if ( (versionRequiredToExtract != 0) && (versionRequiredToExtract < 10) ) { - throw new ArgumentOutOfRangeException("versionRequiredToExtract"); - } - - this.DateTime = System.DateTime.Now; - this.name = name; - this.versionMadeBy = (ushort)madeByInfo; - this.versionToExtract = (ushort)versionRequiredToExtract; - this.method = method; - } - - /// - /// Creates a deep copy of the given zip entry. - /// - /// - /// The entry to copy. - /// - [Obsolete("Use Clone instead")] - public ZipEntry(ZipEntry entry) - { - if ( entry == null ) { - throw new ArgumentNullException("entry"); - } - - known = entry.known; - name = entry.name; - size = entry.size; - compressedSize = entry.compressedSize; - crc = entry.crc; - dosTime = entry.dosTime; - method = entry.method; - comment = entry.comment; - versionToExtract = entry.versionToExtract; - versionMadeBy = entry.versionMadeBy; - externalFileAttributes = entry.externalFileAttributes; - flags = entry.flags; - - zipFileIndex = entry.zipFileIndex; - offset = entry.offset; - - forceZip64_ = entry.forceZip64_; - - if ( entry.extra != null ) { - extra = new byte[entry.extra.Length]; - Array.Copy(entry.extra, 0, extra, 0, entry.extra.Length); - } - } - - #endregion - - /// - /// Get a value indicating wether the entry has a CRC value available. - /// - public bool HasCrc - { - get { - return (known & Known.Crc) != 0; - } - } - - /// - /// Get/Set flag indicating if entry is encrypted. - /// A simple helper routine to aid interpretation of flags - /// - /// This is an assistant that interprets the flags property. - public bool IsCrypted - { - get { - return (flags & 1) != 0; - } - set { - if (value) { - flags |= 1; - } - else { - flags &= ~1; - } - } - } - - /// - /// Get / set a flag indicating wether entry name and comment text are - /// encoded in unicode UTF8. - /// - /// This is an assistant that interprets the flags property. - public bool IsUnicodeText - { - get { - return ( flags & (int)GeneralBitFlags.UnicodeText ) != 0; - } - set { - if ( value ) { - flags |= (int)GeneralBitFlags.UnicodeText; - } - else { - flags &= ~(int)GeneralBitFlags.UnicodeText; - } - } - } - - /// - /// Value used during password checking for PKZIP 2.0 / 'classic' encryption. - /// - internal byte CryptoCheckValue - { - get { - return cryptoCheckValue_; - } - - set { - cryptoCheckValue_ = value; - } - } - - /// - /// Get/Set general purpose bit flag for entry - /// - /// - /// General purpose bit flag
    - ///
    - /// Bit 0: If set, indicates the file is encrypted
    - /// Bit 1-2 Only used for compression type 6 Imploding, and 8, 9 deflating
    - /// Imploding:
    - /// Bit 1 if set indicates an 8K sliding dictionary was used. If clear a 4k dictionary was used
    - /// Bit 2 if set indicates 3 Shannon-Fanno trees were used to encode the sliding dictionary, 2 otherwise
    - ///
    - /// Deflating:
    - /// Bit 2 Bit 1
    - /// 0 0 Normal compression was used
    - /// 0 1 Maximum compression was used
    - /// 1 0 Fast compression was used
    - /// 1 1 Super fast compression was used
    - ///
    - /// Bit 3: If set, the fields crc-32, compressed size - /// and uncompressed size are were not able to be written during zip file creation - /// The correct values are held in a data descriptor immediately following the compressed data.
    - /// Bit 4: Reserved for use by PKZIP for enhanced deflating
    - /// Bit 5: If set indicates the file contains compressed patch data
    - /// Bit 6: If set indicates strong encryption was used.
    - /// Bit 7-10: Unused or reserved
    - /// Bit 11: If set the name and comments for this entry are in unicode.
    - /// Bit 12-15: Unused or reserved
    - ///
    - /// - /// - public int Flags - { - get { - return flags; - } - set { - flags = value; - } - } - - /// - /// Get/Set index of this entry in Zip file - /// - /// This is only valid when the entry is part of a - public long ZipFileIndex - { - get { - return zipFileIndex; - } - set { - zipFileIndex = value; - } - } - - /// - /// Get/set offset for use in central header - /// - public long Offset - { - get { - return offset; - } - set { - offset = value; - } - } - - /// - /// Get/Set external file attributes as an integer. - /// The values of this are operating system dependant see - /// HostSystem for details - /// - public int ExternalFileAttributes - { - get { - if ((known & Known.ExternalAttributes) == 0) { - return -1; - } - else { - return externalFileAttributes; - } - } - - set { - externalFileAttributes = value; - known |= Known.ExternalAttributes; - } - } - - /// - /// Get the version made by for this entry or zero if unknown. - /// The value / 10 indicates the major version number, and - /// the value mod 10 is the minor version number - /// - public int VersionMadeBy - { - get { - return (versionMadeBy & 0xff); - } - } - - /// - /// Get a value indicating this entry is for a DOS/Windows system. - /// - public bool IsDOSEntry - { - get { - return ((HostSystem == ( int )HostSystemID.Msdos) || - (HostSystem == ( int )HostSystemID.WindowsNT)); - } - } - - /// - /// Test the external attributes for this to - /// see if the external attributes are Dos based (including WINNT and variants) - /// and match the values - /// - /// The attributes to test. - /// Returns true if the external attributes are known to be DOS/Windows - /// based and have the same attributes set as the value passed. - bool HasDosAttributes(int attributes) - { - bool result = false; - if ( (known & Known.ExternalAttributes) != 0 ) { - if ( ((HostSystem == (int)HostSystemID.Msdos) || - (HostSystem == (int)HostSystemID.WindowsNT)) && - (ExternalFileAttributes & attributes) == attributes) { - result = true; - } - } - return result; - } - - /// - /// Gets the compatability information for the external file attribute - /// If the external file attributes are compatible with MS-DOS and can be read - /// by PKZIP for DOS version 2.04g then this value will be zero. Otherwise the value - /// will be non-zero and identify the host system on which the attributes are compatible. - /// - /// - /// - /// The values for this as defined in the Zip File format and by others are shown below. The values are somewhat - /// misleading in some cases as they are not all used as shown. You should consult the relevant documentation - /// to obtain up to date and correct information. The modified appnote by the infozip group is - /// particularly helpful as it documents a lot of peculiarities. The document is however a little dated. - /// - /// 0 - MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems) - /// 1 - Amiga - /// 2 - OpenVMS - /// 3 - Unix - /// 4 - VM/CMS - /// 5 - Atari ST - /// 6 - OS/2 HPFS - /// 7 - Macintosh - /// 8 - Z-System - /// 9 - CP/M - /// 10 - Windows NTFS - /// 11 - MVS (OS/390 - Z/OS) - /// 12 - VSE - /// 13 - Acorn Risc - /// 14 - VFAT - /// 15 - Alternate MVS - /// 16 - BeOS - /// 17 - Tandem - /// 18 - OS/400 - /// 19 - OS/X (Darwin) - /// 99 - WinZip AES - /// remainder - unused - /// - /// - public int HostSystem - { - get { - return (versionMadeBy >> 8) & 0xff; - } - - set { - versionMadeBy &= 0xff; - versionMadeBy |= (ushort)((value & 0xff) << 8); - } - } - - /// - /// Get minimum Zip feature version required to extract this entry - /// - /// - /// Minimum features are defined as:
    - /// 1.0 - Default value
    - /// 1.1 - File is a volume label
    - /// 2.0 - File is a folder/directory
    - /// 2.0 - File is compressed using Deflate compression
    - /// 2.0 - File is encrypted using traditional encryption
    - /// 2.1 - File is compressed using Deflate64
    - /// 2.5 - File is compressed using PKWARE DCL Implode
    - /// 2.7 - File is a patch data set
    - /// 4.5 - File uses Zip64 format extensions
    - /// 4.6 - File is compressed using BZIP2 compression
    - /// 5.0 - File is encrypted using DES
    - /// 5.0 - File is encrypted using 3DES
    - /// 5.0 - File is encrypted using original RC2 encryption
    - /// 5.0 - File is encrypted using RC4 encryption
    - /// 5.1 - File is encrypted using AES encryption
    - /// 5.1 - File is encrypted using corrected RC2 encryption
    - /// 5.1 - File is encrypted using corrected RC2-64 encryption
    - /// 6.1 - File is encrypted using non-OAEP key wrapping
    - /// 6.2 - Central directory encryption (not confirmed yet)
    - /// 6.3 - File is compressed using LZMA
    - /// 6.3 - File is compressed using PPMD+
    - /// 6.3 - File is encrypted using Blowfish
    - /// 6.3 - File is encrypted using Twofish
    - ///
    - /// - public int Version - { - get { - // Return recorded version if known. - if (versionToExtract != 0) { - return versionToExtract; - } - else { - int result = 10; - if (AESKeySize > 0) { - result = ZipConstants.VERSION_AES; // Ver 5.1 = AES - } - else if (CentralHeaderRequiresZip64) { - result = ZipConstants.VersionZip64; - } - else if (CompressionMethod.Deflated == method) { - result = 20; - } - else if (IsDirectory == true) { - result = 20; - } - else if (IsCrypted == true) { - result = 20; - } - else if (HasDosAttributes(0x08) ) { - result = 11; - } - return result; - } - } - } - - /// - /// Get a value indicating whether this entry can be decompressed by the library. - /// - /// This is based on the and - /// wether the compression method is supported. - public bool CanDecompress - { - get { - return (Version <= ZipConstants.VersionMadeBy) && - ((Version == 10) || - (Version == 11) || - (Version == 20) || - (Version == 45) || - (Version == 51)) && - IsCompressionMethodSupported(); - } - } - - /// - /// Force this entry to be recorded using Zip64 extensions. - /// - public void ForceZip64() - { - forceZip64_ = true; - } - - /// - /// Get a value indicating wether Zip64 extensions were forced. - /// - /// A value of true if Zip64 extensions have been forced on; false if not. - public bool IsZip64Forced() - { - return forceZip64_; - } - - /// - /// Gets a value indicating if the entry requires Zip64 extensions - /// to store the full entry values. - /// - /// A value of true if a local header requires Zip64 extensions; false if not. - public bool LocalHeaderRequiresZip64 - { - get { - bool result = forceZip64_; - - if ( !result ) { - ulong trueCompressedSize = compressedSize; - - if ( (versionToExtract == 0) && IsCrypted ) { - trueCompressedSize += ZipConstants.CryptoHeaderSize; - } - - // TODO: A better estimation of the true limit based on compression overhead should be used - // to determine when an entry should use Zip64. - result = - ((this.size >= uint.MaxValue) || (trueCompressedSize >= uint.MaxValue)) && - ((versionToExtract == 0) || (versionToExtract >= ZipConstants.VersionZip64)); - } - - return result; - } - } - - /// - /// Get a value indicating wether the central directory entry requires Zip64 extensions to be stored. - /// - public bool CentralHeaderRequiresZip64 - { - get { - return LocalHeaderRequiresZip64 || (offset >= uint.MaxValue); - } - } - - /// - /// Get/Set DosTime value. - /// - /// - /// The MS-DOS date format can only represent dates between 1/1/1980 and 12/31/2107. - /// - public long DosTime - { - get { - if ((known & Known.Time) == 0) { - return 0; - } - else { - return dosTime; - } - } - - set { - unchecked { - dosTime = (uint)value; - } - - known |= Known.Time; - } - } - - /// - /// Gets/Sets the time of last modification of the entry. - /// - /// - /// The property is updated to match this as far as possible. - /// - public DateTime DateTime - { - get { - uint sec = Math.Min(59, 2 * (dosTime & 0x1f)); - uint min = Math.Min(59, (dosTime >> 5) & 0x3f); - uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f); - uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf))); - uint year = ((dosTime >> 25) & 0x7f) + 1980; - int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f))); - return new System.DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec); - } - - set { - uint year = (uint) value.Year; - uint month = (uint) value.Month; - uint day = (uint) value.Day; - uint hour = (uint) value.Hour; - uint minute = (uint) value.Minute; - uint second = (uint) value.Second; - - if ( year < 1980 ) { - year = 1980; - month = 1; - day = 1; - hour = 0; - minute = 0; - second = 0; - } - else if ( year > 2107 ) { - year = 2107; - month = 12; - day = 31; - hour = 23; - minute = 59; - second = 59; - } - - DosTime = ((year - 1980) & 0x7f) << 25 | - (month << 21) | - (day << 16) | - (hour << 11) | - (minute << 5) | - (second >> 1); - } - } - - /// - /// Returns the entry name. - /// - /// - /// The unix naming convention is followed. - /// Path components in the entry should always separated by forward slashes ('/'). - /// Dos device names like C: should also be removed. - /// See the class, or - /// - public string Name - { - get { - return name; - } - } - - /// - /// Gets/Sets the size of the uncompressed data. - /// - /// - /// The size or -1 if unknown. - /// - /// Setting the size before adding an entry to an archive can help - /// avoid compatability problems with some archivers which dont understand Zip64 extensions. - public long Size - { - get { - return (known & Known.Size) != 0 ? (long)size : -1L; - } - set { - this.size = (ulong)value; - this.known |= Known.Size; - } - } - - /// - /// Gets/Sets the size of the compressed data. - /// - /// - /// The compressed entry size or -1 if unknown. - /// - public long CompressedSize - { - get { - return (known & Known.CompressedSize) != 0 ? (long)compressedSize : -1L; - } - set { - this.compressedSize = (ulong)value; - this.known |= Known.CompressedSize; - } - } - - /// - /// Gets/Sets the crc of the uncompressed data. - /// - /// - /// Crc is not in the range 0..0xffffffffL - /// - /// - /// The crc value or -1 if unknown. - /// - public long Crc - { - get { - return (known & Known.Crc) != 0 ? crc & 0xffffffffL : -1L; - } - set { - if (((ulong)crc & 0xffffffff00000000L) != 0) { - throw new ArgumentOutOfRangeException("value"); - } - this.crc = (uint)value; - this.known |= Known.Crc; - } - } - - /// - /// Gets/Sets the compression method. Only Deflated and Stored are supported. - /// - /// - /// The compression method for this entry - /// - /// - /// - public CompressionMethod CompressionMethod { - get { - return method; - } - - set { - if ( !IsCompressionMethodSupported(value) ) { - throw new NotSupportedException("Compression method not supported"); - } - this.method = value; - } - } - - /// - /// Gets the compression method for outputting to the local or central header. - /// Returns same value as CompressionMethod except when AES encrypting, which - /// places 99 in the method and places the real method in the extra data. - /// - internal CompressionMethod CompressionMethodForHeader { - get { - return (AESKeySize > 0) ? CompressionMethod.WinZipAES : method; - } - } - - /// - /// Gets/Sets the extra data. - /// - /// - /// Extra data is longer than 64KB (0xffff) bytes. - /// - /// - /// Extra data or null if not set. - /// - public byte[] ExtraData { - - get { + /// + /// Defines known values for the property. + /// + public enum HostSystemID + { + /// + /// Host system = MSDOS + /// + Msdos = 0, + /// + /// Host system = Amiga + /// + Amiga = 1, + /// + /// Host system = Open VMS + /// + OpenVms = 2, + /// + /// Host system = Unix + /// + Unix = 3, + /// + /// Host system = VMCms + /// + VMCms = 4, + /// + /// Host system = Atari ST + /// + AtariST = 5, + /// + /// Host system = OS2 + /// + OS2 = 6, + /// + /// Host system = Macintosh + /// + Macintosh = 7, + /// + /// Host system = ZSystem + /// + ZSystem = 8, + /// + /// Host system = Cpm + /// + Cpm = 9, + /// + /// Host system = Windows NT + /// + WindowsNT = 10, + /// + /// Host system = MVS + /// + MVS = 11, + /// + /// Host system = VSE + /// + Vse = 12, + /// + /// Host system = Acorn RISC + /// + AcornRisc = 13, + /// + /// Host system = VFAT + /// + Vfat = 14, + /// + /// Host system = Alternate MVS + /// + AlternateMvs = 15, + /// + /// Host system = BEOS + /// + BeOS = 16, + /// + /// Host system = Tandem + /// + Tandem = 17, + /// + /// Host system = OS400 + /// + OS400 = 18, + /// + /// Host system = OSX + /// + OSX = 19, + /// + /// Host system = WinZIP AES + /// + WinZipAES = 99, + } + + /// + /// This class represents an entry in a zip archive. This can be a file + /// or a directory + /// ZipFile and ZipInputStream will give you instances of this class as + /// information about the members in an archive. ZipOutputStream + /// uses an instance of this class when creating an entry in a Zip file. + ///
    + ///
    Author of the original java version : Jochen Hoenicke + ///
    + public class ZipEntry : ICloneable + { + [Flags] + enum Known : byte + { + None = 0, + Size = 0x01, + CompressedSize = 0x02, + Crc = 0x04, + Time = 0x08, + ExternalAttributes = 0x10, + } + + #region Constructors + /// + /// Creates a zip entry with the given name. + /// + /// + /// The name for this entry. Can include directory components. + /// The convention for names is 'unix' style paths with relative names only. + /// There are with no device names and path elements are separated by '/' characters. + /// + /// + /// The name passed is null + /// + public ZipEntry(string name) + : this(name, 0, ZipConstants.VersionMadeBy, CompressionMethod.Deflated) + { + } + + /// + /// Creates a zip entry with the given name and version required to extract + /// + /// + /// The name for this entry. Can include directory components. + /// The convention for names is 'unix' style paths with no device names and + /// path elements separated by '/' characters. This is not enforced see CleanName + /// on how to ensure names are valid if this is desired. + /// + /// + /// The minimum 'feature version' required this entry + /// + /// + /// The name passed is null + /// + internal ZipEntry(string name, int versionRequiredToExtract) + : this(name, versionRequiredToExtract, ZipConstants.VersionMadeBy, + CompressionMethod.Deflated) + { + } + + /// + /// Initializes an entry with the given name and made by information + /// + /// Name for this entry + /// Version and HostSystem Information + /// Minimum required zip feature version required to extract this entry + /// Compression method for this entry. + /// + /// The name passed is null + /// + /// + /// versionRequiredToExtract should be 0 (auto-calculate) or > 10 + /// + /// + /// This constructor is used by the ZipFile class when reading from the central header + /// It is not generally useful, use the constructor specifying the name only. + /// + internal ZipEntry(string name, int versionRequiredToExtract, int madeByInfo, + CompressionMethod method) + { + if (name == null) { + throw new System.ArgumentNullException("name"); + } + + if ( name.Length > 0xffff ) { + throw new ArgumentException("Name is too long", "name"); + } + + if ( (versionRequiredToExtract != 0) && (versionRequiredToExtract < 10) ) { + throw new ArgumentOutOfRangeException("versionRequiredToExtract"); + } + + this.DateTime = System.DateTime.Now; + this.name = name; + this.versionMadeBy = (ushort)madeByInfo; + this.versionToExtract = (ushort)versionRequiredToExtract; + this.method = method; + } + + /// + /// Creates a deep copy of the given zip entry. + /// + /// + /// The entry to copy. + /// + [Obsolete("Use Clone instead")] + public ZipEntry(ZipEntry entry) + { + if ( entry == null ) { + throw new ArgumentNullException("entry"); + } + + known = entry.known; + name = entry.name; + size = entry.size; + compressedSize = entry.compressedSize; + crc = entry.crc; + dosTime = entry.dosTime; + method = entry.method; + comment = entry.comment; + versionToExtract = entry.versionToExtract; + versionMadeBy = entry.versionMadeBy; + externalFileAttributes = entry.externalFileAttributes; + flags = entry.flags; + + zipFileIndex = entry.zipFileIndex; + offset = entry.offset; + + forceZip64_ = entry.forceZip64_; + + if ( entry.extra != null ) { + extra = new byte[entry.extra.Length]; + Array.Copy(entry.extra, 0, extra, 0, entry.extra.Length); + } + } + + #endregion + + /// + /// Get a value indicating wether the entry has a CRC value available. + /// + public bool HasCrc + { + get { + return (known & Known.Crc) != 0; + } + } + + /// + /// Get/Set flag indicating if entry is encrypted. + /// A simple helper routine to aid interpretation of flags + /// + /// This is an assistant that interprets the flags property. + public bool IsCrypted + { + get { + return (flags & 1) != 0; + } + set { + if (value) { + flags |= 1; + } + else { + flags &= ~1; + } + } + } + + /// + /// Get / set a flag indicating wether entry name and comment text are + /// encoded in unicode UTF8. + /// + /// This is an assistant that interprets the flags property. + public bool IsUnicodeText + { + get { + return ( flags & (int)GeneralBitFlags.UnicodeText ) != 0; + } + set { + if ( value ) { + flags |= (int)GeneralBitFlags.UnicodeText; + } + else { + flags &= ~(int)GeneralBitFlags.UnicodeText; + } + } + } + + /// + /// Value used during password checking for PKZIP 2.0 / 'classic' encryption. + /// + internal byte CryptoCheckValue + { + get { + return cryptoCheckValue_; + } + + set { + cryptoCheckValue_ = value; + } + } + + /// + /// Get/Set general purpose bit flag for entry + /// + /// + /// General purpose bit flag
    + ///
    + /// Bit 0: If set, indicates the file is encrypted
    + /// Bit 1-2 Only used for compression type 6 Imploding, and 8, 9 deflating
    + /// Imploding:
    + /// Bit 1 if set indicates an 8K sliding dictionary was used. If clear a 4k dictionary was used
    + /// Bit 2 if set indicates 3 Shannon-Fanno trees were used to encode the sliding dictionary, 2 otherwise
    + ///
    + /// Deflating:
    + /// Bit 2 Bit 1
    + /// 0 0 Normal compression was used
    + /// 0 1 Maximum compression was used
    + /// 1 0 Fast compression was used
    + /// 1 1 Super fast compression was used
    + ///
    + /// Bit 3: If set, the fields crc-32, compressed size + /// and uncompressed size are were not able to be written during zip file creation + /// The correct values are held in a data descriptor immediately following the compressed data.
    + /// Bit 4: Reserved for use by PKZIP for enhanced deflating
    + /// Bit 5: If set indicates the file contains compressed patch data
    + /// Bit 6: If set indicates strong encryption was used.
    + /// Bit 7-10: Unused or reserved
    + /// Bit 11: If set the name and comments for this entry are in unicode.
    + /// Bit 12-15: Unused or reserved
    + ///
    + /// + /// + public int Flags + { + get { + return flags; + } + set { + flags = value; + } + } + + /// + /// Get/Set index of this entry in Zip file + /// + /// This is only valid when the entry is part of a + public long ZipFileIndex + { + get { + return zipFileIndex; + } + set { + zipFileIndex = value; + } + } + + /// + /// Get/set offset for use in central header + /// + public long Offset + { + get { + return offset; + } + set { + offset = value; + } + } + + /// + /// Get/Set external file attributes as an integer. + /// The values of this are operating system dependant see + /// HostSystem for details + /// + public int ExternalFileAttributes + { + get { + if ((known & Known.ExternalAttributes) == 0) { + return -1; + } + else { + return externalFileAttributes; + } + } + + set { + externalFileAttributes = value; + known |= Known.ExternalAttributes; + } + } + + /// + /// Get the version made by for this entry or zero if unknown. + /// The value / 10 indicates the major version number, and + /// the value mod 10 is the minor version number + /// + public int VersionMadeBy + { + get { + return (versionMadeBy & 0xff); + } + } + + /// + /// Get a value indicating this entry is for a DOS/Windows system. + /// + public bool IsDOSEntry + { + get { + return ((HostSystem == ( int )HostSystemID.Msdos) || + (HostSystem == ( int )HostSystemID.WindowsNT)); + } + } + + /// + /// Test the external attributes for this to + /// see if the external attributes are Dos based (including WINNT and variants) + /// and match the values + /// + /// The attributes to test. + /// Returns true if the external attributes are known to be DOS/Windows + /// based and have the same attributes set as the value passed. + bool HasDosAttributes(int attributes) + { + bool result = false; + if ( (known & Known.ExternalAttributes) != 0 ) { + if ( ((HostSystem == (int)HostSystemID.Msdos) || + (HostSystem == (int)HostSystemID.WindowsNT)) && + (ExternalFileAttributes & attributes) == attributes) { + result = true; + } + } + return result; + } + + /// + /// Gets the compatability information for the external file attribute + /// If the external file attributes are compatible with MS-DOS and can be read + /// by PKZIP for DOS version 2.04g then this value will be zero. Otherwise the value + /// will be non-zero and identify the host system on which the attributes are compatible. + /// + /// + /// + /// The values for this as defined in the Zip File format and by others are shown below. The values are somewhat + /// misleading in some cases as they are not all used as shown. You should consult the relevant documentation + /// to obtain up to date and correct information. The modified appnote by the infozip group is + /// particularly helpful as it documents a lot of peculiarities. The document is however a little dated. + /// + /// 0 - MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems) + /// 1 - Amiga + /// 2 - OpenVMS + /// 3 - Unix + /// 4 - VM/CMS + /// 5 - Atari ST + /// 6 - OS/2 HPFS + /// 7 - Macintosh + /// 8 - Z-System + /// 9 - CP/M + /// 10 - Windows NTFS + /// 11 - MVS (OS/390 - Z/OS) + /// 12 - VSE + /// 13 - Acorn Risc + /// 14 - VFAT + /// 15 - Alternate MVS + /// 16 - BeOS + /// 17 - Tandem + /// 18 - OS/400 + /// 19 - OS/X (Darwin) + /// 99 - WinZip AES + /// remainder - unused + /// + /// + public int HostSystem + { + get { + return (versionMadeBy >> 8) & 0xff; + } + + set { + versionMadeBy &= 0xff; + versionMadeBy |= (ushort)((value & 0xff) << 8); + } + } + + /// + /// Get minimum Zip feature version required to extract this entry + /// + /// + /// Minimum features are defined as:
    + /// 1.0 - Default value
    + /// 1.1 - File is a volume label
    + /// 2.0 - File is a folder/directory
    + /// 2.0 - File is compressed using Deflate compression
    + /// 2.0 - File is encrypted using traditional encryption
    + /// 2.1 - File is compressed using Deflate64
    + /// 2.5 - File is compressed using PKWARE DCL Implode
    + /// 2.7 - File is a patch data set
    + /// 4.5 - File uses Zip64 format extensions
    + /// 4.6 - File is compressed using BZIP2 compression
    + /// 5.0 - File is encrypted using DES
    + /// 5.0 - File is encrypted using 3DES
    + /// 5.0 - File is encrypted using original RC2 encryption
    + /// 5.0 - File is encrypted using RC4 encryption
    + /// 5.1 - File is encrypted using AES encryption
    + /// 5.1 - File is encrypted using corrected RC2 encryption
    + /// 5.1 - File is encrypted using corrected RC2-64 encryption
    + /// 6.1 - File is encrypted using non-OAEP key wrapping
    + /// 6.2 - Central directory encryption (not confirmed yet)
    + /// 6.3 - File is compressed using LZMA
    + /// 6.3 - File is compressed using PPMD+
    + /// 6.3 - File is encrypted using Blowfish
    + /// 6.3 - File is encrypted using Twofish
    + ///
    + /// + public int Version + { + get { + // Return recorded version if known. + if (versionToExtract != 0) { + return versionToExtract; + } + else { + int result = 10; + if (AESKeySize > 0) { + result = ZipConstants.VERSION_AES; // Ver 5.1 = AES + } + else if (CentralHeaderRequiresZip64) { + result = ZipConstants.VersionZip64; + } + else if (CompressionMethod.Deflated == method) { + result = 20; + } + else if (IsDirectory == true) { + result = 20; + } + else if (IsCrypted == true) { + result = 20; + } + else if (HasDosAttributes(0x08) ) { + result = 11; + } + return result; + } + } + } + + /// + /// Get a value indicating whether this entry can be decompressed by the library. + /// + /// This is based on the and + /// wether the compression method is supported. + public bool CanDecompress + { + get { + return (Version <= ZipConstants.VersionMadeBy) && + ((Version == 10) || + (Version == 11) || + (Version == 20) || + (Version == 45) || + (Version == 51)) && + IsCompressionMethodSupported(); + } + } + + /// + /// Force this entry to be recorded using Zip64 extensions. + /// + public void ForceZip64() + { + forceZip64_ = true; + } + + /// + /// Get a value indicating wether Zip64 extensions were forced. + /// + /// A value of true if Zip64 extensions have been forced on; false if not. + public bool IsZip64Forced() + { + return forceZip64_; + } + + /// + /// Gets a value indicating if the entry requires Zip64 extensions + /// to store the full entry values. + /// + /// A value of true if a local header requires Zip64 extensions; false if not. + public bool LocalHeaderRequiresZip64 + { + get { + bool result = forceZip64_; + + if ( !result ) { + ulong trueCompressedSize = compressedSize; + + if ( (versionToExtract == 0) && IsCrypted ) { + trueCompressedSize += ZipConstants.CryptoHeaderSize; + } + + // TODO: A better estimation of the true limit based on compression overhead should be used + // to determine when an entry should use Zip64. + result = + ((this.size >= uint.MaxValue) || (trueCompressedSize >= uint.MaxValue)) && + ((versionToExtract == 0) || (versionToExtract >= ZipConstants.VersionZip64)); + } + + return result; + } + } + + /// + /// Get a value indicating wether the central directory entry requires Zip64 extensions to be stored. + /// + public bool CentralHeaderRequiresZip64 + { + get { + return LocalHeaderRequiresZip64 || (offset >= uint.MaxValue); + } + } + + /// + /// Get/Set DosTime value. + /// + /// + /// The MS-DOS date format can only represent dates between 1/1/1980 and 12/31/2107. + /// + public long DosTime + { + get { + if ((known & Known.Time) == 0) { + return 0; + } + else { + return dosTime; + } + } + + set { + unchecked { + dosTime = (uint)value; + } + + known |= Known.Time; + } + } + + /// + /// Gets/Sets the time of last modification of the entry. + /// + /// + /// The property is updated to match this as far as possible. + /// + public DateTime DateTime + { + get { + uint sec = Math.Min(59, 2 * (dosTime & 0x1f)); + uint min = Math.Min(59, (dosTime >> 5) & 0x3f); + uint hrs = Math.Min(23, (dosTime >> 11) & 0x1f); + uint mon = Math.Max(1, Math.Min(12, ((dosTime >> 21) & 0xf))); + uint year = ((dosTime >> 25) & 0x7f) + 1980; + int day = Math.Max(1, Math.Min(DateTime.DaysInMonth((int)year, (int)mon), (int)((dosTime >> 16) & 0x1f))); + return new System.DateTime((int)year, (int)mon, day, (int)hrs, (int)min, (int)sec); + } + + set { + uint year = (uint) value.Year; + uint month = (uint) value.Month; + uint day = (uint) value.Day; + uint hour = (uint) value.Hour; + uint minute = (uint) value.Minute; + uint second = (uint) value.Second; + + if ( year < 1980 ) { + year = 1980; + month = 1; + day = 1; + hour = 0; + minute = 0; + second = 0; + } + else if ( year > 2107 ) { + year = 2107; + month = 12; + day = 31; + hour = 23; + minute = 59; + second = 59; + } + + DosTime = ((year - 1980) & 0x7f) << 25 | + (month << 21) | + (day << 16) | + (hour << 11) | + (minute << 5) | + (second >> 1); + } + } + + /// + /// Returns the entry name. + /// + /// + /// The unix naming convention is followed. + /// Path components in the entry should always separated by forward slashes ('/'). + /// Dos device names like C: should also be removed. + /// See the class, or + /// + public string Name + { + get { + return name; + } + } + + /// + /// Gets/Sets the size of the uncompressed data. + /// + /// + /// The size or -1 if unknown. + /// + /// Setting the size before adding an entry to an archive can help + /// avoid compatability problems with some archivers which dont understand Zip64 extensions. + public long Size + { + get { + return (known & Known.Size) != 0 ? (long)size : -1L; + } + set { + this.size = (ulong)value; + this.known |= Known.Size; + } + } + + /// + /// Gets/Sets the size of the compressed data. + /// + /// + /// The compressed entry size or -1 if unknown. + /// + public long CompressedSize + { + get { + return (known & Known.CompressedSize) != 0 ? (long)compressedSize : -1L; + } + set { + this.compressedSize = (ulong)value; + this.known |= Known.CompressedSize; + } + } + + /// + /// Gets/Sets the crc of the uncompressed data. + /// + /// + /// Crc is not in the range 0..0xffffffffL + /// + /// + /// The crc value or -1 if unknown. + /// + public long Crc + { + get { + return (known & Known.Crc) != 0 ? crc & 0xffffffffL : -1L; + } + set { + if (((ulong)crc & 0xffffffff00000000L) != 0) { + throw new ArgumentOutOfRangeException("value"); + } + this.crc = (uint)value; + this.known |= Known.Crc; + } + } + + /// + /// Gets/Sets the compression method. Only Deflated and Stored are supported. + /// + /// + /// The compression method for this entry + /// + /// + /// + public CompressionMethod CompressionMethod { + get { + return method; + } + + set { + if ( !IsCompressionMethodSupported(value) ) { + throw new NotSupportedException("Compression method not supported"); + } + this.method = value; + } + } + + /// + /// Gets the compression method for outputting to the local or central header. + /// Returns same value as CompressionMethod except when AES encrypting, which + /// places 99 in the method and places the real method in the extra data. + /// + internal CompressionMethod CompressionMethodForHeader { + get { + return (AESKeySize > 0) ? CompressionMethod.WinZipAES : method; + } + } + + /// + /// Gets/Sets the extra data. + /// + /// + /// Extra data is longer than 64KB (0xffff) bytes. + /// + /// + /// Extra data or null if not set. + /// + public byte[] ExtraData { + + get { // TODO: This is slightly safer but less efficient. Think about wether it should change. -// return (byte[]) extra.Clone(); - return extra; - } - - set { - if (value == null) { - extra = null; - } - else { - if (value.Length > 0xffff) { - throw new System.ArgumentOutOfRangeException("value"); - } - - extra = new byte[value.Length]; - Array.Copy(value, 0, extra, 0, value.Length); - } - } - } +// return (byte[]) extra.Clone(); + return extra; + } + + set { + if (value == null) { + extra = null; + } + else { + if (value.Length > 0xffff) { + throw new System.ArgumentOutOfRangeException("value"); + } + + extra = new byte[value.Length]; + Array.Copy(value, 0, extra, 0, value.Length); + } + } + } #if !NET_1_1 && !NETCF_2_0 - /// - /// For AES encrypted files returns or sets the number of bits of encryption (128, 192 or 256). - /// When setting, only 0 (off), 128 or 256 is supported. - /// - public int AESKeySize { - get { - // the strength (1 or 3) is in the entry header - switch (_aesEncryptionStrength) { - case 0: return 0; // Not AES - case 1: return 128; - case 2: return 192; // Not used by WinZip - case 3: return 256; - default: throw new ZipException("Invalid AESEncryptionStrength " + _aesEncryptionStrength); - } - } - set { - switch (value) { - case 0: _aesEncryptionStrength = 0; break; - case 128: _aesEncryptionStrength = 1; break; - case 256: _aesEncryptionStrength = 3; break; - default: throw new ZipException("AESKeySize must be 0, 128 or 256: " + value); - } - } - } - - /// - /// AES Encryption strength for storage in extra data in entry header. - /// 1 is 128 bit, 2 is 192 bit, 3 is 256 bit. - /// - internal byte AESEncryptionStrength { - get { - return (byte)_aesEncryptionStrength; - } - } + /// + /// For AES encrypted files returns or sets the number of bits of encryption (128, 192 or 256). + /// When setting, only 0 (off), 128 or 256 is supported. + /// + public int AESKeySize { + get { + // the strength (1 or 3) is in the entry header + switch (_aesEncryptionStrength) { + case 0: return 0; // Not AES + case 1: return 128; + case 2: return 192; // Not used by WinZip + case 3: return 256; + default: throw new ZipException("Invalid AESEncryptionStrength " + _aesEncryptionStrength); + } + } + set { + switch (value) { + case 0: _aesEncryptionStrength = 0; break; + case 128: _aesEncryptionStrength = 1; break; + case 256: _aesEncryptionStrength = 3; break; + default: throw new ZipException("AESKeySize must be 0, 128 or 256: " + value); + } + } + } + + /// + /// AES Encryption strength for storage in extra data in entry header. + /// 1 is 128 bit, 2 is 192 bit, 3 is 256 bit. + /// + internal byte AESEncryptionStrength { + get { + return (byte)_aesEncryptionStrength; + } + } #else - /// - /// AES unsupported prior to .NET 2.0 - /// - internal int AESKeySize; + /// + /// AES unsupported prior to .NET 2.0 + /// + internal int AESKeySize; #endif - /// - /// Returns the length of the salt, in bytes - /// - internal int AESSaltLen { - get { - // Key size -> Salt length: 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes. - return AESKeySize / 16; - } - } - - /// - /// Number of extra bytes required to hold the AES Header fields (Salt, Pwd verify, AuthCode) - /// - internal int AESOverheadSize { - get { - // File format: - // Bytes Content - // Variable Salt value - // 2 Password verification value - // Variable Encrypted file data - // 10 Authentication code - return 12 + AESSaltLen; - } - } - - /// - /// Process extra data fields updating the entry based on the contents. - /// - /// True if the extra data fields should be handled - /// for a local header, rather than for a central header. - /// - internal void ProcessExtraData(bool localHeader) - { - ZipExtraData extraData = new ZipExtraData(this.extra); - - if ( extraData.Find(0x0001) ) { + /// + /// Returns the length of the salt, in bytes + /// + internal int AESSaltLen { + get { + // Key size -> Salt length: 128 bits = 8 bytes, 192 bits = 12 bytes, 256 bits = 16 bytes. + return AESKeySize / 16; + } + } + + /// + /// Number of extra bytes required to hold the AES Header fields (Salt, Pwd verify, AuthCode) + /// + internal int AESOverheadSize { + get { + // File format: + // Bytes Content + // Variable Salt value + // 2 Password verification value + // Variable Encrypted file data + // 10 Authentication code + return 12 + AESSaltLen; + } + } + + /// + /// Process extra data fields updating the entry based on the contents. + /// + /// True if the extra data fields should be handled + /// for a local header, rather than for a central header. + /// + internal void ProcessExtraData(bool localHeader) + { + ZipExtraData extraData = new ZipExtraData(this.extra); + + if ( extraData.Find(0x0001) ) { // Version required to extract is ignored here as some archivers dont set it correctly // in theory it should be version 45 or higher - // The recorded size will change but remember that this is zip64. - forceZip64_ = true; + // The recorded size will change but remember that this is zip64. + forceZip64_ = true; - if ( extraData.ValueLength < 4 ) { - throw new ZipException("Extra data extended Zip64 information length is invalid"); - } + if ( extraData.ValueLength < 4 ) { + throw new ZipException("Extra data extended Zip64 information length is invalid"); + } - if ( localHeader || (size == uint.MaxValue) ) { - size = (ulong)extraData.ReadLong(); - } + if ( localHeader || (size == uint.MaxValue) ) { + size = (ulong)extraData.ReadLong(); + } - if ( localHeader || (compressedSize == uint.MaxValue) ) { - compressedSize = (ulong)extraData.ReadLong(); - } + if ( localHeader || (compressedSize == uint.MaxValue) ) { + compressedSize = (ulong)extraData.ReadLong(); + } - if ( !localHeader && (offset == uint.MaxValue) ) { - offset = extraData.ReadLong(); - } + if ( !localHeader && (offset == uint.MaxValue) ) { + offset = extraData.ReadLong(); + } // Disk number on which file starts is ignored - } - else { - if ( - ((versionToExtract & 0xff) >= ZipConstants.VersionZip64) && - ((size == uint.MaxValue) || (compressedSize == uint.MaxValue)) - ) { - throw new ZipException("Zip64 Extended information required but is missing."); - } - } - - if ( extraData.Find(10) ) { - // No room for any tags. - if ( extraData.ValueLength < 4 ) { - throw new ZipException("NTFS Extra data invalid"); - } - - extraData.ReadInt(); // Reserved - - while ( extraData.UnreadCount >= 4 ) { - int ntfsTag = extraData.ReadShort(); - int ntfsLength = extraData.ReadShort(); - if ( ntfsTag == 1 ) { - if ( ntfsLength >= 24 ) { - long lastModification = extraData.ReadLong(); - long lastAccess = extraData.ReadLong(); - long createTime = extraData.ReadLong(); - - DateTime = System.DateTime.FromFileTime(lastModification); - } - break; - } - else { - // An unknown NTFS tag so simply skip it. - extraData.Skip(ntfsLength); - } - } - } - else if ( extraData.Find(0x5455) ) { - int length = extraData.ValueLength; - int flags = extraData.ReadByte(); - - // Can include other times but these are ignored. Length of data should - // actually be 1 + 4 * no of bits in flags. - if ( ((flags & 1) != 0) && (length >= 5) ) { - int iTime = extraData.ReadInt(); - - DateTime = (new System.DateTime ( 1970, 1, 1, 0, 0, 0 ).ToUniversalTime() + - new TimeSpan ( 0, 0, 0, iTime, 0 )).ToLocalTime(); - } - } - if (method == CompressionMethod.WinZipAES) { - ProcessAESExtraData(extraData); - } - } - - // For AES the method in the entry is 99, and the real compression method is in the extradata - // - private void ProcessAESExtraData(ZipExtraData extraData) { + } + else { + if ( + ((versionToExtract & 0xff) >= ZipConstants.VersionZip64) && + ((size == uint.MaxValue) || (compressedSize == uint.MaxValue)) + ) { + throw new ZipException("Zip64 Extended information required but is missing."); + } + } + + if ( extraData.Find(10) ) { + // No room for any tags. + if ( extraData.ValueLength < 4 ) { + throw new ZipException("NTFS Extra data invalid"); + } + + extraData.ReadInt(); // Reserved + + while ( extraData.UnreadCount >= 4 ) { + int ntfsTag = extraData.ReadShort(); + int ntfsLength = extraData.ReadShort(); + if ( ntfsTag == 1 ) { + if ( ntfsLength >= 24 ) { + long lastModification = extraData.ReadLong(); + long lastAccess = extraData.ReadLong(); + long createTime = extraData.ReadLong(); + + DateTime = System.DateTime.FromFileTime(lastModification); + } + break; + } + else { + // An unknown NTFS tag so simply skip it. + extraData.Skip(ntfsLength); + } + } + } + else if ( extraData.Find(0x5455) ) { + int length = extraData.ValueLength; + int flags = extraData.ReadByte(); + + // Can include other times but these are ignored. Length of data should + // actually be 1 + 4 * no of bits in flags. + if ( ((flags & 1) != 0) && (length >= 5) ) { + int iTime = extraData.ReadInt(); + + DateTime = (new System.DateTime ( 1970, 1, 1, 0, 0, 0 ).ToUniversalTime() + + new TimeSpan ( 0, 0, 0, iTime, 0 )).ToLocalTime(); + } + } + if (method == CompressionMethod.WinZipAES) { + ProcessAESExtraData(extraData); + } + } + + // For AES the method in the entry is 99, and the real compression method is in the extradata + // + private void ProcessAESExtraData(ZipExtraData extraData) { #if !NET_1_1 && !NETCF_2_0 - if (extraData.Find(0x9901)) { - // Set version and flag for Zipfile.CreateAndInitDecryptionStream - versionToExtract = ZipConstants.VERSION_AES; // Ver 5.1 = AES see "Version" getter - // Set StrongEncryption flag for ZipFile.CreateAndInitDecryptionStream - Flags = Flags | (int)GeneralBitFlags.StrongEncryption; - // - // Unpack AES extra data field see http://www.winzip.com/aes_info.htm - int length = extraData.ValueLength; // Data size currently 7 - if (length < 7) - throw new ZipException("AES Extra Data Length " + length + " invalid."); - int ver = extraData.ReadShort(); // Version number (1=AE-1 2=AE-2) - int vendorId = extraData.ReadShort(); // 2-character vendor ID 0x4541 = "AE" - int encrStrength = extraData.ReadByte(); // encryption strength 1 = 128 2 = 192 3 = 256 - int actualCompress = extraData.ReadShort(); // The actual compression method used to compress the file - _aesVer = ver; - _aesEncryptionStrength = encrStrength; - method = (CompressionMethod)actualCompress; - } else - throw new ZipException("AES Extra Data missing"); + if (extraData.Find(0x9901)) { + // Set version and flag for Zipfile.CreateAndInitDecryptionStream + versionToExtract = ZipConstants.VERSION_AES; // Ver 5.1 = AES see "Version" getter + // Set StrongEncryption flag for ZipFile.CreateAndInitDecryptionStream + Flags = Flags | (int)GeneralBitFlags.StrongEncryption; + // + // Unpack AES extra data field see http://www.winzip.com/aes_info.htm + int length = extraData.ValueLength; // Data size currently 7 + if (length < 7) + throw new ZipException("AES Extra Data Length " + length + " invalid."); + int ver = extraData.ReadShort(); // Version number (1=AE-1 2=AE-2) + int vendorId = extraData.ReadShort(); // 2-character vendor ID 0x4541 = "AE" + int encrStrength = extraData.ReadByte(); // encryption strength 1 = 128 2 = 192 3 = 256 + int actualCompress = extraData.ReadShort(); // The actual compression method used to compress the file + _aesVer = ver; + _aesEncryptionStrength = encrStrength; + method = (CompressionMethod)actualCompress; + } else + throw new ZipException("AES Extra Data missing"); #else - throw new ZipException("AES unsupported"); + throw new ZipException("AES unsupported"); #endif - } - - /// - /// Gets/Sets the entry comment. - /// - /// - /// If comment is longer than 0xffff. - /// - /// - /// The comment or null if not set. - /// - /// - /// A comment is only available for entries when read via the class. - /// The class doesnt have the comment data available. - /// - public string Comment { - get { - return comment; - } - set { - // This test is strictly incorrect as the length is in characters - // while the storage limit is in bytes. - // While the test is partially correct in that a comment of this length or greater - // is definitely invalid, shorter comments may also have an invalid length - // where there are multi-byte characters - // The full test is not possible here however as the code page to apply conversions with - // isnt available. - if ( (value != null) && (value.Length > 0xffff) ) { + } + + /// + /// Gets/Sets the entry comment. + /// + /// + /// If comment is longer than 0xffff. + /// + /// + /// The comment or null if not set. + /// + /// + /// A comment is only available for entries when read via the class. + /// The class doesnt have the comment data available. + /// + public string Comment { + get { + return comment; + } + set { + // This test is strictly incorrect as the length is in characters + // while the storage limit is in bytes. + // While the test is partially correct in that a comment of this length or greater + // is definitely invalid, shorter comments may also have an invalid length + // where there are multi-byte characters + // The full test is not possible here however as the code page to apply conversions with + // isnt available. + if ( (value != null) && (value.Length > 0xffff) ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("value"); + throw new ArgumentOutOfRangeException("value"); #else - throw new ArgumentOutOfRangeException("value", "cannot exceed 65535"); + throw new ArgumentOutOfRangeException("value", "cannot exceed 65535"); #endif - } - - comment = value; - } - } - - /// - /// Gets a value indicating if the entry is a directory. - /// however. - /// - /// - /// A directory is determined by an entry name with a trailing slash '/'. - /// The external file attributes can also indicate an entry is for a directory. - /// Currently only dos/windows attributes are tested in this manner. - /// The trailing slash convention should always be followed. - /// - public bool IsDirectory - { - get { - int nameLength = name.Length; - bool result = - ((nameLength > 0) && - ((name[nameLength - 1] == '/') || (name[nameLength - 1] == '\\'))) || - HasDosAttributes(16) - ; - return result; - } - } - - /// - /// Get a value of true if the entry appears to be a file; false otherwise - /// - /// - /// This only takes account of DOS/Windows attributes. Other operating systems are ignored. - /// For linux and others the result may be incorrect. - /// - public bool IsFile - { - get { - return !IsDirectory && !HasDosAttributes(8); - } - } - - /// - /// Test entry to see if data can be extracted. - /// - /// Returns true if data can be extracted for this entry; false otherwise. - public bool IsCompressionMethodSupported() - { - return IsCompressionMethodSupported(CompressionMethod); - } - - #region ICloneable Members - /// - /// Creates a copy of this zip entry. - /// - /// An that is a copy of the current instance. - public object Clone() - { - ZipEntry result = (ZipEntry)this.MemberwiseClone(); - - // Ensure extra data is unique if it exists. - if ( extra != null ) { - result.extra = new byte[extra.Length]; - Array.Copy(extra, 0, result.extra, 0, extra.Length); - } - - return result; - } - - #endregion - - /// - /// Gets a string representation of this ZipEntry. - /// - /// A readable textual representation of this - public override string ToString() - { - return name; - } - - /// - /// Test a compression method to see if this library - /// supports extracting data compressed with that method - /// - /// The compression method to test. - /// Returns true if the compression method is supported; false otherwise - public static bool IsCompressionMethodSupported(CompressionMethod method) - { - return - ( method == CompressionMethod.Deflated ) || - ( method == CompressionMethod.Stored ); - } - - /// - /// Cleans a name making it conform to Zip file conventions. - /// Devices names ('c:\') and UNC share names ('\\server\share') are removed - /// and forward slashes ('\') are converted to back slashes ('/'). - /// Names are made relative by trimming leading slashes which is compatible - /// with the ZIP naming convention. - /// - /// The name to clean - /// The 'cleaned' name. - /// - /// The Zip name transform class is more flexible. - /// - public static string CleanName(string name) - { - if (name == null) { - return string.Empty; - } - - if (Path.IsPathRooted(name) == true) { - // NOTE: - // for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt - name = name.Substring(Path.GetPathRoot(name).Length); - } - - name = name.Replace(@"\", "/"); - - while ( (name.Length > 0) && (name[0] == '/')) { - name = name.Remove(0, 1); - } - return name; - } - - #region Instance Fields - Known known; - int externalFileAttributes = -1; // contains external attributes (O/S dependant) - - ushort versionMadeBy; // Contains host system and version information - // only relevant for central header entries - - string name; - ulong size; - ulong compressedSize; - ushort versionToExtract; // Version required to extract (library handles <= 2.0) - uint crc; - uint dosTime; - - CompressionMethod method = CompressionMethod.Deflated; - byte[] extra; - string comment; - - int flags; // general purpose bit flags - - long zipFileIndex = -1; // used by ZipFile - long offset; // used by ZipFile and ZipOutputStream - - bool forceZip64_; - byte cryptoCheckValue_; + } + + comment = value; + } + } + + /// + /// Gets a value indicating if the entry is a directory. + /// however. + /// + /// + /// A directory is determined by an entry name with a trailing slash '/'. + /// The external file attributes can also indicate an entry is for a directory. + /// Currently only dos/windows attributes are tested in this manner. + /// The trailing slash convention should always be followed. + /// + public bool IsDirectory + { + get { + int nameLength = name.Length; + bool result = + ((nameLength > 0) && + ((name[nameLength - 1] == '/') || (name[nameLength - 1] == '\\'))) || + HasDosAttributes(16) + ; + return result; + } + } + + /// + /// Get a value of true if the entry appears to be a file; false otherwise + /// + /// + /// This only takes account of DOS/Windows attributes. Other operating systems are ignored. + /// For linux and others the result may be incorrect. + /// + public bool IsFile + { + get { + return !IsDirectory && !HasDosAttributes(8); + } + } + + /// + /// Test entry to see if data can be extracted. + /// + /// Returns true if data can be extracted for this entry; false otherwise. + public bool IsCompressionMethodSupported() + { + return IsCompressionMethodSupported(CompressionMethod); + } + + #region ICloneable Members + /// + /// Creates a copy of this zip entry. + /// + /// An that is a copy of the current instance. + public object Clone() + { + ZipEntry result = (ZipEntry)this.MemberwiseClone(); + + // Ensure extra data is unique if it exists. + if ( extra != null ) { + result.extra = new byte[extra.Length]; + Array.Copy(extra, 0, result.extra, 0, extra.Length); + } + + return result; + } + + #endregion + + /// + /// Gets a string representation of this ZipEntry. + /// + /// A readable textual representation of this + public override string ToString() + { + return name; + } + + /// + /// Test a compression method to see if this library + /// supports extracting data compressed with that method + /// + /// The compression method to test. + /// Returns true if the compression method is supported; false otherwise + public static bool IsCompressionMethodSupported(CompressionMethod method) + { + return + ( method == CompressionMethod.Deflated ) || + ( method == CompressionMethod.Stored ); + } + + /// + /// Cleans a name making it conform to Zip file conventions. + /// Devices names ('c:\') and UNC share names ('\\server\share') are removed + /// and forward slashes ('\') are converted to back slashes ('/'). + /// Names are made relative by trimming leading slashes which is compatible + /// with the ZIP naming convention. + /// + /// The name to clean + /// The 'cleaned' name. + /// + /// The Zip name transform class is more flexible. + /// + public static string CleanName(string name) + { + if (name == null) { + return string.Empty; + } + + if (Path.IsPathRooted(name) == true) { + // NOTE: + // for UNC names... \\machine\share\zoom\beet.txt gives \zoom\beet.txt + name = name.Substring(Path.GetPathRoot(name).Length); + } + + name = name.Replace(@"\", "/"); + + while ( (name.Length > 0) && (name[0] == '/')) { + name = name.Remove(0, 1); + } + return name; + } + + #region Instance Fields + Known known; + int externalFileAttributes = -1; // contains external attributes (O/S dependant) + + ushort versionMadeBy; // Contains host system and version information + // only relevant for central header entries + + string name; + ulong size; + ulong compressedSize; + ushort versionToExtract; // Version required to extract (library handles <= 2.0) + uint crc; + uint dosTime; + + CompressionMethod method = CompressionMethod.Deflated; + byte[] extra; + string comment; + + int flags; // general purpose bit flags + + long zipFileIndex = -1; // used by ZipFile + long offset; // used by ZipFile and ZipOutputStream + + bool forceZip64_; + byte cryptoCheckValue_; #if !NET_1_1 && !NETCF_2_0 - int _aesVer; // Version number (2 = AE-2 ?). Assigned but not used. - int _aesEncryptionStrength; // Encryption strength 1 = 128 2 = 192 3 = 256 + int _aesVer; // Version number (2 = AE-2 ?). Assigned but not used. + int _aesEncryptionStrength; // Encryption strength 1 = 128 2 = 192 3 = 256 #endif - #endregion - } + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipEntryFactory.cs b/External/Tools/AppMan/ZipLib/Zip/ZipEntryFactory.cs index 164a80e75c..7ab5327dc0 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipEntryFactory.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipEntryFactory.cs @@ -42,372 +42,372 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// Basic implementation of - /// - public class ZipEntryFactory : IEntryFactory - { - #region Enumerations - /// - /// Defines the possible values to be used for the . - /// - public enum TimeSetting - { - /// - /// Use the recorded LastWriteTime value for the file. - /// - LastWriteTime, - /// - /// Use the recorded LastWriteTimeUtc value for the file - /// - LastWriteTimeUtc, - /// - /// Use the recorded CreateTime value for the file. - /// - CreateTime, - /// - /// Use the recorded CreateTimeUtc value for the file. - /// - CreateTimeUtc, - /// - /// Use the recorded LastAccessTime value for the file. - /// - LastAccessTime, - /// - /// Use the recorded LastAccessTimeUtc value for the file. - /// - LastAccessTimeUtc, - /// - /// Use a fixed value. - /// - /// The actual value used can be - /// specified via the constructor or - /// using the with the setting set - /// to which will use the when this class was constructed. - /// The property can also be used to set this value. - Fixed, - } - #endregion - - #region Constructors - /// - /// Initialise a new instance of the class. - /// - /// A default , and the LastWriteTime for files is used. - public ZipEntryFactory() - { - nameTransform_ = new ZipNameTransform(); - } - - /// - /// Initialise a new instance of using the specified - /// - /// The time setting to use when creating Zip entries. - public ZipEntryFactory(TimeSetting timeSetting) - { - timeSetting_ = timeSetting; - nameTransform_ = new ZipNameTransform(); - } - - /// - /// Initialise a new instance of using the specified - /// - /// The time to set all values to. - public ZipEntryFactory(DateTime time) - { - timeSetting_ = TimeSetting.Fixed; - FixedDateTime = time; - nameTransform_ = new ZipNameTransform(); - } - - #endregion - - #region Properties - /// - /// Get / set the to be used when creating new values. - /// - /// - /// Setting this property to null will cause a default name transform to be used. - /// - public INameTransform NameTransform - { - get { return nameTransform_; } - set - { - if (value == null) { - nameTransform_ = new ZipNameTransform(); - } - else { - nameTransform_ = value; - } - } - } - - /// - /// Get / set the in use. - /// - public TimeSetting Setting - { - get { return timeSetting_; } - set { timeSetting_ = value; } - } - - /// - /// Get / set the value to use when is set to - /// - public DateTime FixedDateTime - { - get { return fixedDateTime_; } - set - { - if (value.Year < 1970) { - throw new ArgumentException("Value is too old to be valid", "value"); - } - fixedDateTime_ = value; - } - } - - /// - /// A bitmask defining the attributes to be retrieved from the actual file. - /// - /// The default is to get all possible attributes from the actual file. - public int GetAttributes - { - get { return getAttributes_; } - set { getAttributes_ = value; } - } - - /// - /// A bitmask defining which attributes are to be set on. - /// - /// By default no attributes are set on. - public int SetAttributes - { - get { return setAttributes_; } - set { setAttributes_ = value; } - } - - /// - /// Get set a value indicating wether unidoce text should be set on. - /// - public bool IsUnicodeText - { - get { return isUnicodeText_; } - set { isUnicodeText_ = value; } - } - - #endregion - - #region IEntryFactory Members - - /// - /// Make a new for a file. - /// - /// The name of the file to create a new entry for. - /// Returns a new based on the . - public ZipEntry MakeFileEntry(string fileName) - { - return MakeFileEntry(fileName, true); - } - - /// - /// Make a new from a name. - /// - /// The name of the file to create a new entry for. - /// If true entry detail is retrieved from the file system if the file exists. - /// Returns a new based on the . - public ZipEntry MakeFileEntry(string fileName, bool useFileSystem) - { - ZipEntry result = new ZipEntry(nameTransform_.TransformFile(fileName)); - result.IsUnicodeText = isUnicodeText_; - - int externalAttributes = 0; - bool useAttributes = (setAttributes_ != 0); - - FileInfo fi = null; - if (useFileSystem) - { - fi = new FileInfo(fileName); - } - - if ((fi != null) && fi.Exists) - { - switch (timeSetting_) - { - case TimeSetting.CreateTime: - result.DateTime = fi.CreationTime; - break; - - case TimeSetting.CreateTimeUtc: + /// + /// Basic implementation of + /// + public class ZipEntryFactory : IEntryFactory + { + #region Enumerations + /// + /// Defines the possible values to be used for the . + /// + public enum TimeSetting + { + /// + /// Use the recorded LastWriteTime value for the file. + /// + LastWriteTime, + /// + /// Use the recorded LastWriteTimeUtc value for the file + /// + LastWriteTimeUtc, + /// + /// Use the recorded CreateTime value for the file. + /// + CreateTime, + /// + /// Use the recorded CreateTimeUtc value for the file. + /// + CreateTimeUtc, + /// + /// Use the recorded LastAccessTime value for the file. + /// + LastAccessTime, + /// + /// Use the recorded LastAccessTimeUtc value for the file. + /// + LastAccessTimeUtc, + /// + /// Use a fixed value. + /// + /// The actual value used can be + /// specified via the constructor or + /// using the with the setting set + /// to which will use the when this class was constructed. + /// The property can also be used to set this value. + Fixed, + } + #endregion + + #region Constructors + /// + /// Initialise a new instance of the class. + /// + /// A default , and the LastWriteTime for files is used. + public ZipEntryFactory() + { + nameTransform_ = new ZipNameTransform(); + } + + /// + /// Initialise a new instance of using the specified + /// + /// The time setting to use when creating Zip entries. + public ZipEntryFactory(TimeSetting timeSetting) + { + timeSetting_ = timeSetting; + nameTransform_ = new ZipNameTransform(); + } + + /// + /// Initialise a new instance of using the specified + /// + /// The time to set all values to. + public ZipEntryFactory(DateTime time) + { + timeSetting_ = TimeSetting.Fixed; + FixedDateTime = time; + nameTransform_ = new ZipNameTransform(); + } + + #endregion + + #region Properties + /// + /// Get / set the to be used when creating new values. + /// + /// + /// Setting this property to null will cause a default name transform to be used. + /// + public INameTransform NameTransform + { + get { return nameTransform_; } + set + { + if (value == null) { + nameTransform_ = new ZipNameTransform(); + } + else { + nameTransform_ = value; + } + } + } + + /// + /// Get / set the in use. + /// + public TimeSetting Setting + { + get { return timeSetting_; } + set { timeSetting_ = value; } + } + + /// + /// Get / set the value to use when is set to + /// + public DateTime FixedDateTime + { + get { return fixedDateTime_; } + set + { + if (value.Year < 1970) { + throw new ArgumentException("Value is too old to be valid", "value"); + } + fixedDateTime_ = value; + } + } + + /// + /// A bitmask defining the attributes to be retrieved from the actual file. + /// + /// The default is to get all possible attributes from the actual file. + public int GetAttributes + { + get { return getAttributes_; } + set { getAttributes_ = value; } + } + + /// + /// A bitmask defining which attributes are to be set on. + /// + /// By default no attributes are set on. + public int SetAttributes + { + get { return setAttributes_; } + set { setAttributes_ = value; } + } + + /// + /// Get set a value indicating wether unidoce text should be set on. + /// + public bool IsUnicodeText + { + get { return isUnicodeText_; } + set { isUnicodeText_ = value; } + } + + #endregion + + #region IEntryFactory Members + + /// + /// Make a new for a file. + /// + /// The name of the file to create a new entry for. + /// Returns a new based on the . + public ZipEntry MakeFileEntry(string fileName) + { + return MakeFileEntry(fileName, true); + } + + /// + /// Make a new from a name. + /// + /// The name of the file to create a new entry for. + /// If true entry detail is retrieved from the file system if the file exists. + /// Returns a new based on the . + public ZipEntry MakeFileEntry(string fileName, bool useFileSystem) + { + ZipEntry result = new ZipEntry(nameTransform_.TransformFile(fileName)); + result.IsUnicodeText = isUnicodeText_; + + int externalAttributes = 0; + bool useAttributes = (setAttributes_ != 0); + + FileInfo fi = null; + if (useFileSystem) + { + fi = new FileInfo(fileName); + } + + if ((fi != null) && fi.Exists) + { + switch (timeSetting_) + { + case TimeSetting.CreateTime: + result.DateTime = fi.CreationTime; + break; + + case TimeSetting.CreateTimeUtc: #if NETCF_1_0 || NETCF_2_0 - result.DateTime = fi.CreationTime.ToUniversalTime(); + result.DateTime = fi.CreationTime.ToUniversalTime(); #else - result.DateTime = fi.CreationTimeUtc; + result.DateTime = fi.CreationTimeUtc; #endif - break; + break; - case TimeSetting.LastAccessTime: - result.DateTime = fi.LastAccessTime; - break; + case TimeSetting.LastAccessTime: + result.DateTime = fi.LastAccessTime; + break; - case TimeSetting.LastAccessTimeUtc: + case TimeSetting.LastAccessTimeUtc: #if NETCF_1_0 || NETCF_2_0 - result.DateTime = fi.LastAccessTime.ToUniversalTime(); + result.DateTime = fi.LastAccessTime.ToUniversalTime(); #else - result.DateTime = fi.LastAccessTimeUtc; + result.DateTime = fi.LastAccessTimeUtc; #endif - break; + break; - case TimeSetting.LastWriteTime: - result.DateTime = fi.LastWriteTime; - break; + case TimeSetting.LastWriteTime: + result.DateTime = fi.LastWriteTime; + break; - case TimeSetting.LastWriteTimeUtc: + case TimeSetting.LastWriteTimeUtc: #if NETCF_1_0 || NETCF_2_0 - result.DateTime = fi.LastWriteTime.ToUniversalTime(); + result.DateTime = fi.LastWriteTime.ToUniversalTime(); #else - result.DateTime = fi.LastWriteTimeUtc; + result.DateTime = fi.LastWriteTimeUtc; #endif - break; - - case TimeSetting.Fixed: - result.DateTime = fixedDateTime_; - break; - - default: - throw new ZipException("Unhandled time setting in MakeFileEntry"); - } - - result.Size = fi.Length; - - useAttributes = true; - externalAttributes = ((int)fi.Attributes & getAttributes_); - } - else - { - if (timeSetting_ == TimeSetting.Fixed) - { - result.DateTime = fixedDateTime_; - } - } - - if (useAttributes) - { - externalAttributes |= setAttributes_; - result.ExternalFileAttributes = externalAttributes; - } - - return result; - } - - /// - /// Make a new for a directory. - /// - /// The raw untransformed name for the new directory - /// Returns a new representing a directory. - public ZipEntry MakeDirectoryEntry(string directoryName) - { - return MakeDirectoryEntry(directoryName, true); - } - - /// - /// Make a new for a directory. - /// - /// The raw untransformed name for the new directory - /// If true entry detail is retrieved from the file system if the file exists. - /// Returns a new representing a directory. - public ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem) - { - - ZipEntry result = new ZipEntry(nameTransform_.TransformDirectory(directoryName)); + break; + + case TimeSetting.Fixed: + result.DateTime = fixedDateTime_; + break; + + default: + throw new ZipException("Unhandled time setting in MakeFileEntry"); + } + + result.Size = fi.Length; + + useAttributes = true; + externalAttributes = ((int)fi.Attributes & getAttributes_); + } + else + { + if (timeSetting_ == TimeSetting.Fixed) + { + result.DateTime = fixedDateTime_; + } + } + + if (useAttributes) + { + externalAttributes |= setAttributes_; + result.ExternalFileAttributes = externalAttributes; + } + + return result; + } + + /// + /// Make a new for a directory. + /// + /// The raw untransformed name for the new directory + /// Returns a new representing a directory. + public ZipEntry MakeDirectoryEntry(string directoryName) + { + return MakeDirectoryEntry(directoryName, true); + } + + /// + /// Make a new for a directory. + /// + /// The raw untransformed name for the new directory + /// If true entry detail is retrieved from the file system if the file exists. + /// Returns a new representing a directory. + public ZipEntry MakeDirectoryEntry(string directoryName, bool useFileSystem) + { + + ZipEntry result = new ZipEntry(nameTransform_.TransformDirectory(directoryName)); result.IsUnicodeText = isUnicodeText_; result.Size = 0; - - int externalAttributes = 0; + + int externalAttributes = 0; - DirectoryInfo di = null; + DirectoryInfo di = null; - if (useFileSystem) - { - di = new DirectoryInfo(directoryName); - } + if (useFileSystem) + { + di = new DirectoryInfo(directoryName); + } - if ((di != null) && di.Exists) - { - switch (timeSetting_) - { - case TimeSetting.CreateTime: - result.DateTime = di.CreationTime; - break; + if ((di != null) && di.Exists) + { + switch (timeSetting_) + { + case TimeSetting.CreateTime: + result.DateTime = di.CreationTime; + break; - case TimeSetting.CreateTimeUtc: + case TimeSetting.CreateTimeUtc: #if NETCF_1_0 || NETCF_2_0 - result.DateTime = di.CreationTime.ToUniversalTime(); + result.DateTime = di.CreationTime.ToUniversalTime(); #else - result.DateTime = di.CreationTimeUtc; + result.DateTime = di.CreationTimeUtc; #endif - break; + break; - case TimeSetting.LastAccessTime: - result.DateTime = di.LastAccessTime; - break; + case TimeSetting.LastAccessTime: + result.DateTime = di.LastAccessTime; + break; - case TimeSetting.LastAccessTimeUtc: + case TimeSetting.LastAccessTimeUtc: #if NETCF_1_0 || NETCF_2_0 - result.DateTime = di.LastAccessTime.ToUniversalTime(); + result.DateTime = di.LastAccessTime.ToUniversalTime(); #else - result.DateTime = di.LastAccessTimeUtc; + result.DateTime = di.LastAccessTimeUtc; #endif - break; + break; - case TimeSetting.LastWriteTime: - result.DateTime = di.LastWriteTime; - break; + case TimeSetting.LastWriteTime: + result.DateTime = di.LastWriteTime; + break; - case TimeSetting.LastWriteTimeUtc: + case TimeSetting.LastWriteTimeUtc: #if NETCF_1_0 || NETCF_2_0 - result.DateTime = di.LastWriteTime.ToUniversalTime(); + result.DateTime = di.LastWriteTime.ToUniversalTime(); #else - result.DateTime = di.LastWriteTimeUtc; + result.DateTime = di.LastWriteTimeUtc; #endif - break; - - case TimeSetting.Fixed: - result.DateTime = fixedDateTime_; - break; - - default: - throw new ZipException("Unhandled time setting in MakeDirectoryEntry"); - } - - externalAttributes = ((int)di.Attributes & getAttributes_); - } - else - { - if (timeSetting_ == TimeSetting.Fixed) - { - result.DateTime = fixedDateTime_; - } - } - - // Always set directory attribute on. - externalAttributes |= (setAttributes_ | 16); - result.ExternalFileAttributes = externalAttributes; - - return result; - } - - #endregion - - #region Instance Fields - INameTransform nameTransform_; - DateTime fixedDateTime_ = DateTime.Now; - TimeSetting timeSetting_; - bool isUnicodeText_; - - int getAttributes_ = -1; - int setAttributes_; - #endregion - } + break; + + case TimeSetting.Fixed: + result.DateTime = fixedDateTime_; + break; + + default: + throw new ZipException("Unhandled time setting in MakeDirectoryEntry"); + } + + externalAttributes = ((int)di.Attributes & getAttributes_); + } + else + { + if (timeSetting_ == TimeSetting.Fixed) + { + result.DateTime = fixedDateTime_; + } + } + + // Always set directory attribute on. + externalAttributes |= (setAttributes_ | 16); + result.ExternalFileAttributes = externalAttributes; + + return result; + } + + #endregion + + #region Instance Fields + INameTransform nameTransform_; + DateTime fixedDateTime_ = DateTime.Now; + TimeSetting timeSetting_; + bool isUnicodeText_; + + int getAttributes_ = -1; + int setAttributes_; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipException.cs b/External/Tools/AppMan/ZipLib/Zip/ZipException.cs index 1cf4f16220..0965d068d6 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipException.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipException.cs @@ -44,51 +44,51 @@ namespace ICSharpCode.SharpZipLib.Zip { - - /// - /// Represents exception conditions specific to Zip archive handling - /// + + /// + /// Represents exception conditions specific to Zip archive handling + /// #if !NETCF_1_0 && !NETCF_2_0 - [Serializable] + [Serializable] #endif - public class ZipException : SharpZipBaseException - { + public class ZipException : SharpZipBaseException + { #if !NETCF_1_0 && !NETCF_2_0 - /// - /// Deserialization constructor - /// - /// for this constructor - /// for this constructor - protected ZipException(SerializationInfo info, StreamingContext context ) - : base( info, context ) - { - } + /// + /// Deserialization constructor + /// + /// for this constructor + /// for this constructor + protected ZipException(SerializationInfo info, StreamingContext context ) + : base( info, context ) + { + } #endif - /// - /// Initializes a new instance of the ZipException class. - /// - public ZipException() - { - } - - /// - /// Initializes a new instance of the ZipException class with a specified error message. - /// - /// The error message that explains the reason for the exception. - public ZipException(string message) - : base(message) - { - } + /// + /// Initializes a new instance of the ZipException class. + /// + public ZipException() + { + } + + /// + /// Initializes a new instance of the ZipException class with a specified error message. + /// + /// The error message that explains the reason for the exception. + public ZipException(string message) + : base(message) + { + } - /// - /// Initialise a new instance of ZipException. - /// - /// A message describing the error. - /// The exception that is the cause of the current exception. - public ZipException(string message, Exception exception) - : base(message, exception) - { - } - } + /// + /// Initialise a new instance of ZipException. + /// + /// A message describing the error. + /// The exception that is the cause of the current exception. + public ZipException(string message, Exception exception) + : base(message, exception) + { + } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipExtraData.cs b/External/Tools/AppMan/ZipLib/Zip/ZipExtraData.cs index aaeb0a6e16..2966a90891 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipExtraData.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipExtraData.cs @@ -39,949 +39,949 @@ namespace ICSharpCode.SharpZipLib.Zip { - // TODO: Sort out wether tagged data is useful and what a good implementation might look like. - // Its just a sketch of an idea at the moment. - - /// - /// ExtraData tagged value interface. - /// - public interface ITaggedData - { - /// - /// Get the ID for this tagged data value. - /// - short TagID { get; } - - /// - /// Set the contents of this instance from the data passed. - /// - /// The data to extract contents from. - /// The offset to begin extracting data from. - /// The number of bytes to extract. - void SetData(byte[] data, int offset, int count); - - /// - /// Get the data representing this instance. - /// - /// Returns the data for this instance. - byte[] GetData(); - } - - /// - /// A raw binary tagged value - /// - public class RawTaggedData : ITaggedData - { - /// - /// Initialise a new instance. - /// - /// The tag ID. - public RawTaggedData(short tag) - { - _tag = tag; - } - - #region ITaggedData Members - - /// - /// Get the ID for this tagged data value. - /// - public short TagID - { - get { return _tag; } - set { _tag = value; } - } - - /// - /// Set the data from the raw values provided. - /// - /// The raw data to extract values from. - /// The index to start extracting values from. - /// The number of bytes available. - public void SetData(byte[] data, int offset, int count) - { - if( data==null ) - { - throw new ArgumentNullException("data"); - } - - _data=new byte[count]; - Array.Copy(data, offset, _data, 0, count); - } - - /// - /// Get the binary data representing this instance. - /// - /// The raw binary data representing this instance. - public byte[] GetData() - { - return _data; - } - - #endregion - - /// - /// Get /set the binary data representing this instance. - /// - /// The raw binary data representing this instance. - public byte[] Data - { - get { return _data; } - set { _data=value; } - } - - #region Instance Fields - /// - /// The tag ID for this instance. - /// - short _tag; - - byte[] _data; - #endregion - } - - /// - /// Class representing extended unix date time values. - /// - public class ExtendedUnixData : ITaggedData - { - /// - /// Flags indicate which values are included in this instance. - /// - [Flags] - public enum Flags : byte - { - /// - /// The modification time is included - /// - ModificationTime = 0x01, - - /// - /// The access time is included - /// - AccessTime = 0x02, - - /// - /// The create time is included. - /// - CreateTime = 0x04, - } - - #region ITaggedData Members - - /// - /// Get the ID - /// - public short TagID - { - get { return 0x5455; } - } - - /// - /// Set the data from the raw values provided. - /// - /// The raw data to extract values from. - /// The index to start extracting values from. - /// The number of bytes available. - public void SetData(byte[] data, int index, int count) - { - using (MemoryStream ms = new MemoryStream(data, index, count, false)) - using (ZipHelperStream helperStream = new ZipHelperStream(ms)) - { - // bit 0 if set, modification time is present - // bit 1 if set, access time is present - // bit 2 if set, creation time is present - - _flags = (Flags)helperStream.ReadByte(); - if (((_flags & Flags.ModificationTime) != 0) && (count >= 5)) - { - int iTime = helperStream.ReadLEInt(); - - _modificationTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + - new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); - } - - if ((_flags & Flags.AccessTime) != 0) - { - int iTime = helperStream.ReadLEInt(); - - _lastAccessTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + - new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); - } - - if ((_flags & Flags.CreateTime) != 0) - { - int iTime = helperStream.ReadLEInt(); - - _createTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + - new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); - } - } - } - - /// - /// Get the binary data representing this instance. - /// - /// The raw binary data representing this instance. - public byte[] GetData() - { - using (MemoryStream ms = new MemoryStream()) - using (ZipHelperStream helperStream = new ZipHelperStream(ms)) - { - helperStream.IsStreamOwner = false; - helperStream.WriteByte((byte)_flags); // Flags - if ( (_flags & Flags.ModificationTime) != 0) { - TimeSpan span = _modificationTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); - int seconds = (int)span.TotalSeconds; - helperStream.WriteLEInt(seconds); - } - if ( (_flags & Flags.AccessTime) != 0) { - TimeSpan span = _lastAccessTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); - int seconds = (int)span.TotalSeconds; - helperStream.WriteLEInt(seconds); - } - if ( (_flags & Flags.CreateTime) != 0) { - TimeSpan span = _createTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); - int seconds = (int)span.TotalSeconds; - helperStream.WriteLEInt(seconds); - } - return ms.ToArray(); - } - } - - #endregion - - /// - /// Test a value to see if is valid and can be represented here. - /// - /// The value to test. - /// Returns true if the value is valid and can be represented; false if not. - /// The standard Unix time is a signed integer data type, directly encoding the Unix time number, - /// which is the number of seconds since 1970-01-01. - /// Being 32 bits means the values here cover a range of about 136 years. - /// The minimum representable time is 1901-12-13 20:45:52, - /// and the maximum representable time is 2038-01-19 03:14:07. - /// - public static bool IsValidValue(DateTime value) - { - return (( value >= new DateTime(1901, 12, 13, 20, 45, 52)) || - ( value <= new DateTime(2038, 1, 19, 03, 14, 07) )); - } - - /// - /// Get /set the Modification Time - /// - /// - /// - public DateTime ModificationTime - { - get { return _modificationTime; } - set - { - if ( !IsValidValue(value) ) { - throw new ArgumentOutOfRangeException("value"); - } - - _flags |= Flags.ModificationTime; - _modificationTime=value; - } - } - - /// - /// Get / set the Access Time - /// - /// - /// - public DateTime AccessTime - { - get { return _lastAccessTime; } - set { - if ( !IsValidValue(value) ) { - throw new ArgumentOutOfRangeException("value"); - } - - _flags |= Flags.AccessTime; - _lastAccessTime=value; - } - } - - /// - /// Get / Set the Create Time - /// - /// - /// - public DateTime CreateTime - { - get { return _createTime; } - set { - if ( !IsValidValue(value) ) { - throw new ArgumentOutOfRangeException("value"); - } - - _flags |= Flags.CreateTime; - _createTime=value; - } - } - - /// - /// Get/set the values to include. - /// - Flags Include - { - get { return _flags; } - set { _flags = value; } - } - - #region Instance Fields - Flags _flags; - DateTime _modificationTime = new DateTime(1970,1,1); - DateTime _lastAccessTime = new DateTime(1970, 1, 1); - DateTime _createTime = new DateTime(1970, 1, 1); - #endregion - } - - /// - /// Class handling NT date time values. - /// - public class NTTaggedData : ITaggedData - { - /// - /// Get the ID for this tagged data value. - /// - public short TagID - { - get { return 10; } - } - - /// - /// Set the data from the raw values provided. - /// - /// The raw data to extract values from. - /// The index to start extracting values from. - /// The number of bytes available. - public void SetData(byte[] data, int index, int count) - { - using (MemoryStream ms = new MemoryStream(data, index, count, false)) - using (ZipHelperStream helperStream = new ZipHelperStream(ms)) - { - helperStream.ReadLEInt(); // Reserved - while (helperStream.Position < helperStream.Length) - { - int ntfsTag = helperStream.ReadLEShort(); - int ntfsLength = helperStream.ReadLEShort(); - if (ntfsTag == 1) - { - if (ntfsLength >= 24) - { - long lastModificationTicks = helperStream.ReadLELong(); - _lastModificationTime = DateTime.FromFileTime(lastModificationTicks); - - long lastAccessTicks = helperStream.ReadLELong(); - _lastAccessTime = DateTime.FromFileTime(lastAccessTicks); - - long createTimeTicks = helperStream.ReadLELong(); - _createTime = DateTime.FromFileTime(createTimeTicks); - } - break; - } - else - { - // An unknown NTFS tag so simply skip it. - helperStream.Seek(ntfsLength, SeekOrigin.Current); - } - } - } - } - - /// - /// Get the binary data representing this instance. - /// - /// The raw binary data representing this instance. - public byte[] GetData() - { - using (MemoryStream ms = new MemoryStream()) - using (ZipHelperStream helperStream = new ZipHelperStream(ms)) - { - helperStream.IsStreamOwner = false; - helperStream.WriteLEInt(0); // Reserved - helperStream.WriteLEShort(1); // Tag - helperStream.WriteLEShort(24); // Length = 3 x 8. - helperStream.WriteLELong(_lastModificationTime.ToFileTime()); - helperStream.WriteLELong(_lastAccessTime.ToFileTime()); - helperStream.WriteLELong(_createTime.ToFileTime()); - return ms.ToArray(); - } - } - - /// - /// Test a valuie to see if is valid and can be represented here. - /// - /// The value to test. - /// Returns true if the value is valid and can be represented; false if not. - /// - /// NTFS filetimes are 64-bit unsigned integers, stored in Intel - /// (least significant byte first) byte order. They determine the - /// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch", - /// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit - /// - public static bool IsValidValue(DateTime value) - { - bool result = true; - try - { - value.ToFileTimeUtc(); - } - catch - { - result = false; - } - return result; - } - - /// - /// Get/set the last modification time. - /// - public DateTime LastModificationTime - { - get { return _lastModificationTime; } - set { - if (! IsValidValue(value)) - { - throw new ArgumentOutOfRangeException("value"); - } - _lastModificationTime = value; - } - } - - /// - /// Get /set the create time - /// - public DateTime CreateTime - { - get { return _createTime; } - set { - if ( !IsValidValue(value)) { - throw new ArgumentOutOfRangeException("value"); - } - _createTime = value; - } - } - - /// - /// Get /set the last access time. - /// - public DateTime LastAccessTime - { - get { return _lastAccessTime; } - set { - if (!IsValidValue(value)) { - throw new ArgumentOutOfRangeException("value"); - } - _lastAccessTime = value; - } - } - - #region Instance Fields - DateTime _lastAccessTime = DateTime.FromFileTime(0); - DateTime _lastModificationTime = DateTime.FromFileTime(0); - DateTime _createTime = DateTime.FromFileTime(0); - #endregion - } - - /// - /// A factory that creates tagged data instances. - /// - interface ITaggedDataFactory - { - /// - /// Get data for a specific tag value. - /// - /// The tag ID to find. - /// The data to search. - /// The offset to begin extracting data from. - /// The number of bytes to extract. - /// The located value found, or null if not found. - ITaggedData Create(short tag, byte[] data, int offset, int count); - } - - /// - /// - /// A class to handle the extra data field for Zip entries - /// - /// - /// Extra data contains 0 or more values each prefixed by a header tag and length. - /// They contain zero or more bytes of actual data. - /// The data is held internally using a copy on write strategy. This is more efficient but - /// means that for extra data created by passing in data can have the values modified by the caller - /// in some circumstances. - /// - sealed public class ZipExtraData : IDisposable - { - #region Constructors - /// - /// Initialise a default instance. - /// - public ZipExtraData() - { - Clear(); - } - - /// - /// Initialise with known extra data. - /// - /// The extra data. - public ZipExtraData(byte[] data) - { - if ( data == null ) - { - _data = new byte[0]; - } - else - { - _data = data; - } - } - #endregion - - /// - /// Get the raw extra data value - /// - /// Returns the raw byte[] extra data this instance represents. - public byte[] GetEntryData() - { - if ( Length > ushort.MaxValue ) { - throw new ZipException("Data exceeds maximum length"); - } - - return (byte[])_data.Clone(); - } - - /// - /// Clear the stored data. - /// - public void Clear() - { - if ( (_data == null) || (_data.Length != 0) ) { - _data = new byte[0]; - } - } - - /// - /// Gets the current extra data length. - /// - public int Length - { - get { return _data.Length; } - } - - /// - /// Get a read-only for the associated tag. - /// - /// The tag to locate data for. - /// Returns a containing tag data or null if no tag was found. - public Stream GetStreamForTag(int tag) - { - Stream result = null; - if ( Find(tag) ) { - result = new MemoryStream(_data, _index, _readValueLength, false); - } - return result; - } - - /// - /// Get the tagged data for a tag. - /// - /// The tag to search for. - /// Returns a tagged value or null if none found. - private ITaggedData GetData(short tag) - { - ITaggedData result = null; - if (Find(tag)) - { - result = Create(tag, _data, _readValueStart, _readValueLength); - } - return result; - } - - static ITaggedData Create(short tag, byte[] data, int offset, int count) - { - ITaggedData result = null; - switch ( tag ) - { - case 0x000A: - result = new NTTaggedData(); - break; - case 0x5455: - result = new ExtendedUnixData(); - break; - default: - result = new RawTaggedData(tag); - break; - } - result.SetData(data, offset, count); - return result; - } - - /// - /// Get the length of the last value found by - /// - /// This is only valid if has previously returned true. - public int ValueLength - { - get { return _readValueLength; } - } - - /// - /// Get the index for the current read value. - /// - /// This is only valid if has previously returned true. - /// Initially the result will be the index of the first byte of actual data. The value is updated after calls to - /// , and . - public int CurrentReadIndex - { - get { return _index; } - } - - /// - /// Get the number of bytes remaining to be read for the current value; - /// - public int UnreadCount - { - get - { - if ((_readValueStart > _data.Length) || - (_readValueStart < 4) ) { - throw new ZipException("Find must be called before calling a Read method"); - } - - return _readValueStart + _readValueLength - _index; - } - } - - /// - /// Find an extra data value - /// - /// The identifier for the value to find. - /// Returns true if the value was found; false otherwise. - public bool Find(int headerID) - { - _readValueStart = _data.Length; - _readValueLength = 0; - _index = 0; - - int localLength = _readValueStart; - int localTag = headerID - 1; - - // Trailing bytes that cant make up an entry (as there arent enough - // bytes for a tag and length) are ignored! - while ( (localTag != headerID) && (_index < _data.Length - 3) ) { - localTag = ReadShortInternal(); - localLength = ReadShortInternal(); - if ( localTag != headerID ) { - _index += localLength; - } - } - - bool result = (localTag == headerID) && ((_index + localLength) <= _data.Length); - - if ( result ) { - _readValueStart = _index; - _readValueLength = localLength; - } - - return result; - } - - /// - /// Add a new entry to extra data. - /// - /// The value to add. - public void AddEntry(ITaggedData taggedData) - { - if (taggedData == null) - { - throw new ArgumentNullException("taggedData"); - } - AddEntry(taggedData.TagID, taggedData.GetData()); - } - - /// - /// Add a new entry to extra data - /// - /// The ID for this entry. - /// The data to add. - /// If the ID already exists its contents are replaced. - public void AddEntry(int headerID, byte[] fieldData) - { - if ( (headerID > ushort.MaxValue) || (headerID < 0)) { - throw new ArgumentOutOfRangeException("headerID"); - } - - int addLength = (fieldData == null) ? 0 : fieldData.Length; - - if ( addLength > ushort.MaxValue ) { + // TODO: Sort out wether tagged data is useful and what a good implementation might look like. + // Its just a sketch of an idea at the moment. + + /// + /// ExtraData tagged value interface. + /// + public interface ITaggedData + { + /// + /// Get the ID for this tagged data value. + /// + short TagID { get; } + + /// + /// Set the contents of this instance from the data passed. + /// + /// The data to extract contents from. + /// The offset to begin extracting data from. + /// The number of bytes to extract. + void SetData(byte[] data, int offset, int count); + + /// + /// Get the data representing this instance. + /// + /// Returns the data for this instance. + byte[] GetData(); + } + + /// + /// A raw binary tagged value + /// + public class RawTaggedData : ITaggedData + { + /// + /// Initialise a new instance. + /// + /// The tag ID. + public RawTaggedData(short tag) + { + _tag = tag; + } + + #region ITaggedData Members + + /// + /// Get the ID for this tagged data value. + /// + public short TagID + { + get { return _tag; } + set { _tag = value; } + } + + /// + /// Set the data from the raw values provided. + /// + /// The raw data to extract values from. + /// The index to start extracting values from. + /// The number of bytes available. + public void SetData(byte[] data, int offset, int count) + { + if( data==null ) + { + throw new ArgumentNullException("data"); + } + + _data=new byte[count]; + Array.Copy(data, offset, _data, 0, count); + } + + /// + /// Get the binary data representing this instance. + /// + /// The raw binary data representing this instance. + public byte[] GetData() + { + return _data; + } + + #endregion + + /// + /// Get /set the binary data representing this instance. + /// + /// The raw binary data representing this instance. + public byte[] Data + { + get { return _data; } + set { _data=value; } + } + + #region Instance Fields + /// + /// The tag ID for this instance. + /// + short _tag; + + byte[] _data; + #endregion + } + + /// + /// Class representing extended unix date time values. + /// + public class ExtendedUnixData : ITaggedData + { + /// + /// Flags indicate which values are included in this instance. + /// + [Flags] + public enum Flags : byte + { + /// + /// The modification time is included + /// + ModificationTime = 0x01, + + /// + /// The access time is included + /// + AccessTime = 0x02, + + /// + /// The create time is included. + /// + CreateTime = 0x04, + } + + #region ITaggedData Members + + /// + /// Get the ID + /// + public short TagID + { + get { return 0x5455; } + } + + /// + /// Set the data from the raw values provided. + /// + /// The raw data to extract values from. + /// The index to start extracting values from. + /// The number of bytes available. + public void SetData(byte[] data, int index, int count) + { + using (MemoryStream ms = new MemoryStream(data, index, count, false)) + using (ZipHelperStream helperStream = new ZipHelperStream(ms)) + { + // bit 0 if set, modification time is present + // bit 1 if set, access time is present + // bit 2 if set, creation time is present + + _flags = (Flags)helperStream.ReadByte(); + if (((_flags & Flags.ModificationTime) != 0) && (count >= 5)) + { + int iTime = helperStream.ReadLEInt(); + + _modificationTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + + new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); + } + + if ((_flags & Flags.AccessTime) != 0) + { + int iTime = helperStream.ReadLEInt(); + + _lastAccessTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + + new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); + } + + if ((_flags & Flags.CreateTime) != 0) + { + int iTime = helperStream.ReadLEInt(); + + _createTime = (new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime() + + new TimeSpan(0, 0, 0, iTime, 0)).ToLocalTime(); + } + } + } + + /// + /// Get the binary data representing this instance. + /// + /// The raw binary data representing this instance. + public byte[] GetData() + { + using (MemoryStream ms = new MemoryStream()) + using (ZipHelperStream helperStream = new ZipHelperStream(ms)) + { + helperStream.IsStreamOwner = false; + helperStream.WriteByte((byte)_flags); // Flags + if ( (_flags & Flags.ModificationTime) != 0) { + TimeSpan span = _modificationTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); + int seconds = (int)span.TotalSeconds; + helperStream.WriteLEInt(seconds); + } + if ( (_flags & Flags.AccessTime) != 0) { + TimeSpan span = _lastAccessTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); + int seconds = (int)span.TotalSeconds; + helperStream.WriteLEInt(seconds); + } + if ( (_flags & Flags.CreateTime) != 0) { + TimeSpan span = _createTime.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0).ToUniversalTime(); + int seconds = (int)span.TotalSeconds; + helperStream.WriteLEInt(seconds); + } + return ms.ToArray(); + } + } + + #endregion + + /// + /// Test a value to see if is valid and can be represented here. + /// + /// The value to test. + /// Returns true if the value is valid and can be represented; false if not. + /// The standard Unix time is a signed integer data type, directly encoding the Unix time number, + /// which is the number of seconds since 1970-01-01. + /// Being 32 bits means the values here cover a range of about 136 years. + /// The minimum representable time is 1901-12-13 20:45:52, + /// and the maximum representable time is 2038-01-19 03:14:07. + /// + public static bool IsValidValue(DateTime value) + { + return (( value >= new DateTime(1901, 12, 13, 20, 45, 52)) || + ( value <= new DateTime(2038, 1, 19, 03, 14, 07) )); + } + + /// + /// Get /set the Modification Time + /// + /// + /// + public DateTime ModificationTime + { + get { return _modificationTime; } + set + { + if ( !IsValidValue(value) ) { + throw new ArgumentOutOfRangeException("value"); + } + + _flags |= Flags.ModificationTime; + _modificationTime=value; + } + } + + /// + /// Get / set the Access Time + /// + /// + /// + public DateTime AccessTime + { + get { return _lastAccessTime; } + set { + if ( !IsValidValue(value) ) { + throw new ArgumentOutOfRangeException("value"); + } + + _flags |= Flags.AccessTime; + _lastAccessTime=value; + } + } + + /// + /// Get / Set the Create Time + /// + /// + /// + public DateTime CreateTime + { + get { return _createTime; } + set { + if ( !IsValidValue(value) ) { + throw new ArgumentOutOfRangeException("value"); + } + + _flags |= Flags.CreateTime; + _createTime=value; + } + } + + /// + /// Get/set the values to include. + /// + Flags Include + { + get { return _flags; } + set { _flags = value; } + } + + #region Instance Fields + Flags _flags; + DateTime _modificationTime = new DateTime(1970,1,1); + DateTime _lastAccessTime = new DateTime(1970, 1, 1); + DateTime _createTime = new DateTime(1970, 1, 1); + #endregion + } + + /// + /// Class handling NT date time values. + /// + public class NTTaggedData : ITaggedData + { + /// + /// Get the ID for this tagged data value. + /// + public short TagID + { + get { return 10; } + } + + /// + /// Set the data from the raw values provided. + /// + /// The raw data to extract values from. + /// The index to start extracting values from. + /// The number of bytes available. + public void SetData(byte[] data, int index, int count) + { + using (MemoryStream ms = new MemoryStream(data, index, count, false)) + using (ZipHelperStream helperStream = new ZipHelperStream(ms)) + { + helperStream.ReadLEInt(); // Reserved + while (helperStream.Position < helperStream.Length) + { + int ntfsTag = helperStream.ReadLEShort(); + int ntfsLength = helperStream.ReadLEShort(); + if (ntfsTag == 1) + { + if (ntfsLength >= 24) + { + long lastModificationTicks = helperStream.ReadLELong(); + _lastModificationTime = DateTime.FromFileTime(lastModificationTicks); + + long lastAccessTicks = helperStream.ReadLELong(); + _lastAccessTime = DateTime.FromFileTime(lastAccessTicks); + + long createTimeTicks = helperStream.ReadLELong(); + _createTime = DateTime.FromFileTime(createTimeTicks); + } + break; + } + else + { + // An unknown NTFS tag so simply skip it. + helperStream.Seek(ntfsLength, SeekOrigin.Current); + } + } + } + } + + /// + /// Get the binary data representing this instance. + /// + /// The raw binary data representing this instance. + public byte[] GetData() + { + using (MemoryStream ms = new MemoryStream()) + using (ZipHelperStream helperStream = new ZipHelperStream(ms)) + { + helperStream.IsStreamOwner = false; + helperStream.WriteLEInt(0); // Reserved + helperStream.WriteLEShort(1); // Tag + helperStream.WriteLEShort(24); // Length = 3 x 8. + helperStream.WriteLELong(_lastModificationTime.ToFileTime()); + helperStream.WriteLELong(_lastAccessTime.ToFileTime()); + helperStream.WriteLELong(_createTime.ToFileTime()); + return ms.ToArray(); + } + } + + /// + /// Test a valuie to see if is valid and can be represented here. + /// + /// The value to test. + /// Returns true if the value is valid and can be represented; false if not. + /// + /// NTFS filetimes are 64-bit unsigned integers, stored in Intel + /// (least significant byte first) byte order. They determine the + /// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch", + /// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit + /// + public static bool IsValidValue(DateTime value) + { + bool result = true; + try + { + value.ToFileTimeUtc(); + } + catch + { + result = false; + } + return result; + } + + /// + /// Get/set the last modification time. + /// + public DateTime LastModificationTime + { + get { return _lastModificationTime; } + set { + if (! IsValidValue(value)) + { + throw new ArgumentOutOfRangeException("value"); + } + _lastModificationTime = value; + } + } + + /// + /// Get /set the create time + /// + public DateTime CreateTime + { + get { return _createTime; } + set { + if ( !IsValidValue(value)) { + throw new ArgumentOutOfRangeException("value"); + } + _createTime = value; + } + } + + /// + /// Get /set the last access time. + /// + public DateTime LastAccessTime + { + get { return _lastAccessTime; } + set { + if (!IsValidValue(value)) { + throw new ArgumentOutOfRangeException("value"); + } + _lastAccessTime = value; + } + } + + #region Instance Fields + DateTime _lastAccessTime = DateTime.FromFileTime(0); + DateTime _lastModificationTime = DateTime.FromFileTime(0); + DateTime _createTime = DateTime.FromFileTime(0); + #endregion + } + + /// + /// A factory that creates tagged data instances. + /// + interface ITaggedDataFactory + { + /// + /// Get data for a specific tag value. + /// + /// The tag ID to find. + /// The data to search. + /// The offset to begin extracting data from. + /// The number of bytes to extract. + /// The located value found, or null if not found. + ITaggedData Create(short tag, byte[] data, int offset, int count); + } + + /// + /// + /// A class to handle the extra data field for Zip entries + /// + /// + /// Extra data contains 0 or more values each prefixed by a header tag and length. + /// They contain zero or more bytes of actual data. + /// The data is held internally using a copy on write strategy. This is more efficient but + /// means that for extra data created by passing in data can have the values modified by the caller + /// in some circumstances. + /// + sealed public class ZipExtraData : IDisposable + { + #region Constructors + /// + /// Initialise a default instance. + /// + public ZipExtraData() + { + Clear(); + } + + /// + /// Initialise with known extra data. + /// + /// The extra data. + public ZipExtraData(byte[] data) + { + if ( data == null ) + { + _data = new byte[0]; + } + else + { + _data = data; + } + } + #endregion + + /// + /// Get the raw extra data value + /// + /// Returns the raw byte[] extra data this instance represents. + public byte[] GetEntryData() + { + if ( Length > ushort.MaxValue ) { + throw new ZipException("Data exceeds maximum length"); + } + + return (byte[])_data.Clone(); + } + + /// + /// Clear the stored data. + /// + public void Clear() + { + if ( (_data == null) || (_data.Length != 0) ) { + _data = new byte[0]; + } + } + + /// + /// Gets the current extra data length. + /// + public int Length + { + get { return _data.Length; } + } + + /// + /// Get a read-only for the associated tag. + /// + /// The tag to locate data for. + /// Returns a containing tag data or null if no tag was found. + public Stream GetStreamForTag(int tag) + { + Stream result = null; + if ( Find(tag) ) { + result = new MemoryStream(_data, _index, _readValueLength, false); + } + return result; + } + + /// + /// Get the tagged data for a tag. + /// + /// The tag to search for. + /// Returns a tagged value or null if none found. + private ITaggedData GetData(short tag) + { + ITaggedData result = null; + if (Find(tag)) + { + result = Create(tag, _data, _readValueStart, _readValueLength); + } + return result; + } + + static ITaggedData Create(short tag, byte[] data, int offset, int count) + { + ITaggedData result = null; + switch ( tag ) + { + case 0x000A: + result = new NTTaggedData(); + break; + case 0x5455: + result = new ExtendedUnixData(); + break; + default: + result = new RawTaggedData(tag); + break; + } + result.SetData(data, offset, count); + return result; + } + + /// + /// Get the length of the last value found by + /// + /// This is only valid if has previously returned true. + public int ValueLength + { + get { return _readValueLength; } + } + + /// + /// Get the index for the current read value. + /// + /// This is only valid if has previously returned true. + /// Initially the result will be the index of the first byte of actual data. The value is updated after calls to + /// , and . + public int CurrentReadIndex + { + get { return _index; } + } + + /// + /// Get the number of bytes remaining to be read for the current value; + /// + public int UnreadCount + { + get + { + if ((_readValueStart > _data.Length) || + (_readValueStart < 4) ) { + throw new ZipException("Find must be called before calling a Read method"); + } + + return _readValueStart + _readValueLength - _index; + } + } + + /// + /// Find an extra data value + /// + /// The identifier for the value to find. + /// Returns true if the value was found; false otherwise. + public bool Find(int headerID) + { + _readValueStart = _data.Length; + _readValueLength = 0; + _index = 0; + + int localLength = _readValueStart; + int localTag = headerID - 1; + + // Trailing bytes that cant make up an entry (as there arent enough + // bytes for a tag and length) are ignored! + while ( (localTag != headerID) && (_index < _data.Length - 3) ) { + localTag = ReadShortInternal(); + localLength = ReadShortInternal(); + if ( localTag != headerID ) { + _index += localLength; + } + } + + bool result = (localTag == headerID) && ((_index + localLength) <= _data.Length); + + if ( result ) { + _readValueStart = _index; + _readValueLength = localLength; + } + + return result; + } + + /// + /// Add a new entry to extra data. + /// + /// The value to add. + public void AddEntry(ITaggedData taggedData) + { + if (taggedData == null) + { + throw new ArgumentNullException("taggedData"); + } + AddEntry(taggedData.TagID, taggedData.GetData()); + } + + /// + /// Add a new entry to extra data + /// + /// The ID for this entry. + /// The data to add. + /// If the ID already exists its contents are replaced. + public void AddEntry(int headerID, byte[] fieldData) + { + if ( (headerID > ushort.MaxValue) || (headerID < 0)) { + throw new ArgumentOutOfRangeException("headerID"); + } + + int addLength = (fieldData == null) ? 0 : fieldData.Length; + + if ( addLength > ushort.MaxValue ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("fieldData"); + throw new ArgumentOutOfRangeException("fieldData"); #else - throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length"); + throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length"); #endif - } - - // Test for new length before adjusting data. - int newLength = _data.Length + addLength + 4; - - if ( Find(headerID) ) - { - newLength -= (ValueLength + 4); - } - - if ( newLength > ushort.MaxValue ) { - throw new ZipException("Data exceeds maximum length"); - } - - Delete(headerID); - - byte[] newData = new byte[newLength]; - _data.CopyTo(newData, 0); - int index = _data.Length; - _data = newData; - SetShort(ref index, headerID); - SetShort(ref index, addLength); - if ( fieldData != null ) { - fieldData.CopyTo(newData, index); - } - } - - /// - /// Start adding a new entry. - /// - /// Add data using , , , or . - /// The new entry is completed and actually added by calling - /// - public void StartNewEntry() - { - _newEntry = new MemoryStream(); - } - - /// - /// Add entry data added since using the ID passed. - /// - /// The identifier to use for this entry. - public void AddNewEntry(int headerID) - { - byte[] newData = _newEntry.ToArray(); - _newEntry = null; - AddEntry(headerID, newData); - } - - /// - /// Add a byte of data to the pending new entry. - /// - /// The byte to add. - /// - public void AddData(byte data) - { - _newEntry.WriteByte(data); - } - - /// - /// Add data to a pending new entry. - /// - /// The data to add. - /// - public void AddData(byte[] data) - { - if ( data == null ) { - throw new ArgumentNullException("data"); - } - - _newEntry.Write(data, 0, data.Length); - } - - /// - /// Add a short value in little endian order to the pending new entry. - /// - /// The data to add. - /// - public void AddLeShort(int toAdd) - { - unchecked { - _newEntry.WriteByte(( byte )toAdd); - _newEntry.WriteByte(( byte )(toAdd >> 8)); - } - } - - /// - /// Add an integer value in little endian order to the pending new entry. - /// - /// The data to add. - /// - public void AddLeInt(int toAdd) - { - unchecked { - AddLeShort(( short )toAdd); - AddLeShort(( short )(toAdd >> 16)); - } - } - - /// - /// Add a long value in little endian order to the pending new entry. - /// - /// The data to add. - /// - public void AddLeLong(long toAdd) - { - unchecked { - AddLeInt(( int )(toAdd & 0xffffffff)); - AddLeInt(( int )(toAdd >> 32)); - } - } - - /// - /// Delete an extra data field. - /// - /// The identifier of the field to delete. - /// Returns true if the field was found and deleted. - public bool Delete(int headerID) - { - bool result = false; - - if ( Find(headerID) ) { - result = true; - int trueStart = _readValueStart - 4; - - byte[] newData = new byte[_data.Length - (ValueLength + 4)]; - Array.Copy(_data, 0, newData, 0, trueStart); - - int trueEnd = trueStart + ValueLength + 4; - Array.Copy(_data, trueEnd, newData, trueStart, _data.Length - trueEnd); - _data = newData; - } - return result; - } - - #region Reading Support - /// - /// Read a long in little endian form from the last found data value - /// - /// Returns the long value read. - public long ReadLong() - { - ReadCheck(8); - return (ReadInt() & 0xffffffff) | ((( long )ReadInt()) << 32); - } - - /// - /// Read an integer in little endian form from the last found data value. - /// - /// Returns the integer read. - public int ReadInt() - { - ReadCheck(4); - - int result = _data[_index] + (_data[_index + 1] << 8) + - (_data[_index + 2] << 16) + (_data[_index + 3] << 24); - _index += 4; - return result; - } - - /// - /// Read a short value in little endian form from the last found data value. - /// - /// Returns the short value read. - public int ReadShort() - { - ReadCheck(2); - int result = _data[_index] + (_data[_index + 1] << 8); - _index += 2; - return result; - } - - /// - /// Read a byte from an extra data - /// - /// The byte value read or -1 if the end of data has been reached. - public int ReadByte() - { - int result = -1; - if ( (_index < _data.Length) && (_readValueStart + _readValueLength > _index) ) { - result = _data[_index]; - _index += 1; - } - return result; - } - - /// - /// Skip data during reading. - /// - /// The number of bytes to skip. - public void Skip(int amount) - { - ReadCheck(amount); - _index += amount; - } - - void ReadCheck(int length) - { - if ((_readValueStart > _data.Length) || - (_readValueStart < 4) ) { - throw new ZipException("Find must be called before calling a Read method"); - } - - if (_index > _readValueStart + _readValueLength - length ) { - throw new ZipException("End of extra data"); - } + } + + // Test for new length before adjusting data. + int newLength = _data.Length + addLength + 4; + + if ( Find(headerID) ) + { + newLength -= (ValueLength + 4); + } + + if ( newLength > ushort.MaxValue ) { + throw new ZipException("Data exceeds maximum length"); + } + + Delete(headerID); + + byte[] newData = new byte[newLength]; + _data.CopyTo(newData, 0); + int index = _data.Length; + _data = newData; + SetShort(ref index, headerID); + SetShort(ref index, addLength); + if ( fieldData != null ) { + fieldData.CopyTo(newData, index); + } + } + + /// + /// Start adding a new entry. + /// + /// Add data using , , , or . + /// The new entry is completed and actually added by calling + /// + public void StartNewEntry() + { + _newEntry = new MemoryStream(); + } + + /// + /// Add entry data added since using the ID passed. + /// + /// The identifier to use for this entry. + public void AddNewEntry(int headerID) + { + byte[] newData = _newEntry.ToArray(); + _newEntry = null; + AddEntry(headerID, newData); + } + + /// + /// Add a byte of data to the pending new entry. + /// + /// The byte to add. + /// + public void AddData(byte data) + { + _newEntry.WriteByte(data); + } + + /// + /// Add data to a pending new entry. + /// + /// The data to add. + /// + public void AddData(byte[] data) + { + if ( data == null ) { + throw new ArgumentNullException("data"); + } + + _newEntry.Write(data, 0, data.Length); + } + + /// + /// Add a short value in little endian order to the pending new entry. + /// + /// The data to add. + /// + public void AddLeShort(int toAdd) + { + unchecked { + _newEntry.WriteByte(( byte )toAdd); + _newEntry.WriteByte(( byte )(toAdd >> 8)); + } + } + + /// + /// Add an integer value in little endian order to the pending new entry. + /// + /// The data to add. + /// + public void AddLeInt(int toAdd) + { + unchecked { + AddLeShort(( short )toAdd); + AddLeShort(( short )(toAdd >> 16)); + } + } + + /// + /// Add a long value in little endian order to the pending new entry. + /// + /// The data to add. + /// + public void AddLeLong(long toAdd) + { + unchecked { + AddLeInt(( int )(toAdd & 0xffffffff)); + AddLeInt(( int )(toAdd >> 32)); + } + } + + /// + /// Delete an extra data field. + /// + /// The identifier of the field to delete. + /// Returns true if the field was found and deleted. + public bool Delete(int headerID) + { + bool result = false; + + if ( Find(headerID) ) { + result = true; + int trueStart = _readValueStart - 4; + + byte[] newData = new byte[_data.Length - (ValueLength + 4)]; + Array.Copy(_data, 0, newData, 0, trueStart); + + int trueEnd = trueStart + ValueLength + 4; + Array.Copy(_data, trueEnd, newData, trueStart, _data.Length - trueEnd); + _data = newData; + } + return result; + } + + #region Reading Support + /// + /// Read a long in little endian form from the last found data value + /// + /// Returns the long value read. + public long ReadLong() + { + ReadCheck(8); + return (ReadInt() & 0xffffffff) | ((( long )ReadInt()) << 32); + } + + /// + /// Read an integer in little endian form from the last found data value. + /// + /// Returns the integer read. + public int ReadInt() + { + ReadCheck(4); + + int result = _data[_index] + (_data[_index + 1] << 8) + + (_data[_index + 2] << 16) + (_data[_index + 3] << 24); + _index += 4; + return result; + } + + /// + /// Read a short value in little endian form from the last found data value. + /// + /// Returns the short value read. + public int ReadShort() + { + ReadCheck(2); + int result = _data[_index] + (_data[_index + 1] << 8); + _index += 2; + return result; + } + + /// + /// Read a byte from an extra data + /// + /// The byte value read or -1 if the end of data has been reached. + public int ReadByte() + { + int result = -1; + if ( (_index < _data.Length) && (_readValueStart + _readValueLength > _index) ) { + result = _data[_index]; + _index += 1; + } + return result; + } + + /// + /// Skip data during reading. + /// + /// The number of bytes to skip. + public void Skip(int amount) + { + ReadCheck(amount); + _index += amount; + } + + void ReadCheck(int length) + { + if ((_readValueStart > _data.Length) || + (_readValueStart < 4) ) { + throw new ZipException("Find must be called before calling a Read method"); + } + + if (_index > _readValueStart + _readValueLength - length ) { + throw new ZipException("End of extra data"); + } if ( _index + length < 4 ) { throw new ZipException("Cannot read before start of tag"); } - } - - /// - /// Internal form of that reads data at any location. - /// - /// Returns the short value read. - int ReadShortInternal() - { - if ( _index > _data.Length - 2) { - throw new ZipException("End of extra data"); - } - - int result = _data[_index] + (_data[_index + 1] << 8); - _index += 2; - return result; - } - - void SetShort(ref int index, int source) - { - _data[index] = (byte)source; - _data[index + 1] = (byte)(source >> 8); - index += 2; - } - - #endregion - - #region IDisposable Members - - /// - /// Dispose of this instance. - /// - public void Dispose() - { - if ( _newEntry != null ) { - _newEntry.Close(); - } - } - - #endregion - - #region Instance Fields - int _index; - int _readValueStart; - int _readValueLength; - - MemoryStream _newEntry; - byte[] _data; - #endregion - } + } + + /// + /// Internal form of that reads data at any location. + /// + /// Returns the short value read. + int ReadShortInternal() + { + if ( _index > _data.Length - 2) { + throw new ZipException("End of extra data"); + } + + int result = _data[_index] + (_data[_index + 1] << 8); + _index += 2; + return result; + } + + void SetShort(ref int index, int source) + { + _data[index] = (byte)source; + _data[index + 1] = (byte)(source >> 8); + index += 2; + } + + #endregion + + #region IDisposable Members + + /// + /// Dispose of this instance. + /// + public void Dispose() + { + if ( _newEntry != null ) { + _newEntry.Close(); + } + } + + #endregion + + #region Instance Fields + int _index; + int _readValueStart; + int _readValueLength; + + MemoryStream _newEntry; + byte[] _data; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipFile.cs b/External/Tools/AppMan/ZipLib/Zip/ZipFile.cs index af4000b254..9e2e8f25ff 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipFile.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipFile.cs @@ -38,9 +38,9 @@ // exception statement from your version. // HISTORY -// 2009-12-22 Z-1649 Added AES support -// 2010-03-02 Z-1650 Fixed updating ODT archives in memory. Exposed exceptions in updating. -// 2010-05-25 Z-1663 Fixed exception when testing local header compressed size of -1 +// 2009-12-22 Z-1649 Added AES support +// 2010-03-02 Z-1650 Fixed updating ODT archives in memory. Exposed exceptions in updating. +// 2010-05-25 Z-1663 Fixed exception when testing local header compressed size of -1 using System; using System.Collections; @@ -60,856 +60,856 @@ namespace ICSharpCode.SharpZipLib.Zip { - #region Keys Required Event Args - /// - /// Arguments used with KeysRequiredEvent - /// - public class KeysRequiredEventArgs : EventArgs - { - #region Constructors - /// - /// Initialise a new instance of - /// - /// The name of the file for which keys are required. - public KeysRequiredEventArgs(string name) - { - fileName = name; - } - - /// - /// Initialise a new instance of - /// - /// The name of the file for which keys are required. - /// The current key value. - public KeysRequiredEventArgs(string name, byte[] keyValue) - { - fileName = name; - key = keyValue; - } - - #endregion - #region Properties - /// - /// Gets the name of the file for which keys are required. - /// - public string FileName - { - get { return fileName; } - } - - /// - /// Gets or sets the key value - /// - public byte[] Key - { - get { return key; } - set { key = value; } - } - #endregion - - #region Instance Fields - string fileName; - byte[] key; - #endregion - } - #endregion - - #region Test Definitions - /// - /// The strategy to apply to testing. - /// - public enum TestStrategy - { - /// - /// Find the first error only. - /// - FindFirstError, - /// - /// Find all possible errors. - /// - FindAllErrors, - } - - /// - /// The operation in progress reported by a during testing. - /// - /// TestArchive - public enum TestOperation - { - /// - /// Setting up testing. - /// - Initialising, - - /// - /// Testing an individual entries header - /// - EntryHeader, - - /// - /// Testing an individual entries data - /// - EntryData, - - /// - /// Testing an individual entry has completed. - /// - EntryComplete, - - /// - /// Running miscellaneous tests - /// - MiscellaneousTests, - - /// - /// Testing is complete - /// - Complete, - } - - /// - /// Status returned returned by during testing. - /// - /// TestArchive - public class TestStatus - { - #region Constructors - /// - /// Initialise a new instance of - /// - /// The this status applies to. - public TestStatus(ZipFile file) - { - file_ = file; - } - #endregion - - #region Properties - - /// - /// Get the current in progress. - /// - public TestOperation Operation - { - get { return operation_; } - } - - /// - /// Get the this status is applicable to. - /// - public ZipFile File - { - get { return file_; } - } - - /// - /// Get the current/last entry tested. - /// - public ZipEntry Entry - { - get { return entry_; } - } - - /// - /// Get the number of errors detected so far. - /// - public int ErrorCount - { - get { return errorCount_; } - } - - /// - /// Get the number of bytes tested so far for the current entry. - /// - public long BytesTested - { - get { return bytesTested_; } - } - - /// - /// Get a value indicating wether the last entry test was valid. - /// - public bool EntryValid - { - get { return entryValid_; } - } - #endregion - - #region Internal API - internal void AddError() - { - errorCount_++; - entryValid_ = false; - } - - internal void SetOperation(TestOperation operation) - { - operation_ = operation; - } - - internal void SetEntry(ZipEntry entry) - { - entry_ = entry; - entryValid_ = true; - bytesTested_ = 0; - } - - internal void SetBytesTested(long value) - { - bytesTested_ = value; - } - #endregion - - #region Instance Fields - ZipFile file_; - ZipEntry entry_; - bool entryValid_; - int errorCount_; - long bytesTested_; - TestOperation operation_; - #endregion - } - - /// - /// Delegate invoked during testing if supplied indicating current progress and status. - /// - /// If the message is non-null an error has occured. If the message is null - /// the operation as found in status has started. - public delegate void ZipTestResultHandler(TestStatus status, string message); - #endregion - - #region Update Definitions - /// - /// The possible ways of applying updates to an archive. - /// - public enum FileUpdateMode - { - /// - /// Perform all updates on temporary files ensuring that the original file is saved. - /// - Safe, - /// - /// Update the archive directly, which is faster but less safe. - /// - Direct, - } - #endregion - - #region ZipFile Class - /// - /// This class represents a Zip archive. You can ask for the contained - /// entries, or get an input stream for a file entry. The entry is - /// automatically decompressed. - /// - /// You can also update the archive adding or deleting entries. - /// - /// This class is thread safe for input: You can open input streams for arbitrary - /// entries in different threads. - ///
    - ///
    Author of the original java version : Jochen Hoenicke - ///
    - /// - /// - /// using System; - /// using System.Text; - /// using System.Collections; - /// using System.IO; - /// - /// using ICSharpCode.SharpZipLib.Zip; - /// - /// class MainClass - /// { - /// static public void Main(string[] args) - /// { - /// using (ZipFile zFile = new ZipFile(args[0])) { - /// Console.WriteLine("Listing of : " + zFile.Name); - /// Console.WriteLine(""); - /// Console.WriteLine("Raw Size Size Date Time Name"); - /// Console.WriteLine("-------- -------- -------- ------ ---------"); - /// foreach (ZipEntry e in zFile) { - /// if ( e.IsFile ) { - /// DateTime d = e.DateTime; - /// Console.WriteLine("{0, -10}{1, -10}{2} {3} {4}", e.Size, e.CompressedSize, - /// d.ToString("dd-MM-yy"), d.ToString("HH:mm"), - /// e.Name); - /// } - /// } - /// } - /// } - /// } - /// - /// - public class ZipFile : IEnumerable, IDisposable - { - #region KeyHandling - - /// - /// Delegate for handling keys/password setting during compresion/decompression. - /// - public delegate void KeysRequiredEventHandler( - object sender, - KeysRequiredEventArgs e - ); - - /// - /// Event handler for handling encryption keys. - /// - public KeysRequiredEventHandler KeysRequired; - - /// - /// Handles getting of encryption keys when required. - /// - /// The file for which encryption keys are required. - void OnKeysRequired(string fileName) - { - if (KeysRequired != null) { - KeysRequiredEventArgs krea = new KeysRequiredEventArgs(fileName, key); - KeysRequired(this, krea); - key = krea.Key; - } - } - - /// - /// Get/set the encryption key value. - /// - byte[] Key - { - get { return key; } - set { key = value; } - } - -#if !NETCF_1_0 - /// - /// Password to be used for encrypting/decrypting files. - /// - /// Set to null if no password is required. - public string Password - { - set - { - if ( (value == null) || (value.Length == 0) ) { - key = null; - } - else { - rawPassword_ = value; - key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(value)); - } - } - } + #region Keys Required Event Args + /// + /// Arguments used with KeysRequiredEvent + /// + public class KeysRequiredEventArgs : EventArgs + { + #region Constructors + /// + /// Initialise a new instance of + /// + /// The name of the file for which keys are required. + public KeysRequiredEventArgs(string name) + { + fileName = name; + } + + /// + /// Initialise a new instance of + /// + /// The name of the file for which keys are required. + /// The current key value. + public KeysRequiredEventArgs(string name, byte[] keyValue) + { + fileName = name; + key = keyValue; + } + + #endregion + #region Properties + /// + /// Gets the name of the file for which keys are required. + /// + public string FileName + { + get { return fileName; } + } + + /// + /// Gets or sets the key value + /// + public byte[] Key + { + get { return key; } + set { key = value; } + } + #endregion + + #region Instance Fields + string fileName; + byte[] key; + #endregion + } + #endregion + + #region Test Definitions + /// + /// The strategy to apply to testing. + /// + public enum TestStrategy + { + /// + /// Find the first error only. + /// + FindFirstError, + /// + /// Find all possible errors. + /// + FindAllErrors, + } + + /// + /// The operation in progress reported by a during testing. + /// + /// TestArchive + public enum TestOperation + { + /// + /// Setting up testing. + /// + Initialising, + + /// + /// Testing an individual entries header + /// + EntryHeader, + + /// + /// Testing an individual entries data + /// + EntryData, + + /// + /// Testing an individual entry has completed. + /// + EntryComplete, + + /// + /// Running miscellaneous tests + /// + MiscellaneousTests, + + /// + /// Testing is complete + /// + Complete, + } + + /// + /// Status returned returned by during testing. + /// + /// TestArchive + public class TestStatus + { + #region Constructors + /// + /// Initialise a new instance of + /// + /// The this status applies to. + public TestStatus(ZipFile file) + { + file_ = file; + } + #endregion + + #region Properties + + /// + /// Get the current in progress. + /// + public TestOperation Operation + { + get { return operation_; } + } + + /// + /// Get the this status is applicable to. + /// + public ZipFile File + { + get { return file_; } + } + + /// + /// Get the current/last entry tested. + /// + public ZipEntry Entry + { + get { return entry_; } + } + + /// + /// Get the number of errors detected so far. + /// + public int ErrorCount + { + get { return errorCount_; } + } + + /// + /// Get the number of bytes tested so far for the current entry. + /// + public long BytesTested + { + get { return bytesTested_; } + } + + /// + /// Get a value indicating wether the last entry test was valid. + /// + public bool EntryValid + { + get { return entryValid_; } + } + #endregion + + #region Internal API + internal void AddError() + { + errorCount_++; + entryValid_ = false; + } + + internal void SetOperation(TestOperation operation) + { + operation_ = operation; + } + + internal void SetEntry(ZipEntry entry) + { + entry_ = entry; + entryValid_ = true; + bytesTested_ = 0; + } + + internal void SetBytesTested(long value) + { + bytesTested_ = value; + } + #endregion + + #region Instance Fields + ZipFile file_; + ZipEntry entry_; + bool entryValid_; + int errorCount_; + long bytesTested_; + TestOperation operation_; + #endregion + } + + /// + /// Delegate invoked during testing if supplied indicating current progress and status. + /// + /// If the message is non-null an error has occured. If the message is null + /// the operation as found in status has started. + public delegate void ZipTestResultHandler(TestStatus status, string message); + #endregion + + #region Update Definitions + /// + /// The possible ways of applying updates to an archive. + /// + public enum FileUpdateMode + { + /// + /// Perform all updates on temporary files ensuring that the original file is saved. + /// + Safe, + /// + /// Update the archive directly, which is faster but less safe. + /// + Direct, + } + #endregion + + #region ZipFile Class + /// + /// This class represents a Zip archive. You can ask for the contained + /// entries, or get an input stream for a file entry. The entry is + /// automatically decompressed. + /// + /// You can also update the archive adding or deleting entries. + /// + /// This class is thread safe for input: You can open input streams for arbitrary + /// entries in different threads. + ///
    + ///
    Author of the original java version : Jochen Hoenicke + ///
    + /// + /// + /// using System; + /// using System.Text; + /// using System.Collections; + /// using System.IO; + /// + /// using ICSharpCode.SharpZipLib.Zip; + /// + /// class MainClass + /// { + /// static public void Main(string[] args) + /// { + /// using (ZipFile zFile = new ZipFile(args[0])) { + /// Console.WriteLine("Listing of : " + zFile.Name); + /// Console.WriteLine(""); + /// Console.WriteLine("Raw Size Size Date Time Name"); + /// Console.WriteLine("-------- -------- -------- ------ ---------"); + /// foreach (ZipEntry e in zFile) { + /// if ( e.IsFile ) { + /// DateTime d = e.DateTime; + /// Console.WriteLine("{0, -10}{1, -10}{2} {3} {4}", e.Size, e.CompressedSize, + /// d.ToString("dd-MM-yy"), d.ToString("HH:mm"), + /// e.Name); + /// } + /// } + /// } + /// } + /// } + /// + /// + public class ZipFile : IEnumerable, IDisposable + { + #region KeyHandling + + /// + /// Delegate for handling keys/password setting during compresion/decompression. + /// + public delegate void KeysRequiredEventHandler( + object sender, + KeysRequiredEventArgs e + ); + + /// + /// Event handler for handling encryption keys. + /// + public KeysRequiredEventHandler KeysRequired; + + /// + /// Handles getting of encryption keys when required. + /// + /// The file for which encryption keys are required. + void OnKeysRequired(string fileName) + { + if (KeysRequired != null) { + KeysRequiredEventArgs krea = new KeysRequiredEventArgs(fileName, key); + KeysRequired(this, krea); + key = krea.Key; + } + } + + /// + /// Get/set the encryption key value. + /// + byte[] Key + { + get { return key; } + set { key = value; } + } + +#if !NETCF_1_0 + /// + /// Password to be used for encrypting/decrypting files. + /// + /// Set to null if no password is required. + public string Password + { + set + { + if ( (value == null) || (value.Length == 0) ) { + key = null; + } + else { + rawPassword_ = value; + key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(value)); + } + } + } #endif - /// - /// Get a value indicating wether encryption keys are currently available. - /// - bool HaveKeys - { - get { return key != null; } - } - #endregion - - #region Constructors - /// - /// Opens a Zip file with the given name for reading. - /// - /// The name of the file to open. - /// The argument supplied is null. - /// - /// An i/o error occurs - /// - /// - /// The file doesn't contain a valid zip archive. - /// - public ZipFile(string name) - { - if ( name == null ) { - throw new ArgumentNullException("name"); - } - - name_ = name; - - baseStream_ = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read); - isStreamOwner = true; - - try { - ReadEntries(); - } - catch { - DisposeInternal(true); - throw; - } - } - - /// - /// Opens a Zip file reading the given . - /// - /// The to read archive data from. - /// The supplied argument is null. - /// - /// An i/o error occurs. - /// - /// - /// The file doesn't contain a valid zip archive. - /// - public ZipFile(FileStream file) - { - if ( file == null ) { - throw new ArgumentNullException("file"); - } - - if ( !file.CanSeek ) { - throw new ArgumentException("Stream is not seekable", "file"); - } - - baseStream_ = file; - name_ = file.Name; - isStreamOwner = true; - - try { - ReadEntries(); - } - catch { - DisposeInternal(true); - throw; - } - } - - /// - /// Opens a Zip file reading the given . - /// - /// The to read archive data from. - /// - /// An i/o error occurs - /// - /// - /// The stream doesn't contain a valid zip archive.
    - ///
    - /// - /// The stream doesnt support seeking. - /// - /// - /// The stream argument is null. - /// - public ZipFile(Stream stream) - { - if ( stream == null ) { - throw new ArgumentNullException("stream"); - } - - if ( !stream.CanSeek ) { - throw new ArgumentException("Stream is not seekable", "stream"); - } - - baseStream_ = stream; - isStreamOwner = true; - - if ( baseStream_.Length > 0 ) { - try { - ReadEntries(); - } - catch { - DisposeInternal(true); - throw; - } - } else { - entries_ = new ZipEntry[0]; - isNewArchive_ = true; - } - } - - /// - /// Initialises a default instance with no entries and no file storage. - /// - internal ZipFile() - { - entries_ = new ZipEntry[0]; - isNewArchive_ = true; - } - - #endregion - - #region Destructors and Closing - /// - /// Finalize this instance. - /// - ~ZipFile() - { - Dispose(false); - } - - /// - /// Closes the ZipFile. If the stream is owned then this also closes the underlying input stream. - /// Once closed, no further instance methods should be called. - /// - /// - /// An i/o error occurs. - /// - public void Close() - { - DisposeInternal(true); - GC.SuppressFinalize(this); - } - - #endregion - - #region Creators - /// - /// Create a new whose data will be stored in a file. - /// - /// The name of the archive to create. - /// Returns the newly created - /// is null - public static ZipFile Create(string fileName) - { - if ( fileName == null ) { - throw new ArgumentNullException("fileName"); - } - - FileStream fs = File.Create(fileName); - - ZipFile result = new ZipFile(); - result.name_ = fileName; - result.baseStream_ = fs; - result.isStreamOwner = true; - return result; - } - - /// - /// Create a new whose data will be stored on a stream. - /// - /// The stream providing data storage. - /// Returns the newly created - /// is null - /// doesnt support writing. - public static ZipFile Create(Stream outStream) - { - if ( outStream == null ) { - throw new ArgumentNullException("outStream"); - } - - if ( !outStream.CanWrite ) { - throw new ArgumentException("Stream is not writeable", "outStream"); - } - - if ( !outStream.CanSeek ) { - throw new ArgumentException("Stream is not seekable", "outStream"); - } - - ZipFile result = new ZipFile(); - result.baseStream_ = outStream; - return result; - } - - #endregion - - #region Properties - /// - /// Get/set a flag indicating if the underlying stream is owned by the ZipFile instance. - /// If the flag is true then the stream will be closed when Close is called. - /// - /// - /// The default value is true in all cases. - /// - public bool IsStreamOwner - { - get { return isStreamOwner; } - set { isStreamOwner = value; } - } - - /// - /// Get a value indicating wether - /// this archive is embedded in another file or not. - /// - public bool IsEmbeddedArchive - { - // Not strictly correct in all circumstances currently - get { return offsetOfFirstEntry > 0; } - } - - /// - /// Get a value indicating that this archive is a new one. - /// - public bool IsNewArchive - { - get { return isNewArchive_; } - } - - /// - /// Gets the comment for the zip file. - /// - public string ZipFileComment - { - get { return comment_; } - } - - /// - /// Gets the name of this zip file. - /// - public string Name - { - get { return name_; } - } - - /// - /// Gets the number of entries in this zip file. - /// - /// - /// The Zip file has been closed. - /// - [Obsolete("Use the Count property instead")] - public int Size - { - get - { - return entries_.Length; - } - } - - /// - /// Get the number of entries contained in this . - /// - public long Count - { - get - { - return entries_.Length; - } - } - - /// - /// Indexer property for ZipEntries - /// - [System.Runtime.CompilerServices.IndexerNameAttribute("EntryByIndex")] - public ZipEntry this[int index] - { - get { - return (ZipEntry) entries_[index].Clone(); - } - } - - #endregion - - #region Input Handling - /// - /// Gets an enumerator for the Zip entries in this Zip file. - /// - /// Returns an for this archive. - /// - /// The Zip file has been closed. - /// - public IEnumerator GetEnumerator() - { - if (isDisposed_) { - throw new ObjectDisposedException("ZipFile"); - } - - return new ZipEntryEnumerator(entries_); - } - - /// - /// Return the index of the entry with a matching name - /// - /// Entry name to find - /// If true the comparison is case insensitive - /// The index position of the matching entry or -1 if not found - /// - /// The Zip file has been closed. - /// - public int FindEntry(string name, bool ignoreCase) - { - if (isDisposed_) { - throw new ObjectDisposedException("ZipFile"); - } - - // TODO: This will be slow as the next ice age for huge archives! - for (int i = 0; i < entries_.Length; i++) { - if (string.Compare(name, entries_[i].Name, ignoreCase, CultureInfo.InvariantCulture) == 0) { - return i; - } - } - return -1; - } - - /// - /// Searches for a zip entry in this archive with the given name. - /// String comparisons are case insensitive - /// - /// - /// The name to find. May contain directory components separated by slashes ('/'). - /// - /// - /// A clone of the zip entry, or null if no entry with that name exists. - /// - /// - /// The Zip file has been closed. - /// - public ZipEntry GetEntry(string name) - { - if (isDisposed_) { - throw new ObjectDisposedException("ZipFile"); - } - - int index = FindEntry(name, true); - return (index >= 0) ? (ZipEntry) entries_[index].Clone() : null; - } - - /// - /// Gets an input stream for reading the given zip entry data in an uncompressed form. - /// Normally the should be an entry returned by GetEntry(). - /// - /// The to obtain a data for - /// An input containing data for this - /// - /// The ZipFile has already been closed - /// - /// - /// The compression method for the entry is unknown - /// - /// - /// The entry is not found in the ZipFile - /// - public Stream GetInputStream(ZipEntry entry) - { - if ( entry == null ) { - throw new ArgumentNullException("entry"); - } - - if ( isDisposed_ ) { - throw new ObjectDisposedException("ZipFile"); - } - - long index = entry.ZipFileIndex; - if ( (index < 0) || (index >= entries_.Length) || (entries_[index].Name != entry.Name) ) { - index = FindEntry(entry.Name, true); - if (index < 0) { - throw new ZipException("Entry cannot be found"); - } - } - return GetInputStream(index); - } - - /// - /// Creates an input stream reading a zip entry - /// - /// The index of the entry to obtain an input stream for. - /// - /// An input containing data for this - /// - /// - /// The ZipFile has already been closed - /// - /// - /// The compression method for the entry is unknown - /// - /// - /// The entry is not found in the ZipFile - /// - public Stream GetInputStream(long entryIndex) - { - if ( isDisposed_ ) { - throw new ObjectDisposedException("ZipFile"); - } - - long start = LocateEntry(entries_[entryIndex]); - CompressionMethod method = entries_[entryIndex].CompressionMethod; - Stream result = new PartialInputStream(this, start, entries_[entryIndex].CompressedSize); - - if (entries_[entryIndex].IsCrypted == true) { + /// + /// Get a value indicating wether encryption keys are currently available. + /// + bool HaveKeys + { + get { return key != null; } + } + #endregion + + #region Constructors + /// + /// Opens a Zip file with the given name for reading. + /// + /// The name of the file to open. + /// The argument supplied is null. + /// + /// An i/o error occurs + /// + /// + /// The file doesn't contain a valid zip archive. + /// + public ZipFile(string name) + { + if ( name == null ) { + throw new ArgumentNullException("name"); + } + + name_ = name; + + baseStream_ = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read); + isStreamOwner = true; + + try { + ReadEntries(); + } + catch { + DisposeInternal(true); + throw; + } + } + + /// + /// Opens a Zip file reading the given . + /// + /// The to read archive data from. + /// The supplied argument is null. + /// + /// An i/o error occurs. + /// + /// + /// The file doesn't contain a valid zip archive. + /// + public ZipFile(FileStream file) + { + if ( file == null ) { + throw new ArgumentNullException("file"); + } + + if ( !file.CanSeek ) { + throw new ArgumentException("Stream is not seekable", "file"); + } + + baseStream_ = file; + name_ = file.Name; + isStreamOwner = true; + + try { + ReadEntries(); + } + catch { + DisposeInternal(true); + throw; + } + } + + /// + /// Opens a Zip file reading the given . + /// + /// The to read archive data from. + /// + /// An i/o error occurs + /// + /// + /// The stream doesn't contain a valid zip archive.
    + ///
    + /// + /// The stream doesnt support seeking. + /// + /// + /// The stream argument is null. + /// + public ZipFile(Stream stream) + { + if ( stream == null ) { + throw new ArgumentNullException("stream"); + } + + if ( !stream.CanSeek ) { + throw new ArgumentException("Stream is not seekable", "stream"); + } + + baseStream_ = stream; + isStreamOwner = true; + + if ( baseStream_.Length > 0 ) { + try { + ReadEntries(); + } + catch { + DisposeInternal(true); + throw; + } + } else { + entries_ = new ZipEntry[0]; + isNewArchive_ = true; + } + } + + /// + /// Initialises a default instance with no entries and no file storage. + /// + internal ZipFile() + { + entries_ = new ZipEntry[0]; + isNewArchive_ = true; + } + + #endregion + + #region Destructors and Closing + /// + /// Finalize this instance. + /// + ~ZipFile() + { + Dispose(false); + } + + /// + /// Closes the ZipFile. If the stream is owned then this also closes the underlying input stream. + /// Once closed, no further instance methods should be called. + /// + /// + /// An i/o error occurs. + /// + public void Close() + { + DisposeInternal(true); + GC.SuppressFinalize(this); + } + + #endregion + + #region Creators + /// + /// Create a new whose data will be stored in a file. + /// + /// The name of the archive to create. + /// Returns the newly created + /// is null + public static ZipFile Create(string fileName) + { + if ( fileName == null ) { + throw new ArgumentNullException("fileName"); + } + + FileStream fs = File.Create(fileName); + + ZipFile result = new ZipFile(); + result.name_ = fileName; + result.baseStream_ = fs; + result.isStreamOwner = true; + return result; + } + + /// + /// Create a new whose data will be stored on a stream. + /// + /// The stream providing data storage. + /// Returns the newly created + /// is null + /// doesnt support writing. + public static ZipFile Create(Stream outStream) + { + if ( outStream == null ) { + throw new ArgumentNullException("outStream"); + } + + if ( !outStream.CanWrite ) { + throw new ArgumentException("Stream is not writeable", "outStream"); + } + + if ( !outStream.CanSeek ) { + throw new ArgumentException("Stream is not seekable", "outStream"); + } + + ZipFile result = new ZipFile(); + result.baseStream_ = outStream; + return result; + } + + #endregion + + #region Properties + /// + /// Get/set a flag indicating if the underlying stream is owned by the ZipFile instance. + /// If the flag is true then the stream will be closed when Close is called. + /// + /// + /// The default value is true in all cases. + /// + public bool IsStreamOwner + { + get { return isStreamOwner; } + set { isStreamOwner = value; } + } + + /// + /// Get a value indicating wether + /// this archive is embedded in another file or not. + /// + public bool IsEmbeddedArchive + { + // Not strictly correct in all circumstances currently + get { return offsetOfFirstEntry > 0; } + } + + /// + /// Get a value indicating that this archive is a new one. + /// + public bool IsNewArchive + { + get { return isNewArchive_; } + } + + /// + /// Gets the comment for the zip file. + /// + public string ZipFileComment + { + get { return comment_; } + } + + /// + /// Gets the name of this zip file. + /// + public string Name + { + get { return name_; } + } + + /// + /// Gets the number of entries in this zip file. + /// + /// + /// The Zip file has been closed. + /// + [Obsolete("Use the Count property instead")] + public int Size + { + get + { + return entries_.Length; + } + } + + /// + /// Get the number of entries contained in this . + /// + public long Count + { + get + { + return entries_.Length; + } + } + + /// + /// Indexer property for ZipEntries + /// + [System.Runtime.CompilerServices.IndexerNameAttribute("EntryByIndex")] + public ZipEntry this[int index] + { + get { + return (ZipEntry) entries_[index].Clone(); + } + } + + #endregion + + #region Input Handling + /// + /// Gets an enumerator for the Zip entries in this Zip file. + /// + /// Returns an for this archive. + /// + /// The Zip file has been closed. + /// + public IEnumerator GetEnumerator() + { + if (isDisposed_) { + throw new ObjectDisposedException("ZipFile"); + } + + return new ZipEntryEnumerator(entries_); + } + + /// + /// Return the index of the entry with a matching name + /// + /// Entry name to find + /// If true the comparison is case insensitive + /// The index position of the matching entry or -1 if not found + /// + /// The Zip file has been closed. + /// + public int FindEntry(string name, bool ignoreCase) + { + if (isDisposed_) { + throw new ObjectDisposedException("ZipFile"); + } + + // TODO: This will be slow as the next ice age for huge archives! + for (int i = 0; i < entries_.Length; i++) { + if (string.Compare(name, entries_[i].Name, ignoreCase, CultureInfo.InvariantCulture) == 0) { + return i; + } + } + return -1; + } + + /// + /// Searches for a zip entry in this archive with the given name. + /// String comparisons are case insensitive + /// + /// + /// The name to find. May contain directory components separated by slashes ('/'). + /// + /// + /// A clone of the zip entry, or null if no entry with that name exists. + /// + /// + /// The Zip file has been closed. + /// + public ZipEntry GetEntry(string name) + { + if (isDisposed_) { + throw new ObjectDisposedException("ZipFile"); + } + + int index = FindEntry(name, true); + return (index >= 0) ? (ZipEntry) entries_[index].Clone() : null; + } + + /// + /// Gets an input stream for reading the given zip entry data in an uncompressed form. + /// Normally the should be an entry returned by GetEntry(). + /// + /// The to obtain a data for + /// An input containing data for this + /// + /// The ZipFile has already been closed + /// + /// + /// The compression method for the entry is unknown + /// + /// + /// The entry is not found in the ZipFile + /// + public Stream GetInputStream(ZipEntry entry) + { + if ( entry == null ) { + throw new ArgumentNullException("entry"); + } + + if ( isDisposed_ ) { + throw new ObjectDisposedException("ZipFile"); + } + + long index = entry.ZipFileIndex; + if ( (index < 0) || (index >= entries_.Length) || (entries_[index].Name != entry.Name) ) { + index = FindEntry(entry.Name, true); + if (index < 0) { + throw new ZipException("Entry cannot be found"); + } + } + return GetInputStream(index); + } + + /// + /// Creates an input stream reading a zip entry + /// + /// The index of the entry to obtain an input stream for. + /// + /// An input containing data for this + /// + /// + /// The ZipFile has already been closed + /// + /// + /// The compression method for the entry is unknown + /// + /// + /// The entry is not found in the ZipFile + /// + public Stream GetInputStream(long entryIndex) + { + if ( isDisposed_ ) { + throw new ObjectDisposedException("ZipFile"); + } + + long start = LocateEntry(entries_[entryIndex]); + CompressionMethod method = entries_[entryIndex].CompressionMethod; + Stream result = new PartialInputStream(this, start, entries_[entryIndex].CompressedSize); + + if (entries_[entryIndex].IsCrypted == true) { #if NETCF_1_0 - throw new ZipException("decryption not supported for Compact Framework 1.0"); + throw new ZipException("decryption not supported for Compact Framework 1.0"); #else - result = CreateAndInitDecryptionStream(result, entries_[entryIndex]); - if (result == null) { - throw new ZipException("Unable to decrypt this entry"); - } -#endif - } - - switch (method) { - case CompressionMethod.Stored: - // read as is. - break; - - case CompressionMethod.Deflated: - // No need to worry about ownership and closing as underlying stream close does nothing. - result = new InflaterInputStream(result, new Inflater(true)); - break; - - default: - throw new ZipException("Unsupported compression method " + method); - } - - return result; - } - - #endregion - - #region Archive Testing - /// - /// Test an archive for integrity/validity - /// - /// Perform low level data Crc check - /// true if all tests pass, false otherwise - /// Testing will terminate on the first error found. - public bool TestArchive(bool testData) - { - return TestArchive(testData, TestStrategy.FindFirstError, null); - } - - /// - /// Test an archive for integrity/validity - /// - /// Perform low level data Crc check - /// The to apply. - /// The handler to call during testing. - /// true if all tests pass, false otherwise - /// The object has already been closed. - public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandler resultHandler) - { - if (isDisposed_) { - throw new ObjectDisposedException("ZipFile"); - } - - TestStatus status = new TestStatus(this); - - if ( resultHandler != null ) { - resultHandler(status, null); - } - - HeaderTest test = testData ? (HeaderTest.Header | HeaderTest.Extract) : HeaderTest.Header; - - bool testing = true; - - try { - int entryIndex = 0; - - while ( testing && (entryIndex < Count) ) { - if ( resultHandler != null ) { - status.SetEntry(this[entryIndex]); - status.SetOperation(TestOperation.EntryHeader); - resultHandler(status, null); - } - - try { - TestLocalHeader(this[entryIndex], test); - } - catch(ZipException ex) { - status.AddError(); - - if ( resultHandler != null ) { - resultHandler(status, - string.Format("Exception during test - '{0}'", ex.Message)); - } - - if ( strategy == TestStrategy.FindFirstError ) { - testing = false; - } - } - - if ( testing && testData && this[entryIndex].IsFile ) { - if ( resultHandler != null ) { - status.SetOperation(TestOperation.EntryData); - resultHandler(status, null); - } + result = CreateAndInitDecryptionStream(result, entries_[entryIndex]); + if (result == null) { + throw new ZipException("Unable to decrypt this entry"); + } +#endif + } + + switch (method) { + case CompressionMethod.Stored: + // read as is. + break; + + case CompressionMethod.Deflated: + // No need to worry about ownership and closing as underlying stream close does nothing. + result = new InflaterInputStream(result, new Inflater(true)); + break; + + default: + throw new ZipException("Unsupported compression method " + method); + } + + return result; + } + + #endregion + + #region Archive Testing + /// + /// Test an archive for integrity/validity + /// + /// Perform low level data Crc check + /// true if all tests pass, false otherwise + /// Testing will terminate on the first error found. + public bool TestArchive(bool testData) + { + return TestArchive(testData, TestStrategy.FindFirstError, null); + } + + /// + /// Test an archive for integrity/validity + /// + /// Perform low level data Crc check + /// The to apply. + /// The handler to call during testing. + /// true if all tests pass, false otherwise + /// The object has already been closed. + public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandler resultHandler) + { + if (isDisposed_) { + throw new ObjectDisposedException("ZipFile"); + } + + TestStatus status = new TestStatus(this); + + if ( resultHandler != null ) { + resultHandler(status, null); + } + + HeaderTest test = testData ? (HeaderTest.Header | HeaderTest.Extract) : HeaderTest.Header; + + bool testing = true; + + try { + int entryIndex = 0; + + while ( testing && (entryIndex < Count) ) { + if ( resultHandler != null ) { + status.SetEntry(this[entryIndex]); + status.SetOperation(TestOperation.EntryHeader); + resultHandler(status, null); + } + + try { + TestLocalHeader(this[entryIndex], test); + } + catch(ZipException ex) { + status.AddError(); + + if ( resultHandler != null ) { + resultHandler(status, + string.Format("Exception during test - '{0}'", ex.Message)); + } + + if ( strategy == TestStrategy.FindFirstError ) { + testing = false; + } + } + + if ( testing && testData && this[entryIndex].IsFile ) { + if ( resultHandler != null ) { + status.SetOperation(TestOperation.EntryData); + resultHandler(status, null); + } Crc32 crc = new Crc32(); @@ -932,123 +932,123 @@ public bool TestArchive(bool testData, TestStrategy strategy, ZipTestResultHandl } } - if (this[entryIndex].Crc != crc.Value) { - status.AddError(); - - if ( resultHandler != null ) { - resultHandler(status, "CRC mismatch"); - } - - if ( strategy == TestStrategy.FindFirstError ) { - testing = false; - } - } - - if (( this[entryIndex].Flags & (int)GeneralBitFlags.Descriptor) != 0 ) { - ZipHelperStream helper = new ZipHelperStream(baseStream_); - DescriptorData data = new DescriptorData(); - helper.ReadDataDescriptor(this[entryIndex].LocalHeaderRequiresZip64, data); - if (this[entryIndex].Crc != data.Crc) { - status.AddError(); - } - - if (this[entryIndex].CompressedSize != data.CompressedSize) { - status.AddError(); - } - - if (this[entryIndex].Size != data.Size) { - status.AddError(); - } - } - } - - if ( resultHandler != null ) { - status.SetOperation(TestOperation.EntryComplete); - resultHandler(status, null); - } - - entryIndex += 1; - } - - if ( resultHandler != null ) { - status.SetOperation(TestOperation.MiscellaneousTests); - resultHandler(status, null); - } - - // TODO: the 'Corrina Johns' test where local headers are missing from - // the central directory. They are therefore invisible to many archivers. - } - catch (Exception ex) { - status.AddError(); - - if ( resultHandler != null ) { - resultHandler(status, string.Format("Exception during test - '{0}'", ex.Message)); - } - } - - if ( resultHandler != null ) { - status.SetOperation(TestOperation.Complete); - status.SetEntry(null); - resultHandler(status, null); - } - - return (status.ErrorCount == 0); - } - - [Flags] - enum HeaderTest - { - Extract = 0x01, // Check that this header represents an entry whose data can be extracted - Header = 0x02, // Check that this header contents are valid - } - - /// - /// Test a local header against that provided from the central directory - /// - /// - /// The entry to test against - /// - /// The type of tests to carry out. - /// The offset of the entries data in the file - long TestLocalHeader(ZipEntry entry, HeaderTest tests) - { - lock(baseStream_) - { - bool testHeader = (tests & HeaderTest.Header) != 0; - bool testData = (tests & HeaderTest.Extract) != 0; - - baseStream_.Seek(offsetOfFirstEntry + entry.Offset, SeekOrigin.Begin); - if ((int)ReadLEUint() != ZipConstants.LocalHeaderSignature) { - throw new ZipException(string.Format("Wrong local header signature @{0:X}", offsetOfFirstEntry + entry.Offset)); - } - - short extractVersion = ( short )ReadLEUshort(); - short localFlags = ( short )ReadLEUshort(); - short compressionMethod = ( short )ReadLEUshort(); - short fileTime = ( short )ReadLEUshort(); - short fileDate = ( short )ReadLEUshort(); - uint crcValue = ReadLEUint(); - long compressedSize = ReadLEUint(); - long size = ReadLEUint(); - int storedNameLength = ReadLEUshort(); - int extraDataLength = ReadLEUshort(); - - byte[] nameData = new byte[storedNameLength]; - StreamUtils.ReadFully(baseStream_, nameData); - - byte[] extraData = new byte[extraDataLength]; - StreamUtils.ReadFully(baseStream_, extraData); - - ZipExtraData localExtraData = new ZipExtraData(extraData); - - // Extra data / zip64 checks - if (localExtraData.Find(1)) - { - // 2010-03-04 Forum 10512: removed checks for version >= ZipConstants.VersionZip64 - // and size or compressedSize = MaxValue, due to rogue creators. - - size = localExtraData.ReadLong(); - compressedSize = localExtraData.ReadLong(); + if (this[entryIndex].Crc != crc.Value) { + status.AddError(); + + if ( resultHandler != null ) { + resultHandler(status, "CRC mismatch"); + } + + if ( strategy == TestStrategy.FindFirstError ) { + testing = false; + } + } + + if (( this[entryIndex].Flags & (int)GeneralBitFlags.Descriptor) != 0 ) { + ZipHelperStream helper = new ZipHelperStream(baseStream_); + DescriptorData data = new DescriptorData(); + helper.ReadDataDescriptor(this[entryIndex].LocalHeaderRequiresZip64, data); + if (this[entryIndex].Crc != data.Crc) { + status.AddError(); + } + + if (this[entryIndex].CompressedSize != data.CompressedSize) { + status.AddError(); + } + + if (this[entryIndex].Size != data.Size) { + status.AddError(); + } + } + } + + if ( resultHandler != null ) { + status.SetOperation(TestOperation.EntryComplete); + resultHandler(status, null); + } + + entryIndex += 1; + } + + if ( resultHandler != null ) { + status.SetOperation(TestOperation.MiscellaneousTests); + resultHandler(status, null); + } + + // TODO: the 'Corrina Johns' test where local headers are missing from + // the central directory. They are therefore invisible to many archivers. + } + catch (Exception ex) { + status.AddError(); + + if ( resultHandler != null ) { + resultHandler(status, string.Format("Exception during test - '{0}'", ex.Message)); + } + } + + if ( resultHandler != null ) { + status.SetOperation(TestOperation.Complete); + status.SetEntry(null); + resultHandler(status, null); + } + + return (status.ErrorCount == 0); + } + + [Flags] + enum HeaderTest + { + Extract = 0x01, // Check that this header represents an entry whose data can be extracted + Header = 0x02, // Check that this header contents are valid + } + + /// + /// Test a local header against that provided from the central directory + /// + /// + /// The entry to test against + /// + /// The type of tests to carry out. + /// The offset of the entries data in the file + long TestLocalHeader(ZipEntry entry, HeaderTest tests) + { + lock(baseStream_) + { + bool testHeader = (tests & HeaderTest.Header) != 0; + bool testData = (tests & HeaderTest.Extract) != 0; + + baseStream_.Seek(offsetOfFirstEntry + entry.Offset, SeekOrigin.Begin); + if ((int)ReadLEUint() != ZipConstants.LocalHeaderSignature) { + throw new ZipException(string.Format("Wrong local header signature @{0:X}", offsetOfFirstEntry + entry.Offset)); + } + + short extractVersion = ( short )ReadLEUshort(); + short localFlags = ( short )ReadLEUshort(); + short compressionMethod = ( short )ReadLEUshort(); + short fileTime = ( short )ReadLEUshort(); + short fileDate = ( short )ReadLEUshort(); + uint crcValue = ReadLEUint(); + long compressedSize = ReadLEUint(); + long size = ReadLEUint(); + int storedNameLength = ReadLEUshort(); + int extraDataLength = ReadLEUshort(); + + byte[] nameData = new byte[storedNameLength]; + StreamUtils.ReadFully(baseStream_, nameData); + + byte[] extraData = new byte[extraDataLength]; + StreamUtils.ReadFully(baseStream_, extraData); + + ZipExtraData localExtraData = new ZipExtraData(extraData); + + // Extra data / zip64 checks + if (localExtraData.Find(1)) + { + // 2010-03-04 Forum 10512: removed checks for version >= ZipConstants.VersionZip64 + // and size or compressedSize = MaxValue, due to rogue creators. + + size = localExtraData.ReadLong(); + compressedSize = localExtraData.ReadLong(); if ((localFlags & (int)GeneralBitFlags.Descriptor) != 0) { @@ -1062,36 +1062,36 @@ long TestLocalHeader(ZipEntry entry, HeaderTest tests) } } } - else - { - // No zip64 extra data but entry requires it. - if ((extractVersion >= ZipConstants.VersionZip64) && - (((uint)size == uint.MaxValue) || ((uint)compressedSize == uint.MaxValue))) - { - throw new ZipException("Required Zip64 extended information missing"); - } - } - - if ( testData ) { - if ( entry.IsFile ) { - if ( !entry.IsCompressionMethodSupported() ) { - throw new ZipException("Compression method not supported"); - } - - if ( (extractVersion > ZipConstants.VersionMadeBy) - || ((extractVersion > 20) && (extractVersion < ZipConstants.VersionZip64)) ) { - throw new ZipException(string.Format("Version required to extract this entry not supported ({0})", extractVersion)); - } - - if ( (localFlags & ( int )(GeneralBitFlags.Patched | GeneralBitFlags.StrongEncryption | GeneralBitFlags.EnhancedCompress | GeneralBitFlags.HeaderMasked)) != 0 ) { - throw new ZipException("The library does not support the zip version required to extract this entry"); - } - } - } + else + { + // No zip64 extra data but entry requires it. + if ((extractVersion >= ZipConstants.VersionZip64) && + (((uint)size == uint.MaxValue) || ((uint)compressedSize == uint.MaxValue))) + { + throw new ZipException("Required Zip64 extended information missing"); + } + } + + if ( testData ) { + if ( entry.IsFile ) { + if ( !entry.IsCompressionMethodSupported() ) { + throw new ZipException("Compression method not supported"); + } + + if ( (extractVersion > ZipConstants.VersionMadeBy) + || ((extractVersion > 20) && (extractVersion < ZipConstants.VersionZip64)) ) { + throw new ZipException(string.Format("Version required to extract this entry not supported ({0})", extractVersion)); + } + + if ( (localFlags & ( int )(GeneralBitFlags.Patched | GeneralBitFlags.StrongEncryption | GeneralBitFlags.EnhancedCompress | GeneralBitFlags.HeaderMasked)) != 0 ) { + throw new ZipException("The library does not support the zip version required to extract this entry"); + } + } + } if (testHeader) { - if ((extractVersion <= 63) && // Ignore later versions as we dont know about them.. + if ((extractVersion <= 63) && // Ignore later versions as we dont know about them.. (extractVersion != 10) && (extractVersion != 11) && (extractVersion != 20) && @@ -1243,3244 +1243,3244 @@ long TestLocalHeader(ZipEntry entry, HeaderTest tests) } } - // Tests that apply to both data and header. - - // Size can be verified only if it is known in the local header. - // it will always be known in the central header. - if (((localFlags & (int)GeneralBitFlags.Descriptor) == 0) || - ((size > 0) || (compressedSize > 0))) { - - if (size != entry.Size) { - throw new ZipException( - string.Format("Size mismatch between central header({0}) and local header({1})", - entry.Size, size)); - } - - if (compressedSize != entry.CompressedSize && - compressedSize != 0xFFFFFFFF && compressedSize != -1) { - throw new ZipException( - string.Format("Compressed size mismatch between central header({0}) and local header({1})", - entry.CompressedSize, compressedSize)); - } - } - - int extraLength = storedNameLength + extraDataLength; - return offsetOfFirstEntry + entry.Offset + ZipConstants.LocalHeaderBaseSize + extraLength; - } - } - - #endregion - - #region Updating - - const int DefaultBufferSize = 4096; - - /// - /// The kind of update to apply. - /// - enum UpdateCommand - { - Copy, // Copy original file contents. - Modify, // Change encryption, compression, attributes, name, time etc, of an existing file. - Add, // Add a new file to the archive. - } - - #region Properties - /// - /// Get / set the to apply to names when updating. - /// - public INameTransform NameTransform - { - get { - return updateEntryFactory_.NameTransform; - } - - set { - updateEntryFactory_.NameTransform = value; - } - } - - /// - /// Get/set the used to generate values - /// during updates. - /// - public IEntryFactory EntryFactory - { - get { - return updateEntryFactory_; - } - - set { - if (value == null) { - updateEntryFactory_ = new ZipEntryFactory(); - } - else { - updateEntryFactory_ = value; - } - } - } - - /// - /// Get /set the buffer size to be used when updating this zip file. - /// - public int BufferSize - { - get { return bufferSize_; } - set { - if ( value < 1024 ) { -#if NETCF_1_0 - throw new ArgumentOutOfRangeException("value"); + // Tests that apply to both data and header. + + // Size can be verified only if it is known in the local header. + // it will always be known in the central header. + if (((localFlags & (int)GeneralBitFlags.Descriptor) == 0) || + ((size > 0) || (compressedSize > 0))) { + + if (size != entry.Size) { + throw new ZipException( + string.Format("Size mismatch between central header({0}) and local header({1})", + entry.Size, size)); + } + + if (compressedSize != entry.CompressedSize && + compressedSize != 0xFFFFFFFF && compressedSize != -1) { + throw new ZipException( + string.Format("Compressed size mismatch between central header({0}) and local header({1})", + entry.CompressedSize, compressedSize)); + } + } + + int extraLength = storedNameLength + extraDataLength; + return offsetOfFirstEntry + entry.Offset + ZipConstants.LocalHeaderBaseSize + extraLength; + } + } + + #endregion + + #region Updating + + const int DefaultBufferSize = 4096; + + /// + /// The kind of update to apply. + /// + enum UpdateCommand + { + Copy, // Copy original file contents. + Modify, // Change encryption, compression, attributes, name, time etc, of an existing file. + Add, // Add a new file to the archive. + } + + #region Properties + /// + /// Get / set the to apply to names when updating. + /// + public INameTransform NameTransform + { + get { + return updateEntryFactory_.NameTransform; + } + + set { + updateEntryFactory_.NameTransform = value; + } + } + + /// + /// Get/set the used to generate values + /// during updates. + /// + public IEntryFactory EntryFactory + { + get { + return updateEntryFactory_; + } + + set { + if (value == null) { + updateEntryFactory_ = new ZipEntryFactory(); + } + else { + updateEntryFactory_ = value; + } + } + } + + /// + /// Get /set the buffer size to be used when updating this zip file. + /// + public int BufferSize + { + get { return bufferSize_; } + set { + if ( value < 1024 ) { +#if NETCF_1_0 + throw new ArgumentOutOfRangeException("value"); #else - throw new ArgumentOutOfRangeException("value", "cannot be below 1024"); -#endif - } - - if ( bufferSize_ != value ) { - bufferSize_ = value; - copyBuffer_ = null; - } - } - } - - /// - /// Get a value indicating an update has been started. - /// - public bool IsUpdating - { - get { return updates_ != null; } - } - - /// - /// Get / set a value indicating how Zip64 Extension usage is determined when adding entries. - /// - public UseZip64 UseZip64 - { - get { return useZip64_; } - set { useZip64_ = value; } - } - - #endregion - - #region Immediate updating -// TBD: Direct form of updating + throw new ArgumentOutOfRangeException("value", "cannot be below 1024"); +#endif + } + + if ( bufferSize_ != value ) { + bufferSize_ = value; + copyBuffer_ = null; + } + } + } + + /// + /// Get a value indicating an update has been started. + /// + public bool IsUpdating + { + get { return updates_ != null; } + } + + /// + /// Get / set a value indicating how Zip64 Extension usage is determined when adding entries. + /// + public UseZip64 UseZip64 + { + get { return useZip64_; } + set { useZip64_ = value; } + } + + #endregion + + #region Immediate updating +// TBD: Direct form of updating // -// public void Update(IEntryMatcher deleteMatcher) -// { -// } +// public void Update(IEntryMatcher deleteMatcher) +// { +// } // -// public void Update(IScanner addScanner) -// { -// } - #endregion - - #region Deferred Updating - /// - /// Begin updating this archive. - /// - /// The archive storage for use during the update. - /// The data source to utilise during updating. - /// ZipFile has been closed. - /// One of the arguments provided is null - /// ZipFile has been closed. - public void BeginUpdate(IArchiveStorage archiveStorage, IDynamicDataSource dataSource) - { - if ( archiveStorage == null ) { - throw new ArgumentNullException("archiveStorage"); - } - - if ( dataSource == null ) { - throw new ArgumentNullException("dataSource"); - } - - if ( isDisposed_ ) { - throw new ObjectDisposedException("ZipFile"); - } - - if ( IsEmbeddedArchive ) { - throw new ZipException ("Cannot update embedded/SFX archives"); - } - - archiveStorage_ = archiveStorage; - updateDataSource_ = dataSource; - - // NOTE: the baseStream_ may not currently support writing or seeking. - - updateIndex_ = new Hashtable(); - - updates_ = new ArrayList(entries_.Length); - foreach(ZipEntry entry in entries_) { - int index = updates_.Add(new ZipUpdate(entry)); - updateIndex_.Add(entry.Name, index); - } - - // We must sort by offset before using offset's calculated sizes - updates_.Sort(new UpdateComparer()); - - int idx = 0; - foreach (ZipUpdate update in updates_) { - //If last entry, there is no next entry offset to use - if (idx == updates_.Count - 1) - break; - - update.OffsetBasedSize = ((ZipUpdate)updates_[idx + 1]).Entry.Offset - update.Entry.Offset; - idx++; - } - updateCount_ = updates_.Count; - - contentsEdited_ = false; - commentEdited_ = false; - newComment_ = null; - } - - /// - /// Begin updating to this archive. - /// - /// The storage to use during the update. - public void BeginUpdate(IArchiveStorage archiveStorage) - { - BeginUpdate(archiveStorage, new DynamicDiskDataSource()); - } - - /// - /// Begin updating this archive. - /// - /// - /// - /// - public void BeginUpdate() - { - if ( Name == null ) { - BeginUpdate(new MemoryArchiveStorage(), new DynamicDiskDataSource()); - } - else { - BeginUpdate(new DiskArchiveStorage(this), new DynamicDiskDataSource()); - } - } - - /// - /// Commit current updates, updating this archive. - /// - /// - /// - /// ZipFile has been closed. - public void CommitUpdate() - { - if ( isDisposed_ ) { - throw new ObjectDisposedException("ZipFile"); - } - - CheckUpdating(); - - try { - updateIndex_.Clear(); - updateIndex_=null; - - if( contentsEdited_ ) { - RunUpdates(); - } - else if( commentEdited_ ) { - UpdateCommentOnly(); - } - else { - // Create an empty archive if none existed originally. - if( entries_.Length==0 ) { - byte[] theComment=(newComment_!=null)?newComment_.RawComment:ZipConstants.ConvertToArray(comment_); - using( ZipHelperStream zhs=new ZipHelperStream(baseStream_) ) { - zhs.WriteEndOfCentralDirectory(0, 0, 0, theComment); - } - } - } - - } - finally { - PostUpdateCleanup(); - } - } - - /// - /// Abort updating leaving the archive unchanged. - /// - /// - /// - public void AbortUpdate() - { - PostUpdateCleanup(); - } - - /// - /// Set the file comment to be recorded when the current update is commited. - /// - /// The comment to record. - /// ZipFile has been closed. - public void SetComment(string comment) - { - if ( isDisposed_ ) { - throw new ObjectDisposedException("ZipFile"); - } - - CheckUpdating(); - - newComment_ = new ZipString(comment); - - if ( newComment_.RawLength > 0xffff ) { - newComment_ = null; - throw new ZipException("Comment length exceeds maximum - 65535"); - } - - // We dont take account of the original and current comment appearing to be the same - // as encoding may be different. - commentEdited_ = true; - } - - #endregion - - #region Adding Entries - - void AddUpdate(ZipUpdate update) - { - contentsEdited_ = true; - - int index = FindExistingUpdate(update.Entry.Name); - - if (index >= 0) { - if ( updates_[index] == null ) { - updateCount_ += 1; - } - - // Direct replacement is faster than delete and add. - updates_[index] = update; - } - else { - index = updates_.Add(update); - updateCount_ += 1; - updateIndex_.Add(update.Entry.Name, index); - } - } - - /// - /// Add a new entry to the archive. - /// - /// The name of the file to add. - /// The compression method to use. - /// Ensure Unicode text is used for name and comment for this entry. - /// Argument supplied is null. - /// ZipFile has been closed. - /// Compression method is not supported. - public void Add(string fileName, CompressionMethod compressionMethod, bool useUnicodeText ) - { - if (fileName == null) { - throw new ArgumentNullException("fileName"); - } - - if ( isDisposed_ ) { - throw new ObjectDisposedException("ZipFile"); - } - - if (!ZipEntry.IsCompressionMethodSupported(compressionMethod)) { - throw new ArgumentOutOfRangeException("compressionMethod"); - } - - CheckUpdating(); - contentsEdited_ = true; - - ZipEntry entry = EntryFactory.MakeFileEntry(fileName); - entry.IsUnicodeText = useUnicodeText; - entry.CompressionMethod = compressionMethod; - - AddUpdate(new ZipUpdate(fileName, entry)); - } - - /// - /// Add a new entry to the archive. - /// - /// The name of the file to add. - /// The compression method to use. - /// ZipFile has been closed. - /// The compression method is not supported. - public void Add(string fileName, CompressionMethod compressionMethod) - { - if ( fileName == null ) { - throw new ArgumentNullException("fileName"); - } - - if ( !ZipEntry.IsCompressionMethodSupported(compressionMethod) ) { - throw new ArgumentOutOfRangeException("compressionMethod"); - } - - CheckUpdating(); - contentsEdited_ = true; - - ZipEntry entry = EntryFactory.MakeFileEntry(fileName); - entry.CompressionMethod = compressionMethod; - AddUpdate(new ZipUpdate(fileName, entry)); - } - - /// - /// Add a file to the archive. - /// - /// The name of the file to add. - /// Argument supplied is null. - public void Add(string fileName) - { - if ( fileName == null ) { - throw new ArgumentNullException("fileName"); - } - - CheckUpdating(); - AddUpdate(new ZipUpdate(fileName, EntryFactory.MakeFileEntry(fileName))); - } - - /// - /// Add a file to the archive. - /// - /// The name of the file to add. - /// The name to use for the on the Zip file created. - /// Argument supplied is null. - public void Add(string fileName, string entryName) - { - if (fileName == null) { - throw new ArgumentNullException("fileName"); - } - - if ( entryName == null ) { - throw new ArgumentNullException("entryName"); - } - - CheckUpdating(); - AddUpdate(new ZipUpdate(fileName, EntryFactory.MakeFileEntry(entryName))); - } - - - /// - /// Add a file entry with data. - /// - /// The source of the data for this entry. - /// The name to give to the entry. - public void Add(IStaticDataSource dataSource, string entryName) - { - if ( dataSource == null ) { - throw new ArgumentNullException("dataSource"); - } - - if ( entryName == null ) { - throw new ArgumentNullException("entryName"); - } - - CheckUpdating(); - AddUpdate(new ZipUpdate(dataSource, EntryFactory.MakeFileEntry(entryName, false))); - } - - /// - /// Add a file entry with data. - /// - /// The source of the data for this entry. - /// The name to give to the entry. - /// The compression method to use. - public void Add(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod) - { - if ( dataSource == null ) { - throw new ArgumentNullException("dataSource"); - } - - if ( entryName == null ) { - throw new ArgumentNullException("entryName"); - } - - CheckUpdating(); - - ZipEntry entry = EntryFactory.MakeFileEntry(entryName, false); - entry.CompressionMethod = compressionMethod; - - AddUpdate(new ZipUpdate(dataSource, entry)); - } - - /// - /// Add a file entry with data. - /// - /// The source of the data for this entry. - /// The name to give to the entry. - /// The compression method to use. - /// Ensure Unicode text is used for name and comments for this entry. - public void Add(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod, bool useUnicodeText) - { - if (dataSource == null) { - throw new ArgumentNullException("dataSource"); - } - - if ( entryName == null ) { - throw new ArgumentNullException("entryName"); - } - - CheckUpdating(); - - ZipEntry entry = EntryFactory.MakeFileEntry(entryName, false); - entry.IsUnicodeText = useUnicodeText; - entry.CompressionMethod = compressionMethod; - - AddUpdate(new ZipUpdate(dataSource, entry)); - } - - /// - /// Add a that contains no data. - /// - /// The entry to add. - /// This can be used to add directories, volume labels, or empty file entries. - public void Add(ZipEntry entry) - { - if ( entry == null ) { - throw new ArgumentNullException("entry"); - } - - CheckUpdating(); - - if ( (entry.Size != 0) || (entry.CompressedSize != 0) ) { - throw new ZipException("Entry cannot have any data"); - } - - AddUpdate(new ZipUpdate(UpdateCommand.Add, entry)); - } - - /// - /// Add a directory entry to the archive. - /// - /// The directory to add. - public void AddDirectory(string directoryName) - { - if ( directoryName == null ) { - throw new ArgumentNullException("directoryName"); - } - - CheckUpdating(); - - ZipEntry dirEntry = EntryFactory.MakeDirectoryEntry(directoryName); - AddUpdate(new ZipUpdate(UpdateCommand.Add, dirEntry)); - } - - #endregion - - #region Modifying Entries +// public void Update(IScanner addScanner) +// { +// } + #endregion + + #region Deferred Updating + /// + /// Begin updating this archive. + /// + /// The archive storage for use during the update. + /// The data source to utilise during updating. + /// ZipFile has been closed. + /// One of the arguments provided is null + /// ZipFile has been closed. + public void BeginUpdate(IArchiveStorage archiveStorage, IDynamicDataSource dataSource) + { + if ( archiveStorage == null ) { + throw new ArgumentNullException("archiveStorage"); + } + + if ( dataSource == null ) { + throw new ArgumentNullException("dataSource"); + } + + if ( isDisposed_ ) { + throw new ObjectDisposedException("ZipFile"); + } + + if ( IsEmbeddedArchive ) { + throw new ZipException ("Cannot update embedded/SFX archives"); + } + + archiveStorage_ = archiveStorage; + updateDataSource_ = dataSource; + + // NOTE: the baseStream_ may not currently support writing or seeking. + + updateIndex_ = new Hashtable(); + + updates_ = new ArrayList(entries_.Length); + foreach(ZipEntry entry in entries_) { + int index = updates_.Add(new ZipUpdate(entry)); + updateIndex_.Add(entry.Name, index); + } + + // We must sort by offset before using offset's calculated sizes + updates_.Sort(new UpdateComparer()); + + int idx = 0; + foreach (ZipUpdate update in updates_) { + //If last entry, there is no next entry offset to use + if (idx == updates_.Count - 1) + break; + + update.OffsetBasedSize = ((ZipUpdate)updates_[idx + 1]).Entry.Offset - update.Entry.Offset; + idx++; + } + updateCount_ = updates_.Count; + + contentsEdited_ = false; + commentEdited_ = false; + newComment_ = null; + } + + /// + /// Begin updating to this archive. + /// + /// The storage to use during the update. + public void BeginUpdate(IArchiveStorage archiveStorage) + { + BeginUpdate(archiveStorage, new DynamicDiskDataSource()); + } + + /// + /// Begin updating this archive. + /// + /// + /// + /// + public void BeginUpdate() + { + if ( Name == null ) { + BeginUpdate(new MemoryArchiveStorage(), new DynamicDiskDataSource()); + } + else { + BeginUpdate(new DiskArchiveStorage(this), new DynamicDiskDataSource()); + } + } + + /// + /// Commit current updates, updating this archive. + /// + /// + /// + /// ZipFile has been closed. + public void CommitUpdate() + { + if ( isDisposed_ ) { + throw new ObjectDisposedException("ZipFile"); + } + + CheckUpdating(); + + try { + updateIndex_.Clear(); + updateIndex_=null; + + if( contentsEdited_ ) { + RunUpdates(); + } + else if( commentEdited_ ) { + UpdateCommentOnly(); + } + else { + // Create an empty archive if none existed originally. + if( entries_.Length==0 ) { + byte[] theComment=(newComment_!=null)?newComment_.RawComment:ZipConstants.ConvertToArray(comment_); + using( ZipHelperStream zhs=new ZipHelperStream(baseStream_) ) { + zhs.WriteEndOfCentralDirectory(0, 0, 0, theComment); + } + } + } + + } + finally { + PostUpdateCleanup(); + } + } + + /// + /// Abort updating leaving the archive unchanged. + /// + /// + /// + public void AbortUpdate() + { + PostUpdateCleanup(); + } + + /// + /// Set the file comment to be recorded when the current update is commited. + /// + /// The comment to record. + /// ZipFile has been closed. + public void SetComment(string comment) + { + if ( isDisposed_ ) { + throw new ObjectDisposedException("ZipFile"); + } + + CheckUpdating(); + + newComment_ = new ZipString(comment); + + if ( newComment_.RawLength > 0xffff ) { + newComment_ = null; + throw new ZipException("Comment length exceeds maximum - 65535"); + } + + // We dont take account of the original and current comment appearing to be the same + // as encoding may be different. + commentEdited_ = true; + } + + #endregion + + #region Adding Entries + + void AddUpdate(ZipUpdate update) + { + contentsEdited_ = true; + + int index = FindExistingUpdate(update.Entry.Name); + + if (index >= 0) { + if ( updates_[index] == null ) { + updateCount_ += 1; + } + + // Direct replacement is faster than delete and add. + updates_[index] = update; + } + else { + index = updates_.Add(update); + updateCount_ += 1; + updateIndex_.Add(update.Entry.Name, index); + } + } + + /// + /// Add a new entry to the archive. + /// + /// The name of the file to add. + /// The compression method to use. + /// Ensure Unicode text is used for name and comment for this entry. + /// Argument supplied is null. + /// ZipFile has been closed. + /// Compression method is not supported. + public void Add(string fileName, CompressionMethod compressionMethod, bool useUnicodeText ) + { + if (fileName == null) { + throw new ArgumentNullException("fileName"); + } + + if ( isDisposed_ ) { + throw new ObjectDisposedException("ZipFile"); + } + + if (!ZipEntry.IsCompressionMethodSupported(compressionMethod)) { + throw new ArgumentOutOfRangeException("compressionMethod"); + } + + CheckUpdating(); + contentsEdited_ = true; + + ZipEntry entry = EntryFactory.MakeFileEntry(fileName); + entry.IsUnicodeText = useUnicodeText; + entry.CompressionMethod = compressionMethod; + + AddUpdate(new ZipUpdate(fileName, entry)); + } + + /// + /// Add a new entry to the archive. + /// + /// The name of the file to add. + /// The compression method to use. + /// ZipFile has been closed. + /// The compression method is not supported. + public void Add(string fileName, CompressionMethod compressionMethod) + { + if ( fileName == null ) { + throw new ArgumentNullException("fileName"); + } + + if ( !ZipEntry.IsCompressionMethodSupported(compressionMethod) ) { + throw new ArgumentOutOfRangeException("compressionMethod"); + } + + CheckUpdating(); + contentsEdited_ = true; + + ZipEntry entry = EntryFactory.MakeFileEntry(fileName); + entry.CompressionMethod = compressionMethod; + AddUpdate(new ZipUpdate(fileName, entry)); + } + + /// + /// Add a file to the archive. + /// + /// The name of the file to add. + /// Argument supplied is null. + public void Add(string fileName) + { + if ( fileName == null ) { + throw new ArgumentNullException("fileName"); + } + + CheckUpdating(); + AddUpdate(new ZipUpdate(fileName, EntryFactory.MakeFileEntry(fileName))); + } + + /// + /// Add a file to the archive. + /// + /// The name of the file to add. + /// The name to use for the on the Zip file created. + /// Argument supplied is null. + public void Add(string fileName, string entryName) + { + if (fileName == null) { + throw new ArgumentNullException("fileName"); + } + + if ( entryName == null ) { + throw new ArgumentNullException("entryName"); + } + + CheckUpdating(); + AddUpdate(new ZipUpdate(fileName, EntryFactory.MakeFileEntry(entryName))); + } + + + /// + /// Add a file entry with data. + /// + /// The source of the data for this entry. + /// The name to give to the entry. + public void Add(IStaticDataSource dataSource, string entryName) + { + if ( dataSource == null ) { + throw new ArgumentNullException("dataSource"); + } + + if ( entryName == null ) { + throw new ArgumentNullException("entryName"); + } + + CheckUpdating(); + AddUpdate(new ZipUpdate(dataSource, EntryFactory.MakeFileEntry(entryName, false))); + } + + /// + /// Add a file entry with data. + /// + /// The source of the data for this entry. + /// The name to give to the entry. + /// The compression method to use. + public void Add(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod) + { + if ( dataSource == null ) { + throw new ArgumentNullException("dataSource"); + } + + if ( entryName == null ) { + throw new ArgumentNullException("entryName"); + } + + CheckUpdating(); + + ZipEntry entry = EntryFactory.MakeFileEntry(entryName, false); + entry.CompressionMethod = compressionMethod; + + AddUpdate(new ZipUpdate(dataSource, entry)); + } + + /// + /// Add a file entry with data. + /// + /// The source of the data for this entry. + /// The name to give to the entry. + /// The compression method to use. + /// Ensure Unicode text is used for name and comments for this entry. + public void Add(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod, bool useUnicodeText) + { + if (dataSource == null) { + throw new ArgumentNullException("dataSource"); + } + + if ( entryName == null ) { + throw new ArgumentNullException("entryName"); + } + + CheckUpdating(); + + ZipEntry entry = EntryFactory.MakeFileEntry(entryName, false); + entry.IsUnicodeText = useUnicodeText; + entry.CompressionMethod = compressionMethod; + + AddUpdate(new ZipUpdate(dataSource, entry)); + } + + /// + /// Add a that contains no data. + /// + /// The entry to add. + /// This can be used to add directories, volume labels, or empty file entries. + public void Add(ZipEntry entry) + { + if ( entry == null ) { + throw new ArgumentNullException("entry"); + } + + CheckUpdating(); + + if ( (entry.Size != 0) || (entry.CompressedSize != 0) ) { + throw new ZipException("Entry cannot have any data"); + } + + AddUpdate(new ZipUpdate(UpdateCommand.Add, entry)); + } + + /// + /// Add a directory entry to the archive. + /// + /// The directory to add. + public void AddDirectory(string directoryName) + { + if ( directoryName == null ) { + throw new ArgumentNullException("directoryName"); + } + + CheckUpdating(); + + ZipEntry dirEntry = EntryFactory.MakeDirectoryEntry(directoryName); + AddUpdate(new ZipUpdate(UpdateCommand.Add, dirEntry)); + } + + #endregion + + #region Modifying Entries /* Modify not yet ready for public consumption. Direct modification of an entry should not overwrite original data before its read. Safe mode is trivial in this sense. - public void Modify(ZipEntry original, ZipEntry updated) - { - if ( original == null ) { - throw new ArgumentNullException("original"); - } - - if ( updated == null ) { - throw new ArgumentNullException("updated"); - } - - CheckUpdating(); - contentsEdited_ = true; - updates_.Add(new ZipUpdate(original, updated)); - } + public void Modify(ZipEntry original, ZipEntry updated) + { + if ( original == null ) { + throw new ArgumentNullException("original"); + } + + if ( updated == null ) { + throw new ArgumentNullException("updated"); + } + + CheckUpdating(); + contentsEdited_ = true; + updates_.Add(new ZipUpdate(original, updated)); + } */ - #endregion - - #region Deleting Entries - /// - /// Delete an entry by name - /// - /// The filename to delete - /// True if the entry was found and deleted; false otherwise. - public bool Delete(string fileName) - { - if ( fileName == null ) { - throw new ArgumentNullException("fileName"); - } - - CheckUpdating(); - - bool result = false; - int index = FindExistingUpdate(fileName); - if ( (index >= 0) && (updates_[index] != null) ) { - result = true; - contentsEdited_ = true; - updates_[index] = null; - updateCount_ -= 1; - } - else { - throw new ZipException("Cannot find entry to delete"); - } - return result; - } - - /// - /// Delete a from the archive. - /// - /// The entry to delete. - public void Delete(ZipEntry entry) - { - if ( entry == null ) { - throw new ArgumentNullException("entry"); - } - - CheckUpdating(); - - int index = FindExistingUpdate(entry); - if ( index >= 0 ) { - contentsEdited_ = true; - updates_[index] = null; - updateCount_ -= 1; - } - else { - throw new ZipException("Cannot find entry to delete"); - } - } - - #endregion - - #region Update Support - - #region Writing Values/Headers - void WriteLEShort(int value) - { - baseStream_.WriteByte(( byte )(value & 0xff)); - baseStream_.WriteByte(( byte )((value >> 8) & 0xff)); - } - - /// - /// Write an unsigned short in little endian byte order. - /// - void WriteLEUshort(ushort value) - { - baseStream_.WriteByte(( byte )(value & 0xff)); - baseStream_.WriteByte(( byte )(value >> 8)); - } - - /// - /// Write an int in little endian byte order. - /// - void WriteLEInt(int value) - { - WriteLEShort(value & 0xffff); - WriteLEShort(value >> 16); - } - - /// - /// Write an unsigned int in little endian byte order. - /// - void WriteLEUint(uint value) - { - WriteLEUshort((ushort)(value & 0xffff)); - WriteLEUshort((ushort)(value >> 16)); - } - - /// - /// Write a long in little endian byte order. - /// - void WriteLeLong(long value) - { - WriteLEInt(( int )(value & 0xffffffff)); - WriteLEInt(( int )(value >> 32)); - } - - void WriteLEUlong(ulong value) - { - WriteLEUint(( uint )(value & 0xffffffff)); - WriteLEUint(( uint )(value >> 32)); - } - - void WriteLocalEntryHeader(ZipUpdate update) - { - ZipEntry entry = update.OutEntry; - - // TODO: Local offset will require adjusting for multi-disk zip files. - entry.Offset = baseStream_.Position; - - // TODO: Need to clear any entry flags that dont make sense or throw an exception here. - if (update.Command != UpdateCommand.Copy) { - if (entry.CompressionMethod == CompressionMethod.Deflated) { - if (entry.Size == 0) { - // No need to compress - no data. - entry.CompressedSize = entry.Size; - entry.Crc = 0; - entry.CompressionMethod = CompressionMethod.Stored; - } - } - else if (entry.CompressionMethod == CompressionMethod.Stored) { - entry.Flags &= ~(int)GeneralBitFlags.Descriptor; - } - - if (HaveKeys) { - entry.IsCrypted = true; - if (entry.Crc < 0) { - entry.Flags |= (int)GeneralBitFlags.Descriptor; - } - } - else { - entry.IsCrypted = false; - } - - switch (useZip64_) { - case UseZip64.Dynamic: - if (entry.Size < 0) { - entry.ForceZip64(); - } - break; - - case UseZip64.On: - entry.ForceZip64(); - break; - - case UseZip64.Off: - // Do nothing. The entry itself may be using Zip64 independantly. - break; - } - } - - // Write the local file header - WriteLEInt(ZipConstants.LocalHeaderSignature); - - WriteLEShort(entry.Version); - WriteLEShort(entry.Flags); - - WriteLEShort((byte)entry.CompressionMethod); - WriteLEInt(( int )entry.DosTime); - - if ( !entry.HasCrc ) { - // Note patch address for updating CRC later. - update.CrcPatchOffset = baseStream_.Position; - WriteLEInt(( int )0); - } - else { - WriteLEInt(unchecked(( int )entry.Crc)); - } - - if (entry.LocalHeaderRequiresZip64) { - WriteLEInt(-1); - WriteLEInt(-1); - } - else { - if ( (entry.CompressedSize < 0) || (entry.Size < 0) ) { - update.SizePatchOffset = baseStream_.Position; - } - - WriteLEInt(( int )entry.CompressedSize); - WriteLEInt(( int )entry.Size); - } - - byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); - - if ( name.Length > 0xFFFF ) { - throw new ZipException("Entry name too long."); - } - - ZipExtraData ed = new ZipExtraData(entry.ExtraData); - - if ( entry.LocalHeaderRequiresZip64 ) { - ed.StartNewEntry(); - - // Local entry header always includes size and compressed size. - // NOTE the order of these fields is reversed when compared to the normal headers! - ed.AddLeLong(entry.Size); - ed.AddLeLong(entry.CompressedSize); - ed.AddNewEntry(1); - } - else { - ed.Delete(1); - } - - entry.ExtraData = ed.GetEntryData(); - - WriteLEShort(name.Length); - WriteLEShort(entry.ExtraData.Length); - - if ( name.Length > 0 ) { - baseStream_.Write(name, 0, name.Length); - } - - if ( entry.LocalHeaderRequiresZip64 ) { - if ( !ed.Find(1) ) { - throw new ZipException("Internal error cannot find extra data"); - } - - update.SizePatchOffset = baseStream_.Position + ed.CurrentReadIndex; - } - - if ( entry.ExtraData.Length > 0 ) { - baseStream_.Write(entry.ExtraData, 0, entry.ExtraData.Length); - } - } - - int WriteCentralDirectoryHeader(ZipEntry entry) - { - if ( entry.CompressedSize < 0 ) { - throw new ZipException("Attempt to write central directory entry with unknown csize"); - } - - if ( entry.Size < 0 ) { - throw new ZipException("Attempt to write central directory entry with unknown size"); - } - - if ( entry.Crc < 0 ) { - throw new ZipException("Attempt to write central directory entry with unknown crc"); - } - - // Write the central file header - WriteLEInt(ZipConstants.CentralHeaderSignature); - - // Version made by - WriteLEShort(ZipConstants.VersionMadeBy); - - // Version required to extract - WriteLEShort(entry.Version); - - WriteLEShort(entry.Flags); - - unchecked { - WriteLEShort((byte)entry.CompressionMethod); - WriteLEInt((int)entry.DosTime); - WriteLEInt((int)entry.Crc); - } - - if ( (entry.IsZip64Forced()) || (entry.CompressedSize >= 0xffffffff) ) { - WriteLEInt(-1); - } - else { - WriteLEInt((int)(entry.CompressedSize & 0xffffffff)); - } - - if ( (entry.IsZip64Forced()) || (entry.Size >= 0xffffffff) ) { - WriteLEInt(-1); - } - else { - WriteLEInt((int)entry.Size); - } - - byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); - - if ( name.Length > 0xFFFF ) { - throw new ZipException("Entry name is too long."); - } - - WriteLEShort(name.Length); - - // Central header extra data is different to local header version so regenerate. - ZipExtraData ed = new ZipExtraData(entry.ExtraData); - - if ( entry.CentralHeaderRequiresZip64 ) { - ed.StartNewEntry(); - - if ( (entry.Size >= 0xffffffff) || (useZip64_ == UseZip64.On) ) - { - ed.AddLeLong(entry.Size); - } - - if ( (entry.CompressedSize >= 0xffffffff) || (useZip64_ == UseZip64.On) ) - { - ed.AddLeLong(entry.CompressedSize); - } - - if ( entry.Offset >= 0xffffffff ) { - ed.AddLeLong(entry.Offset); - } - - // Number of disk on which this file starts isnt supported and is never written here. - ed.AddNewEntry(1); - } - else { - // Should have already be done when local header was added. - ed.Delete(1); - } - - byte[] centralExtraData = ed.GetEntryData(); - - WriteLEShort(centralExtraData.Length); - WriteLEShort(entry.Comment != null ? entry.Comment.Length : 0); - - WriteLEShort(0); // disk number - WriteLEShort(0); // internal file attributes - - // External file attributes... - if ( entry.ExternalFileAttributes != -1 ) { - WriteLEInt(entry.ExternalFileAttributes); - } - else { - if ( entry.IsDirectory ) { - WriteLEUint(16); - } - else { - WriteLEUint(0); - } - } - - if ( entry.Offset >= 0xffffffff ) { - WriteLEUint(0xffffffff); - } - else { - WriteLEUint((uint)(int)entry.Offset); - } - - if ( name.Length > 0 ) { - baseStream_.Write(name, 0, name.Length); - } - - if ( centralExtraData.Length > 0 ) { - baseStream_.Write(centralExtraData, 0, centralExtraData.Length); - } - - byte[] rawComment = (entry.Comment != null) ? Encoding.ASCII.GetBytes(entry.Comment) : new byte[0]; - - if ( rawComment.Length > 0 ) { - baseStream_.Write(rawComment, 0, rawComment.Length); - } - - return ZipConstants.CentralHeaderBaseSize + name.Length + centralExtraData.Length + rawComment.Length; - } - #endregion - - void PostUpdateCleanup() - { + #endregion + + #region Deleting Entries + /// + /// Delete an entry by name + /// + /// The filename to delete + /// True if the entry was found and deleted; false otherwise. + public bool Delete(string fileName) + { + if ( fileName == null ) { + throw new ArgumentNullException("fileName"); + } + + CheckUpdating(); + + bool result = false; + int index = FindExistingUpdate(fileName); + if ( (index >= 0) && (updates_[index] != null) ) { + result = true; + contentsEdited_ = true; + updates_[index] = null; + updateCount_ -= 1; + } + else { + throw new ZipException("Cannot find entry to delete"); + } + return result; + } + + /// + /// Delete a from the archive. + /// + /// The entry to delete. + public void Delete(ZipEntry entry) + { + if ( entry == null ) { + throw new ArgumentNullException("entry"); + } + + CheckUpdating(); + + int index = FindExistingUpdate(entry); + if ( index >= 0 ) { + contentsEdited_ = true; + updates_[index] = null; + updateCount_ -= 1; + } + else { + throw new ZipException("Cannot find entry to delete"); + } + } + + #endregion + + #region Update Support + + #region Writing Values/Headers + void WriteLEShort(int value) + { + baseStream_.WriteByte(( byte )(value & 0xff)); + baseStream_.WriteByte(( byte )((value >> 8) & 0xff)); + } + + /// + /// Write an unsigned short in little endian byte order. + /// + void WriteLEUshort(ushort value) + { + baseStream_.WriteByte(( byte )(value & 0xff)); + baseStream_.WriteByte(( byte )(value >> 8)); + } + + /// + /// Write an int in little endian byte order. + /// + void WriteLEInt(int value) + { + WriteLEShort(value & 0xffff); + WriteLEShort(value >> 16); + } + + /// + /// Write an unsigned int in little endian byte order. + /// + void WriteLEUint(uint value) + { + WriteLEUshort((ushort)(value & 0xffff)); + WriteLEUshort((ushort)(value >> 16)); + } + + /// + /// Write a long in little endian byte order. + /// + void WriteLeLong(long value) + { + WriteLEInt(( int )(value & 0xffffffff)); + WriteLEInt(( int )(value >> 32)); + } + + void WriteLEUlong(ulong value) + { + WriteLEUint(( uint )(value & 0xffffffff)); + WriteLEUint(( uint )(value >> 32)); + } + + void WriteLocalEntryHeader(ZipUpdate update) + { + ZipEntry entry = update.OutEntry; + + // TODO: Local offset will require adjusting for multi-disk zip files. + entry.Offset = baseStream_.Position; + + // TODO: Need to clear any entry flags that dont make sense or throw an exception here. + if (update.Command != UpdateCommand.Copy) { + if (entry.CompressionMethod == CompressionMethod.Deflated) { + if (entry.Size == 0) { + // No need to compress - no data. + entry.CompressedSize = entry.Size; + entry.Crc = 0; + entry.CompressionMethod = CompressionMethod.Stored; + } + } + else if (entry.CompressionMethod == CompressionMethod.Stored) { + entry.Flags &= ~(int)GeneralBitFlags.Descriptor; + } + + if (HaveKeys) { + entry.IsCrypted = true; + if (entry.Crc < 0) { + entry.Flags |= (int)GeneralBitFlags.Descriptor; + } + } + else { + entry.IsCrypted = false; + } + + switch (useZip64_) { + case UseZip64.Dynamic: + if (entry.Size < 0) { + entry.ForceZip64(); + } + break; + + case UseZip64.On: + entry.ForceZip64(); + break; + + case UseZip64.Off: + // Do nothing. The entry itself may be using Zip64 independantly. + break; + } + } + + // Write the local file header + WriteLEInt(ZipConstants.LocalHeaderSignature); + + WriteLEShort(entry.Version); + WriteLEShort(entry.Flags); + + WriteLEShort((byte)entry.CompressionMethod); + WriteLEInt(( int )entry.DosTime); + + if ( !entry.HasCrc ) { + // Note patch address for updating CRC later. + update.CrcPatchOffset = baseStream_.Position; + WriteLEInt(( int )0); + } + else { + WriteLEInt(unchecked(( int )entry.Crc)); + } + + if (entry.LocalHeaderRequiresZip64) { + WriteLEInt(-1); + WriteLEInt(-1); + } + else { + if ( (entry.CompressedSize < 0) || (entry.Size < 0) ) { + update.SizePatchOffset = baseStream_.Position; + } + + WriteLEInt(( int )entry.CompressedSize); + WriteLEInt(( int )entry.Size); + } + + byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); + + if ( name.Length > 0xFFFF ) { + throw new ZipException("Entry name too long."); + } + + ZipExtraData ed = new ZipExtraData(entry.ExtraData); + + if ( entry.LocalHeaderRequiresZip64 ) { + ed.StartNewEntry(); + + // Local entry header always includes size and compressed size. + // NOTE the order of these fields is reversed when compared to the normal headers! + ed.AddLeLong(entry.Size); + ed.AddLeLong(entry.CompressedSize); + ed.AddNewEntry(1); + } + else { + ed.Delete(1); + } + + entry.ExtraData = ed.GetEntryData(); + + WriteLEShort(name.Length); + WriteLEShort(entry.ExtraData.Length); + + if ( name.Length > 0 ) { + baseStream_.Write(name, 0, name.Length); + } + + if ( entry.LocalHeaderRequiresZip64 ) { + if ( !ed.Find(1) ) { + throw new ZipException("Internal error cannot find extra data"); + } + + update.SizePatchOffset = baseStream_.Position + ed.CurrentReadIndex; + } + + if ( entry.ExtraData.Length > 0 ) { + baseStream_.Write(entry.ExtraData, 0, entry.ExtraData.Length); + } + } + + int WriteCentralDirectoryHeader(ZipEntry entry) + { + if ( entry.CompressedSize < 0 ) { + throw new ZipException("Attempt to write central directory entry with unknown csize"); + } + + if ( entry.Size < 0 ) { + throw new ZipException("Attempt to write central directory entry with unknown size"); + } + + if ( entry.Crc < 0 ) { + throw new ZipException("Attempt to write central directory entry with unknown crc"); + } + + // Write the central file header + WriteLEInt(ZipConstants.CentralHeaderSignature); + + // Version made by + WriteLEShort(ZipConstants.VersionMadeBy); + + // Version required to extract + WriteLEShort(entry.Version); + + WriteLEShort(entry.Flags); + + unchecked { + WriteLEShort((byte)entry.CompressionMethod); + WriteLEInt((int)entry.DosTime); + WriteLEInt((int)entry.Crc); + } + + if ( (entry.IsZip64Forced()) || (entry.CompressedSize >= 0xffffffff) ) { + WriteLEInt(-1); + } + else { + WriteLEInt((int)(entry.CompressedSize & 0xffffffff)); + } + + if ( (entry.IsZip64Forced()) || (entry.Size >= 0xffffffff) ) { + WriteLEInt(-1); + } + else { + WriteLEInt((int)entry.Size); + } + + byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); + + if ( name.Length > 0xFFFF ) { + throw new ZipException("Entry name is too long."); + } + + WriteLEShort(name.Length); + + // Central header extra data is different to local header version so regenerate. + ZipExtraData ed = new ZipExtraData(entry.ExtraData); + + if ( entry.CentralHeaderRequiresZip64 ) { + ed.StartNewEntry(); + + if ( (entry.Size >= 0xffffffff) || (useZip64_ == UseZip64.On) ) + { + ed.AddLeLong(entry.Size); + } + + if ( (entry.CompressedSize >= 0xffffffff) || (useZip64_ == UseZip64.On) ) + { + ed.AddLeLong(entry.CompressedSize); + } + + if ( entry.Offset >= 0xffffffff ) { + ed.AddLeLong(entry.Offset); + } + + // Number of disk on which this file starts isnt supported and is never written here. + ed.AddNewEntry(1); + } + else { + // Should have already be done when local header was added. + ed.Delete(1); + } + + byte[] centralExtraData = ed.GetEntryData(); + + WriteLEShort(centralExtraData.Length); + WriteLEShort(entry.Comment != null ? entry.Comment.Length : 0); + + WriteLEShort(0); // disk number + WriteLEShort(0); // internal file attributes + + // External file attributes... + if ( entry.ExternalFileAttributes != -1 ) { + WriteLEInt(entry.ExternalFileAttributes); + } + else { + if ( entry.IsDirectory ) { + WriteLEUint(16); + } + else { + WriteLEUint(0); + } + } + + if ( entry.Offset >= 0xffffffff ) { + WriteLEUint(0xffffffff); + } + else { + WriteLEUint((uint)(int)entry.Offset); + } + + if ( name.Length > 0 ) { + baseStream_.Write(name, 0, name.Length); + } + + if ( centralExtraData.Length > 0 ) { + baseStream_.Write(centralExtraData, 0, centralExtraData.Length); + } + + byte[] rawComment = (entry.Comment != null) ? Encoding.ASCII.GetBytes(entry.Comment) : new byte[0]; + + if ( rawComment.Length > 0 ) { + baseStream_.Write(rawComment, 0, rawComment.Length); + } + + return ZipConstants.CentralHeaderBaseSize + name.Length + centralExtraData.Length + rawComment.Length; + } + #endregion + + void PostUpdateCleanup() + { updateDataSource_ = null; updates_ = null; updateIndex_ = null; if (archiveStorage_ != null) { - archiveStorage_.Dispose(); - archiveStorage_=null; - } - } + archiveStorage_.Dispose(); + archiveStorage_=null; + } + } - string GetTransformedFileName(string name) - { + string GetTransformedFileName(string name) + { INameTransform transform = NameTransform; - return (transform != null) ? - transform.TransformFile(name) : - name; - } + return (transform != null) ? + transform.TransformFile(name) : + name; + } - string GetTransformedDirectoryName(string name) - { + string GetTransformedDirectoryName(string name) + { INameTransform transform = NameTransform; return (transform != null) ? - transform.TransformDirectory(name) : - name; - } - - /// - /// Get a raw memory buffer. - /// - /// Returns a raw memory buffer. - byte[] GetBuffer() - { - if ( copyBuffer_ == null ) { - copyBuffer_ = new byte[bufferSize_]; - } - return copyBuffer_; - } - - void CopyDescriptorBytes(ZipUpdate update, Stream dest, Stream source) - { - int bytesToCopy = GetDescriptorSize(update); - - if ( bytesToCopy > 0 ) { - byte[] buffer = GetBuffer(); - - while ( bytesToCopy > 0 ) { - int readSize = Math.Min(buffer.Length, bytesToCopy); - - int bytesRead = source.Read(buffer, 0, readSize); - if ( bytesRead > 0 ) { - dest.Write(buffer, 0, bytesRead); - bytesToCopy -= bytesRead; - } - else { - throw new ZipException("Unxpected end of stream"); - } - } - } - } - - void CopyBytes(ZipUpdate update, Stream destination, Stream source, - long bytesToCopy, bool updateCrc) - { - if ( destination == source ) { - throw new InvalidOperationException("Destination and source are the same"); - } - - // NOTE: Compressed size is updated elsewhere. - Crc32 crc = new Crc32(); - byte[] buffer = GetBuffer(); - - long targetBytes = bytesToCopy; - long totalBytesRead = 0; - - int bytesRead; - do { - int readSize = buffer.Length; - - if ( bytesToCopy < readSize ) { - readSize = (int)bytesToCopy; - } - - bytesRead = source.Read(buffer, 0, readSize); - if ( bytesRead > 0 ) { - if ( updateCrc ) { - crc.Update(buffer, 0, bytesRead); - } - destination.Write(buffer, 0, bytesRead); - bytesToCopy -= bytesRead; - totalBytesRead += bytesRead; - } - } - while ( (bytesRead > 0) && (bytesToCopy > 0) ); - - if ( totalBytesRead != targetBytes ) { - throw new ZipException(string.Format("Failed to copy bytes expected {0} read {1}", targetBytes, totalBytesRead)); - } - - if ( updateCrc ) { - update.OutEntry.Crc = crc.Value; - } - } - - /// - /// Get the size of the source descriptor for a . - /// - /// The update to get the size for. - /// The descriptor size, zero if there isnt one. - int GetDescriptorSize(ZipUpdate update) - { - int result = 0; - if ( (update.Entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) { - result = ZipConstants.DataDescriptorSize - 4; - if ( update.Entry.LocalHeaderRequiresZip64 ) { - result = ZipConstants.Zip64DataDescriptorSize - 4; - } - } - return result; - } - - void CopyDescriptorBytesDirect(ZipUpdate update, Stream stream, ref long destinationPosition, long sourcePosition) - { - int bytesToCopy = GetDescriptorSize(update); - - while ( bytesToCopy > 0 ) { - int readSize = (int)bytesToCopy; - byte[] buffer = GetBuffer(); - - stream.Position = sourcePosition; - int bytesRead = stream.Read(buffer, 0, readSize); - if ( bytesRead > 0 ) { - stream.Position = destinationPosition; - stream.Write(buffer, 0, bytesRead); - bytesToCopy -= bytesRead; - destinationPosition += bytesRead; - sourcePosition += bytesRead; - } - else { - throw new ZipException("Unxpected end of stream"); - } - } - } - - void CopyEntryDataDirect(ZipUpdate update, Stream stream, bool updateCrc, ref long destinationPosition, ref long sourcePosition) - { - long bytesToCopy = update.Entry.CompressedSize; - - // NOTE: Compressed size is updated elsewhere. - Crc32 crc = new Crc32(); - byte[] buffer = GetBuffer(); - - long targetBytes = bytesToCopy; - long totalBytesRead = 0; - - int bytesRead; - do - { - int readSize = buffer.Length; - - if ( bytesToCopy < readSize ) { - readSize = (int)bytesToCopy; - } - - stream.Position = sourcePosition; - bytesRead = stream.Read(buffer, 0, readSize); - if ( bytesRead > 0 ) { - if ( updateCrc ) { - crc.Update(buffer, 0, bytesRead); - } - stream.Position = destinationPosition; - stream.Write(buffer, 0, bytesRead); - - destinationPosition += bytesRead; - sourcePosition += bytesRead; - bytesToCopy -= bytesRead; - totalBytesRead += bytesRead; - } - } - while ( (bytesRead > 0) && (bytesToCopy > 0) ); - - if ( totalBytesRead != targetBytes ) { - throw new ZipException(string.Format("Failed to copy bytes expected {0} read {1}", targetBytes, totalBytesRead)); - } - - if ( updateCrc ) { - update.OutEntry.Crc = crc.Value; - } - } - - int FindExistingUpdate(ZipEntry entry) - { - int result = -1; - string convertedName = GetTransformedFileName(entry.Name); - - if (updateIndex_.ContainsKey(convertedName)) { - result = (int)updateIndex_[convertedName]; - } + transform.TransformDirectory(name) : + name; + } + + /// + /// Get a raw memory buffer. + /// + /// Returns a raw memory buffer. + byte[] GetBuffer() + { + if ( copyBuffer_ == null ) { + copyBuffer_ = new byte[bufferSize_]; + } + return copyBuffer_; + } + + void CopyDescriptorBytes(ZipUpdate update, Stream dest, Stream source) + { + int bytesToCopy = GetDescriptorSize(update); + + if ( bytesToCopy > 0 ) { + byte[] buffer = GetBuffer(); + + while ( bytesToCopy > 0 ) { + int readSize = Math.Min(buffer.Length, bytesToCopy); + + int bytesRead = source.Read(buffer, 0, readSize); + if ( bytesRead > 0 ) { + dest.Write(buffer, 0, bytesRead); + bytesToCopy -= bytesRead; + } + else { + throw new ZipException("Unxpected end of stream"); + } + } + } + } + + void CopyBytes(ZipUpdate update, Stream destination, Stream source, + long bytesToCopy, bool updateCrc) + { + if ( destination == source ) { + throw new InvalidOperationException("Destination and source are the same"); + } + + // NOTE: Compressed size is updated elsewhere. + Crc32 crc = new Crc32(); + byte[] buffer = GetBuffer(); + + long targetBytes = bytesToCopy; + long totalBytesRead = 0; + + int bytesRead; + do { + int readSize = buffer.Length; + + if ( bytesToCopy < readSize ) { + readSize = (int)bytesToCopy; + } + + bytesRead = source.Read(buffer, 0, readSize); + if ( bytesRead > 0 ) { + if ( updateCrc ) { + crc.Update(buffer, 0, bytesRead); + } + destination.Write(buffer, 0, bytesRead); + bytesToCopy -= bytesRead; + totalBytesRead += bytesRead; + } + } + while ( (bytesRead > 0) && (bytesToCopy > 0) ); + + if ( totalBytesRead != targetBytes ) { + throw new ZipException(string.Format("Failed to copy bytes expected {0} read {1}", targetBytes, totalBytesRead)); + } + + if ( updateCrc ) { + update.OutEntry.Crc = crc.Value; + } + } + + /// + /// Get the size of the source descriptor for a . + /// + /// The update to get the size for. + /// The descriptor size, zero if there isnt one. + int GetDescriptorSize(ZipUpdate update) + { + int result = 0; + if ( (update.Entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) { + result = ZipConstants.DataDescriptorSize - 4; + if ( update.Entry.LocalHeaderRequiresZip64 ) { + result = ZipConstants.Zip64DataDescriptorSize - 4; + } + } + return result; + } + + void CopyDescriptorBytesDirect(ZipUpdate update, Stream stream, ref long destinationPosition, long sourcePosition) + { + int bytesToCopy = GetDescriptorSize(update); + + while ( bytesToCopy > 0 ) { + int readSize = (int)bytesToCopy; + byte[] buffer = GetBuffer(); + + stream.Position = sourcePosition; + int bytesRead = stream.Read(buffer, 0, readSize); + if ( bytesRead > 0 ) { + stream.Position = destinationPosition; + stream.Write(buffer, 0, bytesRead); + bytesToCopy -= bytesRead; + destinationPosition += bytesRead; + sourcePosition += bytesRead; + } + else { + throw new ZipException("Unxpected end of stream"); + } + } + } + + void CopyEntryDataDirect(ZipUpdate update, Stream stream, bool updateCrc, ref long destinationPosition, ref long sourcePosition) + { + long bytesToCopy = update.Entry.CompressedSize; + + // NOTE: Compressed size is updated elsewhere. + Crc32 crc = new Crc32(); + byte[] buffer = GetBuffer(); + + long targetBytes = bytesToCopy; + long totalBytesRead = 0; + + int bytesRead; + do + { + int readSize = buffer.Length; + + if ( bytesToCopy < readSize ) { + readSize = (int)bytesToCopy; + } + + stream.Position = sourcePosition; + bytesRead = stream.Read(buffer, 0, readSize); + if ( bytesRead > 0 ) { + if ( updateCrc ) { + crc.Update(buffer, 0, bytesRead); + } + stream.Position = destinationPosition; + stream.Write(buffer, 0, bytesRead); + + destinationPosition += bytesRead; + sourcePosition += bytesRead; + bytesToCopy -= bytesRead; + totalBytesRead += bytesRead; + } + } + while ( (bytesRead > 0) && (bytesToCopy > 0) ); + + if ( totalBytesRead != targetBytes ) { + throw new ZipException(string.Format("Failed to copy bytes expected {0} read {1}", targetBytes, totalBytesRead)); + } + + if ( updateCrc ) { + update.OutEntry.Crc = crc.Value; + } + } + + int FindExistingUpdate(ZipEntry entry) + { + int result = -1; + string convertedName = GetTransformedFileName(entry.Name); + + if (updateIndex_.ContainsKey(convertedName)) { + result = (int)updateIndex_[convertedName]; + } /* - // This is slow like the coming of the next ice age but takes less storage and may be useful - // for CF? - for (int index = 0; index < updates_.Count; ++index) - { - ZipUpdate zu = ( ZipUpdate )updates_[index]; - if ( (zu.Entry.ZipFileIndex == entry.ZipFileIndex) && - (string.Compare(convertedName, zu.Entry.Name, true, CultureInfo.InvariantCulture) == 0) ) { - result = index; - break; - } - } + // This is slow like the coming of the next ice age but takes less storage and may be useful + // for CF? + for (int index = 0; index < updates_.Count; ++index) + { + ZipUpdate zu = ( ZipUpdate )updates_[index]; + if ( (zu.Entry.ZipFileIndex == entry.ZipFileIndex) && + (string.Compare(convertedName, zu.Entry.Name, true, CultureInfo.InvariantCulture) == 0) ) { + result = index; + break; + } + } */ - return result; - } + return result; + } - int FindExistingUpdate(string fileName) - { - int result = -1; + int FindExistingUpdate(string fileName) + { + int result = -1; - string convertedName = GetTransformedFileName(fileName); + string convertedName = GetTransformedFileName(fileName); - if (updateIndex_.ContainsKey(convertedName)) { - result = (int)updateIndex_[convertedName]; - } + if (updateIndex_.ContainsKey(convertedName)) { + result = (int)updateIndex_[convertedName]; + } /* - // This is slow like the coming of the next ice age but takes less storage and may be useful - // for CF? - for ( int index = 0; index < updates_.Count; ++index ) { - if ( string.Compare(convertedName, (( ZipUpdate )updates_[index]).Entry.Name, - true, CultureInfo.InvariantCulture) == 0 ) { - result = index; - break; - } - } + // This is slow like the coming of the next ice age but takes less storage and may be useful + // for CF? + for ( int index = 0; index < updates_.Count; ++index ) { + if ( string.Compare(convertedName, (( ZipUpdate )updates_[index]).Entry.Name, + true, CultureInfo.InvariantCulture) == 0 ) { + result = index; + break; + } + } */ - return result; - } + return result; + } - /// - /// Get an output stream for the specified - /// - /// The entry to get an output stream for. - /// The output stream obtained for the entry. - Stream GetOutputStream(ZipEntry entry) - { - Stream result = baseStream_; + /// + /// Get an output stream for the specified + /// + /// The entry to get an output stream for. + /// The output stream obtained for the entry. + Stream GetOutputStream(ZipEntry entry) + { + Stream result = baseStream_; - if ( entry.IsCrypted == true ) { + if ( entry.IsCrypted == true ) { #if NETCF_1_0 - throw new ZipException("Encryption not supported for Compact Framework 1.0"); + throw new ZipException("Encryption not supported for Compact Framework 1.0"); #else - result = CreateAndInitEncryptionStream(result, entry); + result = CreateAndInitEncryptionStream(result, entry); #endif - } - - switch ( entry.CompressionMethod ) { - case CompressionMethod.Stored: - result = new UncompressedStream(result); - break; - - case CompressionMethod.Deflated: - DeflaterOutputStream dos = new DeflaterOutputStream(result, new Deflater(9, true)); - dos.IsStreamOwner = false; - result = dos; - break; - - default: - throw new ZipException("Unknown compression method " + entry.CompressionMethod); - } - return result; - } - - void AddEntry(ZipFile workFile, ZipUpdate update) - { - Stream source = null; - - if ( update.Entry.IsFile ) { - source = update.GetSource(); - - if ( source == null ) { - source = updateDataSource_.GetSource(update.Entry, update.Filename); - } - } - - if ( source != null ) { - using ( source ) { - long sourceStreamLength = source.Length; - if ( update.OutEntry.Size < 0 ) { - update.OutEntry.Size = sourceStreamLength; - } - else { - // Check for errant entries. - if ( update.OutEntry.Size != sourceStreamLength ) { - throw new ZipException("Entry size/stream size mismatch"); - } - } - - workFile.WriteLocalEntryHeader(update); - - long dataStart = workFile.baseStream_.Position; - - using ( Stream output = workFile.GetOutputStream(update.OutEntry) ) { - CopyBytes(update, output, source, sourceStreamLength, true); - } - - long dataEnd = workFile.baseStream_.Position; - update.OutEntry.CompressedSize = dataEnd - dataStart; - - if ((update.OutEntry.Flags & (int)GeneralBitFlags.Descriptor) == (int)GeneralBitFlags.Descriptor) - { - ZipHelperStream helper = new ZipHelperStream(workFile.baseStream_); - helper.WriteDataDescriptor(update.OutEntry); - } - } - } - else { - workFile.WriteLocalEntryHeader(update); - update.OutEntry.CompressedSize = 0; - } - - } - - void ModifyEntry(ZipFile workFile, ZipUpdate update) - { - workFile.WriteLocalEntryHeader(update); - long dataStart = workFile.baseStream_.Position; - - // TODO: This is slow if the changes don't effect the data!! - if ( update.Entry.IsFile && (update.Filename != null) ) { - using ( Stream output = workFile.GetOutputStream(update.OutEntry) ) { - using ( Stream source = this.GetInputStream(update.Entry) ) { - CopyBytes(update, output, source, source.Length, true); - } - } - } - - long dataEnd = workFile.baseStream_.Position; - update.Entry.CompressedSize = dataEnd - dataStart; - } - - void CopyEntryDirect(ZipFile workFile, ZipUpdate update, ref long destinationPosition) - { - bool skipOver = false; - if ( update.Entry.Offset == destinationPosition ) { - skipOver = true; - } - - if ( !skipOver ) { - baseStream_.Position = destinationPosition; - workFile.WriteLocalEntryHeader(update); - destinationPosition = baseStream_.Position; - } - - long sourcePosition = 0; - - const int NameLengthOffset = 26; - - // TODO: Add base for SFX friendly handling - long entryDataOffset = update.Entry.Offset + NameLengthOffset; - - baseStream_.Seek(entryDataOffset, SeekOrigin.Begin); - - // Clumsy way of handling retrieving the original name and extra data length for now. - // TODO: Stop re-reading name and data length in CopyEntryDirect. - uint nameLength = ReadLEUshort(); - uint extraLength = ReadLEUshort(); - - sourcePosition = baseStream_.Position + nameLength + extraLength; - - if (skipOver) { - if (update.OffsetBasedSize != -1) - destinationPosition += update.OffsetBasedSize; - else - // TODO: Find out why this calculation comes up 4 bytes short on some entries in ODT (Office Document Text) archives. - // WinZip produces a warning on these entries: - // "caution: value of lrec.csize (compressed size) changed from ..." - destinationPosition += - (sourcePosition - entryDataOffset) + NameLengthOffset + // Header size - update.Entry.CompressedSize + GetDescriptorSize(update); - } - else { - if ( update.Entry.CompressedSize > 0 ) { - CopyEntryDataDirect(update, baseStream_, false, ref destinationPosition, ref sourcePosition ); - } - CopyDescriptorBytesDirect(update, baseStream_, ref destinationPosition, sourcePosition); - } - } - - void CopyEntry(ZipFile workFile, ZipUpdate update) - { - workFile.WriteLocalEntryHeader(update); - - if ( update.Entry.CompressedSize > 0 ) { - const int NameLengthOffset = 26; - - long entryDataOffset = update.Entry.Offset + NameLengthOffset; - - // TODO: This wont work for SFX files! - baseStream_.Seek(entryDataOffset, SeekOrigin.Begin); - - uint nameLength = ReadLEUshort(); - uint extraLength = ReadLEUshort(); - - baseStream_.Seek(nameLength + extraLength, SeekOrigin.Current); - - CopyBytes(update, workFile.baseStream_, baseStream_, update.Entry.CompressedSize, false); - } - CopyDescriptorBytes(update, workFile.baseStream_, baseStream_); - } - - void Reopen(Stream source) - { - if ( source == null ) { - throw new ZipException("Failed to reopen archive - no source"); - } - - isNewArchive_ = false; - baseStream_ = source; - ReadEntries(); - } - - void Reopen() - { - if (Name == null) { - throw new InvalidOperationException("Name is not known cannot Reopen"); - } - - Reopen(File.Open(Name, FileMode.Open, FileAccess.Read, FileShare.Read)); - } - - void UpdateCommentOnly() - { - long baseLength = baseStream_.Length; - - ZipHelperStream updateFile = null; - - if ( archiveStorage_.UpdateMode == FileUpdateMode.Safe ) { - Stream copyStream = archiveStorage_.MakeTemporaryCopy(baseStream_); - updateFile = new ZipHelperStream(copyStream); - updateFile.IsStreamOwner = true; - - baseStream_.Close(); - baseStream_ = null; - } - else { - if (archiveStorage_.UpdateMode == FileUpdateMode.Direct) { - // TODO: archiveStorage wasnt originally intended for this use. - // Need to revisit this to tidy up handling as archive storage currently doesnt - // handle the original stream well. - // The problem is when using an existing zip archive with an in memory archive storage. - // The open stream wont support writing but the memory storage should open the same file not an in memory one. - - // Need to tidy up the archive storage interface and contract basically. - baseStream_ = archiveStorage_.OpenForDirectUpdate(baseStream_); - updateFile = new ZipHelperStream(baseStream_); - } - else { - baseStream_.Close(); - baseStream_ = null; - updateFile = new ZipHelperStream(Name); - } - } - - using ( updateFile ) { - long locatedCentralDirOffset = - updateFile.LocateBlockWithSignature(ZipConstants.EndOfCentralDirectorySignature, - baseLength, ZipConstants.EndOfCentralRecordBaseSize, 0xffff); - if ( locatedCentralDirOffset < 0 ) { - throw new ZipException("Cannot find central directory"); - } - - const int CentralHeaderCommentSizeOffset = 16; - updateFile.Position += CentralHeaderCommentSizeOffset; - - byte[] rawComment = newComment_.RawComment; - - updateFile.WriteLEShort(rawComment.Length); - updateFile.Write(rawComment, 0, rawComment.Length); - updateFile.SetLength(updateFile.Position); - } - - if ( archiveStorage_.UpdateMode == FileUpdateMode.Safe ) { - Reopen(archiveStorage_.ConvertTemporaryToFinal()); - } - else { - ReadEntries(); - } - } - - /// - /// Class used to sort updates. - /// - class UpdateComparer : IComparer - { - /// - /// Compares two objects and returns a value indicating whether one is - /// less than, equal to or greater than the other. - /// - /// First object to compare - /// Second object to compare. - /// Compare result. - public int Compare( - object x, - object y) - { - ZipUpdate zx = x as ZipUpdate; - ZipUpdate zy = y as ZipUpdate; - - int result; - - if (zx == null) { - if (zy == null) { - result = 0; - } - else { - result = -1; - } - } - else if (zy == null) { - result = 1; - } - else { - int xCmdValue = ((zx.Command == UpdateCommand.Copy) || (zx.Command == UpdateCommand.Modify)) ? 0 : 1; - int yCmdValue = ((zy.Command == UpdateCommand.Copy) || (zy.Command == UpdateCommand.Modify)) ? 0 : 1; - - result = xCmdValue - yCmdValue; - if (result == 0) { - long offsetDiff = zx.Entry.Offset - zy.Entry.Offset; - if (offsetDiff < 0) { - result = -1; - } - else if (offsetDiff == 0) { - result = 0; - } - else { - result = 1; - } - } - } - return result; - } - } - - void RunUpdates() - { - long sizeEntries = 0; - long endOfStream = 0; - bool directUpdate = false; - long destinationPosition = 0; // NOT SFX friendly - - ZipFile workFile; - - if ( IsNewArchive ) { - workFile = this; - workFile.baseStream_.Position = 0; - directUpdate = true; - } - else if ( archiveStorage_.UpdateMode == FileUpdateMode.Direct ) { - workFile = this; - workFile.baseStream_.Position = 0; - directUpdate = true; - - // Sort the updates by offset within copies/modifies, then adds. - // This ensures that data required by copies will not be overwritten. - updates_.Sort(new UpdateComparer()); - } - else { - workFile = ZipFile.Create(archiveStorage_.GetTemporaryOutput()); - workFile.UseZip64 = UseZip64; - - if (key != null) { - workFile.key = (byte[])key.Clone(); - } - } - - try { - foreach ( ZipUpdate update in updates_ ) { - if (update != null) { - switch (update.Command) { - case UpdateCommand.Copy: - if (directUpdate) { - CopyEntryDirect(workFile, update, ref destinationPosition); - } - else { - CopyEntry(workFile, update); - } - break; - - case UpdateCommand.Modify: - // TODO: Direct modifying of an entry will take some legwork. - ModifyEntry(workFile, update); - break; - - case UpdateCommand.Add: - if (!IsNewArchive && directUpdate) { - workFile.baseStream_.Position = destinationPosition; - } - - AddEntry(workFile, update); - - if (directUpdate) { - destinationPosition = workFile.baseStream_.Position; - } - break; - } - } - } - - if ( !IsNewArchive && directUpdate ) { - workFile.baseStream_.Position = destinationPosition; - } - - long centralDirOffset = workFile.baseStream_.Position; - - foreach ( ZipUpdate update in updates_ ) { - if (update != null) { - sizeEntries += workFile.WriteCentralDirectoryHeader(update.OutEntry); - } - } - - byte[] theComment = (newComment_ != null) ? newComment_.RawComment : ZipConstants.ConvertToArray(comment_); - using ( ZipHelperStream zhs = new ZipHelperStream(workFile.baseStream_) ) { - zhs.WriteEndOfCentralDirectory(updateCount_, sizeEntries, centralDirOffset, theComment); - } - - endOfStream = workFile.baseStream_.Position; - - // And now patch entries... - foreach ( ZipUpdate update in updates_ ) { - if (update != null) - { - // If the size of the entry is zero leave the crc as 0 as well. - // The calculated crc will be all bits on... - if ((update.CrcPatchOffset > 0) && (update.OutEntry.CompressedSize > 0)) { - workFile.baseStream_.Position = update.CrcPatchOffset; - workFile.WriteLEInt((int)update.OutEntry.Crc); - } - - if (update.SizePatchOffset > 0) { - workFile.baseStream_.Position = update.SizePatchOffset; - if (update.OutEntry.LocalHeaderRequiresZip64) { - workFile.WriteLeLong(update.OutEntry.Size); - workFile.WriteLeLong(update.OutEntry.CompressedSize); - } - else { - workFile.WriteLEInt((int)update.OutEntry.CompressedSize); - workFile.WriteLEInt((int)update.OutEntry.Size); - } - } - } - } - } - catch { - workFile.Close(); - if (!directUpdate && (workFile.Name != null)) { - File.Delete(workFile.Name); - } - throw; - } - - if (directUpdate) { - workFile.baseStream_.SetLength(endOfStream); - workFile.baseStream_.Flush(); - isNewArchive_ = false; - ReadEntries(); - } - else { - baseStream_.Close(); - Reopen(archiveStorage_.ConvertTemporaryToFinal()); - } - } - - void CheckUpdating() - { - if ( updates_ == null ) { - throw new InvalidOperationException("BeginUpdate has not been called"); - } - } - - #endregion - - #region ZipUpdate class - /// - /// Represents a pending update to a Zip file. - /// - class ZipUpdate - { - #region Constructors - public ZipUpdate(string fileName, ZipEntry entry) - { - command_ = UpdateCommand.Add; - entry_ = entry; - filename_ = fileName; - } - - [Obsolete] - public ZipUpdate(string fileName, string entryName, CompressionMethod compressionMethod) - { - command_ = UpdateCommand.Add; - entry_ = new ZipEntry(entryName); - entry_.CompressionMethod = compressionMethod; - filename_ = fileName; - } - - [Obsolete] - public ZipUpdate(string fileName, string entryName) - : this(fileName, entryName, CompressionMethod.Deflated) - { - // Do nothing. - } - - [Obsolete] - public ZipUpdate(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod) - { - command_ = UpdateCommand.Add; - entry_ = new ZipEntry(entryName); - entry_.CompressionMethod = compressionMethod; - dataSource_ = dataSource; - } - - public ZipUpdate(IStaticDataSource dataSource, ZipEntry entry) - { - command_ = UpdateCommand.Add; - entry_ = entry; - dataSource_ = dataSource; - } - - public ZipUpdate(ZipEntry original, ZipEntry updated) - { - throw new ZipException("Modify not currently supported"); - /* - command_ = UpdateCommand.Modify; - entry_ = ( ZipEntry )original.Clone(); - outEntry_ = ( ZipEntry )updated.Clone(); - */ - } - - public ZipUpdate(UpdateCommand command, ZipEntry entry) - { - command_ = command; - entry_ = ( ZipEntry )entry.Clone(); - } - - - /// - /// Copy an existing entry. - /// - /// The existing entry to copy. - public ZipUpdate(ZipEntry entry) - : this(UpdateCommand.Copy, entry) - { - // Do nothing. - } - #endregion - - /// - /// Get the for this update. - /// - /// This is the source or original entry. - public ZipEntry Entry - { - get { return entry_; } - } - - /// - /// Get the that will be written to the updated/new file. - /// - public ZipEntry OutEntry - { - get { - if ( outEntry_ == null ) { - outEntry_ = (ZipEntry)entry_.Clone(); - } - - return outEntry_; - } - } - - /// - /// Get the command for this update. - /// - public UpdateCommand Command - { - get { return command_; } - } - - /// - /// Get the filename if any for this update. Null if none exists. - /// - public string Filename - { - get { return filename_; } - } - - /// - /// Get/set the location of the size patch for this update. - /// - public long SizePatchOffset - { - get { return sizePatchOffset_; } - set { sizePatchOffset_ = value; } - } - - /// - /// Get /set the location of the crc patch for this update. - /// - public long CrcPatchOffset - { - get { return crcPatchOffset_; } - set { crcPatchOffset_ = value; } - } - - /// - /// Get/set the size calculated by offset. - /// Specifically, the difference between this and next entry's starting offset. - /// - public long OffsetBasedSize - { - get { return _offsetBasedSize; } - set { _offsetBasedSize = value; } - } - - public Stream GetSource() - { - Stream result = null; - if ( dataSource_ != null ) { - result = dataSource_.GetSource(); - } - - return result; - } - - #region Instance Fields - ZipEntry entry_; - ZipEntry outEntry_; - UpdateCommand command_; - IStaticDataSource dataSource_; - string filename_; - long sizePatchOffset_ = -1; - long crcPatchOffset_ = -1; - long _offsetBasedSize = -1; - #endregion - } - - #endregion - #endregion - - #region Disposing - - #region IDisposable Members - void IDisposable.Dispose() - { - Close(); - } - #endregion - - void DisposeInternal(bool disposing) - { - if ( !isDisposed_ ) { - isDisposed_ = true; - entries_ = new ZipEntry[0]; - - if ( IsStreamOwner && (baseStream_ != null) ) { - lock(baseStream_) { - baseStream_.Close(); - } - } - - PostUpdateCleanup(); - } - } - - /// - /// Releases the unmanaged resources used by the this instance and optionally releases the managed resources. - /// - /// true to release both managed and unmanaged resources; - /// false to release only unmanaged resources. - protected virtual void Dispose(bool disposing) - { - DisposeInternal(disposing); - } - - #endregion - - #region Internal routines - #region Reading - /// - /// Read an unsigned short in little endian byte order. - /// - /// Returns the value read. - /// - /// The stream ends prematurely - /// - ushort ReadLEUshort() - { - int data1 = baseStream_.ReadByte(); - - if ( data1 < 0 ) { - throw new EndOfStreamException("End of stream"); - } - - int data2 = baseStream_.ReadByte(); - - if ( data2 < 0 ) { - throw new EndOfStreamException("End of stream"); - } - - - return unchecked((ushort)((ushort)data1 | (ushort)(data2 << 8))); - } - - /// - /// Read a uint in little endian byte order. - /// - /// Returns the value read. - /// - /// An i/o error occurs. - /// - /// - /// The file ends prematurely - /// - uint ReadLEUint() - { - return (uint)(ReadLEUshort() | (ReadLEUshort() << 16)); - } - - ulong ReadLEUlong() - { - return ReadLEUint() | ((ulong)ReadLEUint() << 32); - } - - #endregion - // NOTE this returns the offset of the first byte after the signature. - long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) - { - using ( ZipHelperStream les = new ZipHelperStream(baseStream_) ) { - return les.LocateBlockWithSignature(signature, endLocation, minimumBlockSize, maximumVariableData); - } - } - - /// - /// Search for and read the central directory of a zip file filling the entries array. - /// - /// - /// An i/o error occurs. - /// - /// - /// The central directory is malformed or cannot be found - /// - void ReadEntries() - { - // Search for the End Of Central Directory. When a zip comment is - // present the directory will start earlier - // - // The search is limited to 64K which is the maximum size of a trailing comment field to aid speed. - // This should be compatible with both SFX and ZIP files but has only been tested for Zip files - // If a SFX file has the Zip data attached as a resource and there are other resources occuring later then - // this could be invalid. - // Could also speed this up by reading memory in larger blocks. - - if (baseStream_.CanSeek == false) { - throw new ZipException("ZipFile stream must be seekable"); - } - - long locatedEndOfCentralDir = LocateBlockWithSignature(ZipConstants.EndOfCentralDirectorySignature, - baseStream_.Length, ZipConstants.EndOfCentralRecordBaseSize, 0xffff); - - if (locatedEndOfCentralDir < 0) { - throw new ZipException("Cannot find central directory"); - } - - // Read end of central directory record - ushort thisDiskNumber = ReadLEUshort(); - ushort startCentralDirDisk = ReadLEUshort(); - ulong entriesForThisDisk = ReadLEUshort(); - ulong entriesForWholeCentralDir = ReadLEUshort(); - ulong centralDirSize = ReadLEUint(); - long offsetOfCentralDir = ReadLEUint(); - uint commentSize = ReadLEUshort(); - - if ( commentSize > 0 ) { - byte[] comment = new byte[commentSize]; - - StreamUtils.ReadFully(baseStream_, comment); - comment_ = ZipConstants.ConvertToString(comment); - } - else { - comment_ = string.Empty; - } - - bool isZip64 = false; - - // Check if zip64 header information is required. - if ( (thisDiskNumber == 0xffff) || - (startCentralDirDisk == 0xffff) || - (entriesForThisDisk == 0xffff) || - (entriesForWholeCentralDir == 0xffff) || - (centralDirSize == 0xffffffff) || - (offsetOfCentralDir == 0xffffffff) ) { - isZip64 = true; - - long offset = LocateBlockWithSignature(ZipConstants.Zip64CentralDirLocatorSignature, locatedEndOfCentralDir, 0, 0x1000); - if ( offset < 0 ) { - throw new ZipException("Cannot find Zip64 locator"); - } - - // number of the disk with the start of the zip64 end of central directory 4 bytes - // relative offset of the zip64 end of central directory record 8 bytes - // total number of disks 4 bytes - ReadLEUint(); // startDisk64 is not currently used - ulong offset64 = ReadLEUlong(); - uint totalDisks = ReadLEUint(); - - baseStream_.Position = (long)offset64; - long sig64 = ReadLEUint(); - - if ( sig64 != ZipConstants.Zip64CentralFileHeaderSignature ) { - throw new ZipException(string.Format("Invalid Zip64 Central directory signature at {0:X}", offset64)); - } - - // NOTE: Record size = SizeOfFixedFields + SizeOfVariableData - 12. - ulong recordSize = ReadLEUlong(); - int versionMadeBy = ReadLEUshort(); - int versionToExtract = ReadLEUshort(); - uint thisDisk = ReadLEUint(); - uint centralDirDisk = ReadLEUint(); - entriesForThisDisk = ReadLEUlong(); - entriesForWholeCentralDir = ReadLEUlong(); - centralDirSize = ReadLEUlong(); - offsetOfCentralDir = (long)ReadLEUlong(); - - // NOTE: zip64 extensible data sector (variable size) is ignored. - } - - entries_ = new ZipEntry[entriesForThisDisk]; - - // SFX/embedded support, find the offset of the first entry vis the start of the stream - // This applies to Zip files that are appended to the end of an SFX stub. - // Or are appended as a resource to an executable. - // Zip files created by some archivers have the offsets altered to reflect the true offsets - // and so dont require any adjustment here... - // TODO: Difficulty with Zip64 and SFX offset handling needs resolution - maths? - if ( !isZip64 && (offsetOfCentralDir < locatedEndOfCentralDir - (4 + (long)centralDirSize)) ) { - offsetOfFirstEntry = locatedEndOfCentralDir - (4 + (long)centralDirSize + offsetOfCentralDir); - if (offsetOfFirstEntry <= 0) { - throw new ZipException("Invalid embedded zip archive"); - } - } - - baseStream_.Seek(offsetOfFirstEntry + offsetOfCentralDir, SeekOrigin.Begin); - - for (ulong i = 0; i < entriesForThisDisk; i++) { - if (ReadLEUint() != ZipConstants.CentralHeaderSignature) { - throw new ZipException("Wrong Central Directory signature"); - } - - int versionMadeBy = ReadLEUshort(); - int versionToExtract = ReadLEUshort(); - int bitFlags = ReadLEUshort(); - int method = ReadLEUshort(); - uint dostime = ReadLEUint(); - uint crc = ReadLEUint(); - long csize = (long)ReadLEUint(); - long size = (long)ReadLEUint(); - int nameLen = ReadLEUshort(); - int extraLen = ReadLEUshort(); - int commentLen = ReadLEUshort(); - - int diskStartNo = ReadLEUshort(); // Not currently used - int internalAttributes = ReadLEUshort(); // Not currently used - - uint externalAttributes = ReadLEUint(); - long offset = ReadLEUint(); - - byte[] buffer = new byte[Math.Max(nameLen, commentLen)]; - - StreamUtils.ReadFully(baseStream_, buffer, 0, nameLen); - string name = ZipConstants.ConvertToStringExt(bitFlags, buffer, nameLen); - - ZipEntry entry = new ZipEntry(name, versionToExtract, versionMadeBy, (CompressionMethod)method); - entry.Crc = crc & 0xffffffffL; - entry.Size = size & 0xffffffffL; - entry.CompressedSize = csize & 0xffffffffL; - entry.Flags = bitFlags; - entry.DosTime = (uint)dostime; - entry.ZipFileIndex = (long)i; - entry.Offset = offset; - entry.ExternalFileAttributes = (int)externalAttributes; - - if ((bitFlags & 8) == 0) { - entry.CryptoCheckValue = (byte)(crc >> 24); - } - else { - entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff); - } - - if (extraLen > 0) { - byte[] extra = new byte[extraLen]; - StreamUtils.ReadFully(baseStream_, extra); - entry.ExtraData = extra; - } - - entry.ProcessExtraData(false); - - if (commentLen > 0) { - StreamUtils.ReadFully(baseStream_, buffer, 0, commentLen); - entry.Comment = ZipConstants.ConvertToStringExt(bitFlags, buffer, commentLen); - } - - entries_[i] = entry; - } - } - - /// - /// Locate the data for a given entry. - /// - /// - /// The start offset of the data. - /// - /// - /// The stream ends prematurely - /// - /// - /// The local header signature is invalid, the entry and central header file name lengths are different - /// or the local and entry compression methods dont match - /// - long LocateEntry(ZipEntry entry) - { - return TestLocalHeader(entry, HeaderTest.Extract); - } - -#if !NETCF_1_0 - Stream CreateAndInitDecryptionStream(Stream baseStream, ZipEntry entry) - { - CryptoStream result = null; - - if ( (entry.Version < ZipConstants.VersionStrongEncryption) - || (entry.Flags & (int)GeneralBitFlags.StrongEncryption) == 0) { - PkzipClassicManaged classicManaged = new PkzipClassicManaged(); - - OnKeysRequired(entry.Name); - if (HaveKeys == false) { - throw new ZipException("No password available for encrypted stream"); - } - - result = new CryptoStream(baseStream, classicManaged.CreateDecryptor(key, null), CryptoStreamMode.Read); - CheckClassicPassword(result, entry); - } - else { + } + + switch ( entry.CompressionMethod ) { + case CompressionMethod.Stored: + result = new UncompressedStream(result); + break; + + case CompressionMethod.Deflated: + DeflaterOutputStream dos = new DeflaterOutputStream(result, new Deflater(9, true)); + dos.IsStreamOwner = false; + result = dos; + break; + + default: + throw new ZipException("Unknown compression method " + entry.CompressionMethod); + } + return result; + } + + void AddEntry(ZipFile workFile, ZipUpdate update) + { + Stream source = null; + + if ( update.Entry.IsFile ) { + source = update.GetSource(); + + if ( source == null ) { + source = updateDataSource_.GetSource(update.Entry, update.Filename); + } + } + + if ( source != null ) { + using ( source ) { + long sourceStreamLength = source.Length; + if ( update.OutEntry.Size < 0 ) { + update.OutEntry.Size = sourceStreamLength; + } + else { + // Check for errant entries. + if ( update.OutEntry.Size != sourceStreamLength ) { + throw new ZipException("Entry size/stream size mismatch"); + } + } + + workFile.WriteLocalEntryHeader(update); + + long dataStart = workFile.baseStream_.Position; + + using ( Stream output = workFile.GetOutputStream(update.OutEntry) ) { + CopyBytes(update, output, source, sourceStreamLength, true); + } + + long dataEnd = workFile.baseStream_.Position; + update.OutEntry.CompressedSize = dataEnd - dataStart; + + if ((update.OutEntry.Flags & (int)GeneralBitFlags.Descriptor) == (int)GeneralBitFlags.Descriptor) + { + ZipHelperStream helper = new ZipHelperStream(workFile.baseStream_); + helper.WriteDataDescriptor(update.OutEntry); + } + } + } + else { + workFile.WriteLocalEntryHeader(update); + update.OutEntry.CompressedSize = 0; + } + + } + + void ModifyEntry(ZipFile workFile, ZipUpdate update) + { + workFile.WriteLocalEntryHeader(update); + long dataStart = workFile.baseStream_.Position; + + // TODO: This is slow if the changes don't effect the data!! + if ( update.Entry.IsFile && (update.Filename != null) ) { + using ( Stream output = workFile.GetOutputStream(update.OutEntry) ) { + using ( Stream source = this.GetInputStream(update.Entry) ) { + CopyBytes(update, output, source, source.Length, true); + } + } + } + + long dataEnd = workFile.baseStream_.Position; + update.Entry.CompressedSize = dataEnd - dataStart; + } + + void CopyEntryDirect(ZipFile workFile, ZipUpdate update, ref long destinationPosition) + { + bool skipOver = false; + if ( update.Entry.Offset == destinationPosition ) { + skipOver = true; + } + + if ( !skipOver ) { + baseStream_.Position = destinationPosition; + workFile.WriteLocalEntryHeader(update); + destinationPosition = baseStream_.Position; + } + + long sourcePosition = 0; + + const int NameLengthOffset = 26; + + // TODO: Add base for SFX friendly handling + long entryDataOffset = update.Entry.Offset + NameLengthOffset; + + baseStream_.Seek(entryDataOffset, SeekOrigin.Begin); + + // Clumsy way of handling retrieving the original name and extra data length for now. + // TODO: Stop re-reading name and data length in CopyEntryDirect. + uint nameLength = ReadLEUshort(); + uint extraLength = ReadLEUshort(); + + sourcePosition = baseStream_.Position + nameLength + extraLength; + + if (skipOver) { + if (update.OffsetBasedSize != -1) + destinationPosition += update.OffsetBasedSize; + else + // TODO: Find out why this calculation comes up 4 bytes short on some entries in ODT (Office Document Text) archives. + // WinZip produces a warning on these entries: + // "caution: value of lrec.csize (compressed size) changed from ..." + destinationPosition += + (sourcePosition - entryDataOffset) + NameLengthOffset + // Header size + update.Entry.CompressedSize + GetDescriptorSize(update); + } + else { + if ( update.Entry.CompressedSize > 0 ) { + CopyEntryDataDirect(update, baseStream_, false, ref destinationPosition, ref sourcePosition ); + } + CopyDescriptorBytesDirect(update, baseStream_, ref destinationPosition, sourcePosition); + } + } + + void CopyEntry(ZipFile workFile, ZipUpdate update) + { + workFile.WriteLocalEntryHeader(update); + + if ( update.Entry.CompressedSize > 0 ) { + const int NameLengthOffset = 26; + + long entryDataOffset = update.Entry.Offset + NameLengthOffset; + + // TODO: This wont work for SFX files! + baseStream_.Seek(entryDataOffset, SeekOrigin.Begin); + + uint nameLength = ReadLEUshort(); + uint extraLength = ReadLEUshort(); + + baseStream_.Seek(nameLength + extraLength, SeekOrigin.Current); + + CopyBytes(update, workFile.baseStream_, baseStream_, update.Entry.CompressedSize, false); + } + CopyDescriptorBytes(update, workFile.baseStream_, baseStream_); + } + + void Reopen(Stream source) + { + if ( source == null ) { + throw new ZipException("Failed to reopen archive - no source"); + } + + isNewArchive_ = false; + baseStream_ = source; + ReadEntries(); + } + + void Reopen() + { + if (Name == null) { + throw new InvalidOperationException("Name is not known cannot Reopen"); + } + + Reopen(File.Open(Name, FileMode.Open, FileAccess.Read, FileShare.Read)); + } + + void UpdateCommentOnly() + { + long baseLength = baseStream_.Length; + + ZipHelperStream updateFile = null; + + if ( archiveStorage_.UpdateMode == FileUpdateMode.Safe ) { + Stream copyStream = archiveStorage_.MakeTemporaryCopy(baseStream_); + updateFile = new ZipHelperStream(copyStream); + updateFile.IsStreamOwner = true; + + baseStream_.Close(); + baseStream_ = null; + } + else { + if (archiveStorage_.UpdateMode == FileUpdateMode.Direct) { + // TODO: archiveStorage wasnt originally intended for this use. + // Need to revisit this to tidy up handling as archive storage currently doesnt + // handle the original stream well. + // The problem is when using an existing zip archive with an in memory archive storage. + // The open stream wont support writing but the memory storage should open the same file not an in memory one. + + // Need to tidy up the archive storage interface and contract basically. + baseStream_ = archiveStorage_.OpenForDirectUpdate(baseStream_); + updateFile = new ZipHelperStream(baseStream_); + } + else { + baseStream_.Close(); + baseStream_ = null; + updateFile = new ZipHelperStream(Name); + } + } + + using ( updateFile ) { + long locatedCentralDirOffset = + updateFile.LocateBlockWithSignature(ZipConstants.EndOfCentralDirectorySignature, + baseLength, ZipConstants.EndOfCentralRecordBaseSize, 0xffff); + if ( locatedCentralDirOffset < 0 ) { + throw new ZipException("Cannot find central directory"); + } + + const int CentralHeaderCommentSizeOffset = 16; + updateFile.Position += CentralHeaderCommentSizeOffset; + + byte[] rawComment = newComment_.RawComment; + + updateFile.WriteLEShort(rawComment.Length); + updateFile.Write(rawComment, 0, rawComment.Length); + updateFile.SetLength(updateFile.Position); + } + + if ( archiveStorage_.UpdateMode == FileUpdateMode.Safe ) { + Reopen(archiveStorage_.ConvertTemporaryToFinal()); + } + else { + ReadEntries(); + } + } + + /// + /// Class used to sort updates. + /// + class UpdateComparer : IComparer + { + /// + /// Compares two objects and returns a value indicating whether one is + /// less than, equal to or greater than the other. + /// + /// First object to compare + /// Second object to compare. + /// Compare result. + public int Compare( + object x, + object y) + { + ZipUpdate zx = x as ZipUpdate; + ZipUpdate zy = y as ZipUpdate; + + int result; + + if (zx == null) { + if (zy == null) { + result = 0; + } + else { + result = -1; + } + } + else if (zy == null) { + result = 1; + } + else { + int xCmdValue = ((zx.Command == UpdateCommand.Copy) || (zx.Command == UpdateCommand.Modify)) ? 0 : 1; + int yCmdValue = ((zy.Command == UpdateCommand.Copy) || (zy.Command == UpdateCommand.Modify)) ? 0 : 1; + + result = xCmdValue - yCmdValue; + if (result == 0) { + long offsetDiff = zx.Entry.Offset - zy.Entry.Offset; + if (offsetDiff < 0) { + result = -1; + } + else if (offsetDiff == 0) { + result = 0; + } + else { + result = 1; + } + } + } + return result; + } + } + + void RunUpdates() + { + long sizeEntries = 0; + long endOfStream = 0; + bool directUpdate = false; + long destinationPosition = 0; // NOT SFX friendly + + ZipFile workFile; + + if ( IsNewArchive ) { + workFile = this; + workFile.baseStream_.Position = 0; + directUpdate = true; + } + else if ( archiveStorage_.UpdateMode == FileUpdateMode.Direct ) { + workFile = this; + workFile.baseStream_.Position = 0; + directUpdate = true; + + // Sort the updates by offset within copies/modifies, then adds. + // This ensures that data required by copies will not be overwritten. + updates_.Sort(new UpdateComparer()); + } + else { + workFile = ZipFile.Create(archiveStorage_.GetTemporaryOutput()); + workFile.UseZip64 = UseZip64; + + if (key != null) { + workFile.key = (byte[])key.Clone(); + } + } + + try { + foreach ( ZipUpdate update in updates_ ) { + if (update != null) { + switch (update.Command) { + case UpdateCommand.Copy: + if (directUpdate) { + CopyEntryDirect(workFile, update, ref destinationPosition); + } + else { + CopyEntry(workFile, update); + } + break; + + case UpdateCommand.Modify: + // TODO: Direct modifying of an entry will take some legwork. + ModifyEntry(workFile, update); + break; + + case UpdateCommand.Add: + if (!IsNewArchive && directUpdate) { + workFile.baseStream_.Position = destinationPosition; + } + + AddEntry(workFile, update); + + if (directUpdate) { + destinationPosition = workFile.baseStream_.Position; + } + break; + } + } + } + + if ( !IsNewArchive && directUpdate ) { + workFile.baseStream_.Position = destinationPosition; + } + + long centralDirOffset = workFile.baseStream_.Position; + + foreach ( ZipUpdate update in updates_ ) { + if (update != null) { + sizeEntries += workFile.WriteCentralDirectoryHeader(update.OutEntry); + } + } + + byte[] theComment = (newComment_ != null) ? newComment_.RawComment : ZipConstants.ConvertToArray(comment_); + using ( ZipHelperStream zhs = new ZipHelperStream(workFile.baseStream_) ) { + zhs.WriteEndOfCentralDirectory(updateCount_, sizeEntries, centralDirOffset, theComment); + } + + endOfStream = workFile.baseStream_.Position; + + // And now patch entries... + foreach ( ZipUpdate update in updates_ ) { + if (update != null) + { + // If the size of the entry is zero leave the crc as 0 as well. + // The calculated crc will be all bits on... + if ((update.CrcPatchOffset > 0) && (update.OutEntry.CompressedSize > 0)) { + workFile.baseStream_.Position = update.CrcPatchOffset; + workFile.WriteLEInt((int)update.OutEntry.Crc); + } + + if (update.SizePatchOffset > 0) { + workFile.baseStream_.Position = update.SizePatchOffset; + if (update.OutEntry.LocalHeaderRequiresZip64) { + workFile.WriteLeLong(update.OutEntry.Size); + workFile.WriteLeLong(update.OutEntry.CompressedSize); + } + else { + workFile.WriteLEInt((int)update.OutEntry.CompressedSize); + workFile.WriteLEInt((int)update.OutEntry.Size); + } + } + } + } + } + catch { + workFile.Close(); + if (!directUpdate && (workFile.Name != null)) { + File.Delete(workFile.Name); + } + throw; + } + + if (directUpdate) { + workFile.baseStream_.SetLength(endOfStream); + workFile.baseStream_.Flush(); + isNewArchive_ = false; + ReadEntries(); + } + else { + baseStream_.Close(); + Reopen(archiveStorage_.ConvertTemporaryToFinal()); + } + } + + void CheckUpdating() + { + if ( updates_ == null ) { + throw new InvalidOperationException("BeginUpdate has not been called"); + } + } + + #endregion + + #region ZipUpdate class + /// + /// Represents a pending update to a Zip file. + /// + class ZipUpdate + { + #region Constructors + public ZipUpdate(string fileName, ZipEntry entry) + { + command_ = UpdateCommand.Add; + entry_ = entry; + filename_ = fileName; + } + + [Obsolete] + public ZipUpdate(string fileName, string entryName, CompressionMethod compressionMethod) + { + command_ = UpdateCommand.Add; + entry_ = new ZipEntry(entryName); + entry_.CompressionMethod = compressionMethod; + filename_ = fileName; + } + + [Obsolete] + public ZipUpdate(string fileName, string entryName) + : this(fileName, entryName, CompressionMethod.Deflated) + { + // Do nothing. + } + + [Obsolete] + public ZipUpdate(IStaticDataSource dataSource, string entryName, CompressionMethod compressionMethod) + { + command_ = UpdateCommand.Add; + entry_ = new ZipEntry(entryName); + entry_.CompressionMethod = compressionMethod; + dataSource_ = dataSource; + } + + public ZipUpdate(IStaticDataSource dataSource, ZipEntry entry) + { + command_ = UpdateCommand.Add; + entry_ = entry; + dataSource_ = dataSource; + } + + public ZipUpdate(ZipEntry original, ZipEntry updated) + { + throw new ZipException("Modify not currently supported"); + /* + command_ = UpdateCommand.Modify; + entry_ = ( ZipEntry )original.Clone(); + outEntry_ = ( ZipEntry )updated.Clone(); + */ + } + + public ZipUpdate(UpdateCommand command, ZipEntry entry) + { + command_ = command; + entry_ = ( ZipEntry )entry.Clone(); + } + + + /// + /// Copy an existing entry. + /// + /// The existing entry to copy. + public ZipUpdate(ZipEntry entry) + : this(UpdateCommand.Copy, entry) + { + // Do nothing. + } + #endregion + + /// + /// Get the for this update. + /// + /// This is the source or original entry. + public ZipEntry Entry + { + get { return entry_; } + } + + /// + /// Get the that will be written to the updated/new file. + /// + public ZipEntry OutEntry + { + get { + if ( outEntry_ == null ) { + outEntry_ = (ZipEntry)entry_.Clone(); + } + + return outEntry_; + } + } + + /// + /// Get the command for this update. + /// + public UpdateCommand Command + { + get { return command_; } + } + + /// + /// Get the filename if any for this update. Null if none exists. + /// + public string Filename + { + get { return filename_; } + } + + /// + /// Get/set the location of the size patch for this update. + /// + public long SizePatchOffset + { + get { return sizePatchOffset_; } + set { sizePatchOffset_ = value; } + } + + /// + /// Get /set the location of the crc patch for this update. + /// + public long CrcPatchOffset + { + get { return crcPatchOffset_; } + set { crcPatchOffset_ = value; } + } + + /// + /// Get/set the size calculated by offset. + /// Specifically, the difference between this and next entry's starting offset. + /// + public long OffsetBasedSize + { + get { return _offsetBasedSize; } + set { _offsetBasedSize = value; } + } + + public Stream GetSource() + { + Stream result = null; + if ( dataSource_ != null ) { + result = dataSource_.GetSource(); + } + + return result; + } + + #region Instance Fields + ZipEntry entry_; + ZipEntry outEntry_; + UpdateCommand command_; + IStaticDataSource dataSource_; + string filename_; + long sizePatchOffset_ = -1; + long crcPatchOffset_ = -1; + long _offsetBasedSize = -1; + #endregion + } + + #endregion + #endregion + + #region Disposing + + #region IDisposable Members + void IDisposable.Dispose() + { + Close(); + } + #endregion + + void DisposeInternal(bool disposing) + { + if ( !isDisposed_ ) { + isDisposed_ = true; + entries_ = new ZipEntry[0]; + + if ( IsStreamOwner && (baseStream_ != null) ) { + lock(baseStream_) { + baseStream_.Close(); + } + } + + PostUpdateCleanup(); + } + } + + /// + /// Releases the unmanaged resources used by the this instance and optionally releases the managed resources. + /// + /// true to release both managed and unmanaged resources; + /// false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + DisposeInternal(disposing); + } + + #endregion + + #region Internal routines + #region Reading + /// + /// Read an unsigned short in little endian byte order. + /// + /// Returns the value read. + /// + /// The stream ends prematurely + /// + ushort ReadLEUshort() + { + int data1 = baseStream_.ReadByte(); + + if ( data1 < 0 ) { + throw new EndOfStreamException("End of stream"); + } + + int data2 = baseStream_.ReadByte(); + + if ( data2 < 0 ) { + throw new EndOfStreamException("End of stream"); + } + + + return unchecked((ushort)((ushort)data1 | (ushort)(data2 << 8))); + } + + /// + /// Read a uint in little endian byte order. + /// + /// Returns the value read. + /// + /// An i/o error occurs. + /// + /// + /// The file ends prematurely + /// + uint ReadLEUint() + { + return (uint)(ReadLEUshort() | (ReadLEUshort() << 16)); + } + + ulong ReadLEUlong() + { + return ReadLEUint() | ((ulong)ReadLEUint() << 32); + } + + #endregion + // NOTE this returns the offset of the first byte after the signature. + long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) + { + using ( ZipHelperStream les = new ZipHelperStream(baseStream_) ) { + return les.LocateBlockWithSignature(signature, endLocation, minimumBlockSize, maximumVariableData); + } + } + + /// + /// Search for and read the central directory of a zip file filling the entries array. + /// + /// + /// An i/o error occurs. + /// + /// + /// The central directory is malformed or cannot be found + /// + void ReadEntries() + { + // Search for the End Of Central Directory. When a zip comment is + // present the directory will start earlier + // + // The search is limited to 64K which is the maximum size of a trailing comment field to aid speed. + // This should be compatible with both SFX and ZIP files but has only been tested for Zip files + // If a SFX file has the Zip data attached as a resource and there are other resources occuring later then + // this could be invalid. + // Could also speed this up by reading memory in larger blocks. + + if (baseStream_.CanSeek == false) { + throw new ZipException("ZipFile stream must be seekable"); + } + + long locatedEndOfCentralDir = LocateBlockWithSignature(ZipConstants.EndOfCentralDirectorySignature, + baseStream_.Length, ZipConstants.EndOfCentralRecordBaseSize, 0xffff); + + if (locatedEndOfCentralDir < 0) { + throw new ZipException("Cannot find central directory"); + } + + // Read end of central directory record + ushort thisDiskNumber = ReadLEUshort(); + ushort startCentralDirDisk = ReadLEUshort(); + ulong entriesForThisDisk = ReadLEUshort(); + ulong entriesForWholeCentralDir = ReadLEUshort(); + ulong centralDirSize = ReadLEUint(); + long offsetOfCentralDir = ReadLEUint(); + uint commentSize = ReadLEUshort(); + + if ( commentSize > 0 ) { + byte[] comment = new byte[commentSize]; + + StreamUtils.ReadFully(baseStream_, comment); + comment_ = ZipConstants.ConvertToString(comment); + } + else { + comment_ = string.Empty; + } + + bool isZip64 = false; + + // Check if zip64 header information is required. + if ( (thisDiskNumber == 0xffff) || + (startCentralDirDisk == 0xffff) || + (entriesForThisDisk == 0xffff) || + (entriesForWholeCentralDir == 0xffff) || + (centralDirSize == 0xffffffff) || + (offsetOfCentralDir == 0xffffffff) ) { + isZip64 = true; + + long offset = LocateBlockWithSignature(ZipConstants.Zip64CentralDirLocatorSignature, locatedEndOfCentralDir, 0, 0x1000); + if ( offset < 0 ) { + throw new ZipException("Cannot find Zip64 locator"); + } + + // number of the disk with the start of the zip64 end of central directory 4 bytes + // relative offset of the zip64 end of central directory record 8 bytes + // total number of disks 4 bytes + ReadLEUint(); // startDisk64 is not currently used + ulong offset64 = ReadLEUlong(); + uint totalDisks = ReadLEUint(); + + baseStream_.Position = (long)offset64; + long sig64 = ReadLEUint(); + + if ( sig64 != ZipConstants.Zip64CentralFileHeaderSignature ) { + throw new ZipException(string.Format("Invalid Zip64 Central directory signature at {0:X}", offset64)); + } + + // NOTE: Record size = SizeOfFixedFields + SizeOfVariableData - 12. + ulong recordSize = ReadLEUlong(); + int versionMadeBy = ReadLEUshort(); + int versionToExtract = ReadLEUshort(); + uint thisDisk = ReadLEUint(); + uint centralDirDisk = ReadLEUint(); + entriesForThisDisk = ReadLEUlong(); + entriesForWholeCentralDir = ReadLEUlong(); + centralDirSize = ReadLEUlong(); + offsetOfCentralDir = (long)ReadLEUlong(); + + // NOTE: zip64 extensible data sector (variable size) is ignored. + } + + entries_ = new ZipEntry[entriesForThisDisk]; + + // SFX/embedded support, find the offset of the first entry vis the start of the stream + // This applies to Zip files that are appended to the end of an SFX stub. + // Or are appended as a resource to an executable. + // Zip files created by some archivers have the offsets altered to reflect the true offsets + // and so dont require any adjustment here... + // TODO: Difficulty with Zip64 and SFX offset handling needs resolution - maths? + if ( !isZip64 && (offsetOfCentralDir < locatedEndOfCentralDir - (4 + (long)centralDirSize)) ) { + offsetOfFirstEntry = locatedEndOfCentralDir - (4 + (long)centralDirSize + offsetOfCentralDir); + if (offsetOfFirstEntry <= 0) { + throw new ZipException("Invalid embedded zip archive"); + } + } + + baseStream_.Seek(offsetOfFirstEntry + offsetOfCentralDir, SeekOrigin.Begin); + + for (ulong i = 0; i < entriesForThisDisk; i++) { + if (ReadLEUint() != ZipConstants.CentralHeaderSignature) { + throw new ZipException("Wrong Central Directory signature"); + } + + int versionMadeBy = ReadLEUshort(); + int versionToExtract = ReadLEUshort(); + int bitFlags = ReadLEUshort(); + int method = ReadLEUshort(); + uint dostime = ReadLEUint(); + uint crc = ReadLEUint(); + long csize = (long)ReadLEUint(); + long size = (long)ReadLEUint(); + int nameLen = ReadLEUshort(); + int extraLen = ReadLEUshort(); + int commentLen = ReadLEUshort(); + + int diskStartNo = ReadLEUshort(); // Not currently used + int internalAttributes = ReadLEUshort(); // Not currently used + + uint externalAttributes = ReadLEUint(); + long offset = ReadLEUint(); + + byte[] buffer = new byte[Math.Max(nameLen, commentLen)]; + + StreamUtils.ReadFully(baseStream_, buffer, 0, nameLen); + string name = ZipConstants.ConvertToStringExt(bitFlags, buffer, nameLen); + + ZipEntry entry = new ZipEntry(name, versionToExtract, versionMadeBy, (CompressionMethod)method); + entry.Crc = crc & 0xffffffffL; + entry.Size = size & 0xffffffffL; + entry.CompressedSize = csize & 0xffffffffL; + entry.Flags = bitFlags; + entry.DosTime = (uint)dostime; + entry.ZipFileIndex = (long)i; + entry.Offset = offset; + entry.ExternalFileAttributes = (int)externalAttributes; + + if ((bitFlags & 8) == 0) { + entry.CryptoCheckValue = (byte)(crc >> 24); + } + else { + entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff); + } + + if (extraLen > 0) { + byte[] extra = new byte[extraLen]; + StreamUtils.ReadFully(baseStream_, extra); + entry.ExtraData = extra; + } + + entry.ProcessExtraData(false); + + if (commentLen > 0) { + StreamUtils.ReadFully(baseStream_, buffer, 0, commentLen); + entry.Comment = ZipConstants.ConvertToStringExt(bitFlags, buffer, commentLen); + } + + entries_[i] = entry; + } + } + + /// + /// Locate the data for a given entry. + /// + /// + /// The start offset of the data. + /// + /// + /// The stream ends prematurely + /// + /// + /// The local header signature is invalid, the entry and central header file name lengths are different + /// or the local and entry compression methods dont match + /// + long LocateEntry(ZipEntry entry) + { + return TestLocalHeader(entry, HeaderTest.Extract); + } + +#if !NETCF_1_0 + Stream CreateAndInitDecryptionStream(Stream baseStream, ZipEntry entry) + { + CryptoStream result = null; + + if ( (entry.Version < ZipConstants.VersionStrongEncryption) + || (entry.Flags & (int)GeneralBitFlags.StrongEncryption) == 0) { + PkzipClassicManaged classicManaged = new PkzipClassicManaged(); + + OnKeysRequired(entry.Name); + if (HaveKeys == false) { + throw new ZipException("No password available for encrypted stream"); + } + + result = new CryptoStream(baseStream, classicManaged.CreateDecryptor(key, null), CryptoStreamMode.Read); + CheckClassicPassword(result, entry); + } + else { #if !NET_1_1 && !NETCF_2_0 - if (entry.Version == ZipConstants.VERSION_AES) { - // - OnKeysRequired(entry.Name); - if (HaveKeys == false) { - throw new ZipException("No password available for AES encrypted stream"); - } - int saltLen = entry.AESSaltLen; - byte[] saltBytes = new byte[saltLen]; - int saltIn = baseStream.Read(saltBytes, 0, saltLen); - if (saltIn != saltLen) - throw new ZipException("AES Salt expected " + saltLen + " got " + saltIn); - // - byte[] pwdVerifyRead = new byte[2]; - baseStream.Read(pwdVerifyRead, 0, 2); - int blockSize = entry.AESKeySize / 8; // bits to bytes - - ZipAESTransform decryptor = new ZipAESTransform(rawPassword_, saltBytes, blockSize, false); - byte[] pwdVerifyCalc = decryptor.PwdVerifier; - if (pwdVerifyCalc[0] != pwdVerifyRead[0] || pwdVerifyCalc[1] != pwdVerifyRead[1]) - throw new Exception("Invalid password for AES"); - result = new ZipAESStream(baseStream, decryptor, CryptoStreamMode.Read); - } - else + if (entry.Version == ZipConstants.VERSION_AES) { + // + OnKeysRequired(entry.Name); + if (HaveKeys == false) { + throw new ZipException("No password available for AES encrypted stream"); + } + int saltLen = entry.AESSaltLen; + byte[] saltBytes = new byte[saltLen]; + int saltIn = baseStream.Read(saltBytes, 0, saltLen); + if (saltIn != saltLen) + throw new ZipException("AES Salt expected " + saltLen + " got " + saltIn); + // + byte[] pwdVerifyRead = new byte[2]; + baseStream.Read(pwdVerifyRead, 0, 2); + int blockSize = entry.AESKeySize / 8; // bits to bytes + + ZipAESTransform decryptor = new ZipAESTransform(rawPassword_, saltBytes, blockSize, false); + byte[] pwdVerifyCalc = decryptor.PwdVerifier; + if (pwdVerifyCalc[0] != pwdVerifyRead[0] || pwdVerifyCalc[1] != pwdVerifyRead[1]) + throw new Exception("Invalid password for AES"); + result = new ZipAESStream(baseStream, decryptor, CryptoStreamMode.Read); + } + else #endif - { - throw new ZipException("Decryption method not supported"); - } - } - - return result; - } - - Stream CreateAndInitEncryptionStream(Stream baseStream, ZipEntry entry) - { - CryptoStream result = null; - if ( (entry.Version < ZipConstants.VersionStrongEncryption) - || (entry.Flags & (int)GeneralBitFlags.StrongEncryption) == 0) { - PkzipClassicManaged classicManaged = new PkzipClassicManaged(); - - OnKeysRequired(entry.Name); - if (HaveKeys == false) { - throw new ZipException("No password available for encrypted stream"); - } - - // Closing a CryptoStream will close the base stream as well so wrap it in an UncompressedStream - // which doesnt do this. - result = new CryptoStream(new UncompressedStream(baseStream), - classicManaged.CreateEncryptor(key, null), CryptoStreamMode.Write); - - if ( (entry.Crc < 0) || (entry.Flags & 8) != 0) { - WriteEncryptionHeader(result, entry.DosTime << 16); - } - else { - WriteEncryptionHeader(result, entry.Crc); - } - } - return result; - } - - static void CheckClassicPassword(CryptoStream classicCryptoStream, ZipEntry entry) - { - byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; - StreamUtils.ReadFully(classicCryptoStream, cryptbuffer); - if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) { - throw new ZipException("Invalid password"); - } - } + { + throw new ZipException("Decryption method not supported"); + } + } + + return result; + } + + Stream CreateAndInitEncryptionStream(Stream baseStream, ZipEntry entry) + { + CryptoStream result = null; + if ( (entry.Version < ZipConstants.VersionStrongEncryption) + || (entry.Flags & (int)GeneralBitFlags.StrongEncryption) == 0) { + PkzipClassicManaged classicManaged = new PkzipClassicManaged(); + + OnKeysRequired(entry.Name); + if (HaveKeys == false) { + throw new ZipException("No password available for encrypted stream"); + } + + // Closing a CryptoStream will close the base stream as well so wrap it in an UncompressedStream + // which doesnt do this. + result = new CryptoStream(new UncompressedStream(baseStream), + classicManaged.CreateEncryptor(key, null), CryptoStreamMode.Write); + + if ( (entry.Crc < 0) || (entry.Flags & 8) != 0) { + WriteEncryptionHeader(result, entry.DosTime << 16); + } + else { + WriteEncryptionHeader(result, entry.Crc); + } + } + return result; + } + + static void CheckClassicPassword(CryptoStream classicCryptoStream, ZipEntry entry) + { + byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; + StreamUtils.ReadFully(classicCryptoStream, cryptbuffer); + if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) { + throw new ZipException("Invalid password"); + } + } #endif - - static void WriteEncryptionHeader(Stream stream, long crcValue) - { - byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; - Random rnd = new Random(); - rnd.NextBytes(cryptBuffer); - cryptBuffer[11] = (byte)(crcValue >> 24); - stream.Write(cryptBuffer, 0, cryptBuffer.Length); - } - - #endregion - - #region Instance Fields - bool isDisposed_; - string name_; - string comment_; - string rawPassword_; - Stream baseStream_; - bool isStreamOwner; - long offsetOfFirstEntry; - ZipEntry[] entries_; - byte[] key; - bool isNewArchive_; - - // Default is dynamic which is not backwards compatible and can cause problems - // with XP's built in compression which cant read Zip64 archives. - // However it does avoid the situation were a large file is added and cannot be completed correctly. - // Hint: Set always ZipEntry size before they are added to an archive and this setting isnt needed. - UseZip64 useZip64_ = UseZip64.Dynamic ; - - #region Zip Update Instance Fields - ArrayList updates_; - long updateCount_; // Count is managed manually as updates_ can contain nulls! - Hashtable updateIndex_; - IArchiveStorage archiveStorage_; - IDynamicDataSource updateDataSource_; - bool contentsEdited_; - int bufferSize_ = DefaultBufferSize; - byte[] copyBuffer_; - ZipString newComment_; - bool commentEdited_; - IEntryFactory updateEntryFactory_ = new ZipEntryFactory(); - #endregion - #endregion - - #region Support Classes - /// - /// Represents a string from a which is stored as an array of bytes. - /// - class ZipString - { - #region Constructors - /// - /// Initialise a with a string. - /// - /// The textual string form. - public ZipString(string comment) - { - comment_ = comment; - isSourceString_ = true; - } - - /// - /// Initialise a using a string in its binary 'raw' form. - /// - /// - public ZipString(byte[] rawString) - { - rawComment_ = rawString; - } - #endregion - - /// - /// Get a value indicating the original source of data for this instance. - /// True if the source was a string; false if the source was binary data. - /// - public bool IsSourceString - { - get { return isSourceString_; } - } - - /// - /// Get the length of the comment when represented as raw bytes. - /// - public int RawLength - { - get { - MakeBytesAvailable(); - return rawComment_.Length; - } - } - - /// - /// Get the comment in its 'raw' form as plain bytes. - /// - public byte[] RawComment - { - get { - MakeBytesAvailable(); - return (byte[])rawComment_.Clone(); - } - } - - /// - /// Reset the comment to its initial state. - /// - public void Reset() - { - if ( isSourceString_ ) { - rawComment_ = null; - } - else { - comment_ = null; - } - } - - void MakeTextAvailable() - { - if ( comment_ == null ) { - comment_ = ZipConstants.ConvertToString(rawComment_); - } - } - - void MakeBytesAvailable() - { - if ( rawComment_ == null ) { - rawComment_ = ZipConstants.ConvertToArray(comment_); - } - } - - /// - /// Implicit conversion of comment to a string. - /// - /// The to convert to a string. - /// The textual equivalent for the input value. - static public implicit operator string(ZipString zipString) - { - zipString.MakeTextAvailable(); - return zipString.comment_; - } - - #region Instance Fields - string comment_; - byte[] rawComment_; - bool isSourceString_; - #endregion - } - - /// - /// An enumerator for Zip entries - /// - class ZipEntryEnumerator : IEnumerator - { - #region Constructors - public ZipEntryEnumerator(ZipEntry[] entries) - { - array = entries; - } - - #endregion - #region IEnumerator Members - public object Current - { - get { - return array[index]; - } - } - - public void Reset() - { - index = -1; - } - - public bool MoveNext() - { - return (++index < array.Length); - } - #endregion - #region Instance Fields - ZipEntry[] array; - int index = -1; - #endregion - } - - /// - /// An is a stream that you can write uncompressed data - /// to and flush, but cannot read, seek or do anything else to. - /// - class UncompressedStream : Stream - { - #region Constructors - public UncompressedStream(Stream baseStream) - { - baseStream_ = baseStream; - } - - #endregion - - /// - /// Close this stream instance. - /// - public override void Close() - { - // Do nothing - } - - /// - /// Gets a value indicating whether the current stream supports reading. - /// - public override bool CanRead - { - get { - return false; - } - } - - /// - /// Write any buffered data to underlying storage. - /// - public override void Flush() - { - baseStream_.Flush(); - } - - /// - /// Gets a value indicating whether the current stream supports writing. - /// - public override bool CanWrite - { - get { - return baseStream_.CanWrite; - } - } - - /// - /// Gets a value indicating whether the current stream supports seeking. - /// - public override bool CanSeek - { - get { - return false; - } - } - - /// - /// Get the length in bytes of the stream. - /// - public override long Length - { - get { - return 0; - } - } - - /// - /// Gets or sets the position within the current stream. - /// - public override long Position - { - get { - return baseStream_.Position; - } - - set - { - } - } - - /// - /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. - /// - /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. - /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. - /// The maximum number of bytes to be read from the current stream. - /// - /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. - /// - /// The sum of offset and count is larger than the buffer length. - /// Methods were called after the stream was closed. - /// The stream does not support reading. - /// buffer is null. - /// An I/O error occurs. - /// offset or count is negative. - public override int Read(byte[] buffer, int offset, int count) - { - return 0; - } - - /// - /// Sets the position within the current stream. - /// - /// A byte offset relative to the origin parameter. - /// A value of type indicating the reference point used to obtain the new position. - /// - /// The new position within the current stream. - /// - /// An I/O error occurs. - /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. - /// Methods were called after the stream was closed. - public override long Seek(long offset, SeekOrigin origin) - { - return 0; - } - - /// - /// Sets the length of the current stream. - /// - /// The desired length of the current stream in bytes. - /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. - /// An I/O error occurs. - /// Methods were called after the stream was closed. - public override void SetLength(long value) - { - } - - /// - /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. - /// - /// An array of bytes. This method copies count bytes from buffer to the current stream. - /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. - /// The number of bytes to be written to the current stream. - /// An I/O error occurs. - /// The stream does not support writing. - /// Methods were called after the stream was closed. - /// buffer is null. - /// The sum of offset and count is greater than the buffer length. - /// offset or count is negative. - public override void Write(byte[] buffer, int offset, int count) - { - baseStream_.Write(buffer, offset, count); - } - - #region Instance Fields - Stream baseStream_; - #endregion - } - - /// - /// A is an - /// whose data is only a part or subsection of a file. - /// - class PartialInputStream : Stream - { - #region Constructors - /// - /// Initialise a new instance of the class. - /// - /// The containing the underlying stream to use for IO. - /// The start of the partial data. - /// The length of the partial data. - public PartialInputStream(ZipFile zipFile, long start, long length) - { - start_ = start; - length_ = length; - - // Although this is the only time the zipfile is used - // keeping a reference here prevents premature closure of - // this zip file and thus the baseStream_. - - // Code like this will cause apparently random failures depending - // on the size of the files and when garbage is collected. - // - // ZipFile z = new ZipFile (stream); - // Stream reader = z.GetInputStream(0); - // uses reader here.... - zipFile_ = zipFile; - baseStream_ = zipFile_.baseStream_; - readPos_ = start; - end_ = start + length; - } - #endregion - - /// - /// Read a byte from this stream. - /// - /// Returns the byte read or -1 on end of stream. - public override int ReadByte() - { - if (readPos_ >= end_) { - // -1 is the correct value at end of stream. - return -1; - } - - lock( baseStream_ ) { - baseStream_.Seek(readPos_++, SeekOrigin.Begin); - return baseStream_.ReadByte(); - } - } - - /// - /// Close this partial input stream. - /// - /// - /// The underlying stream is not closed. Close the parent ZipFile class to do that. - /// - public override void Close() - { - // Do nothing at all! - } - - /// - /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. - /// - /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. - /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. - /// The maximum number of bytes to be read from the current stream. - /// - /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. - /// - /// The sum of offset and count is larger than the buffer length. - /// Methods were called after the stream was closed. - /// The stream does not support reading. - /// buffer is null. - /// An I/O error occurs. - /// offset or count is negative. - public override int Read(byte[] buffer, int offset, int count) - { - lock(baseStream_) { - if (count > end_ - readPos_) { - count = (int) (end_ - readPos_); - if (count == 0) { - return 0; - } - } - - baseStream_.Seek(readPos_, SeekOrigin.Begin); - int readCount = baseStream_.Read(buffer, offset, count); - if (readCount > 0) { - readPos_ += readCount; - } - return readCount; - } - } - - /// - /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. - /// - /// An array of bytes. This method copies count bytes from buffer to the current stream. - /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. - /// The number of bytes to be written to the current stream. - /// An I/O error occurs. - /// The stream does not support writing. - /// Methods were called after the stream was closed. - /// buffer is null. - /// The sum of offset and count is greater than the buffer length. - /// offset or count is negative. - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotSupportedException(); - } - - /// - /// When overridden in a derived class, sets the length of the current stream. - /// - /// The desired length of the current stream in bytes. - /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. - /// An I/O error occurs. - /// Methods were called after the stream was closed. - public override void SetLength(long value) - { - throw new NotSupportedException(); - } - - /// - /// When overridden in a derived class, sets the position within the current stream. - /// - /// A byte offset relative to the origin parameter. - /// A value of type indicating the reference point used to obtain the new position. - /// - /// The new position within the current stream. - /// - /// An I/O error occurs. - /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. - /// Methods were called after the stream was closed. - public override long Seek(long offset, SeekOrigin origin) - { - long newPos = readPos_; - - switch ( origin ) - { - case SeekOrigin.Begin: - newPos = start_ + offset; - break; - - case SeekOrigin.Current: - newPos = readPos_ + offset; - break; - - case SeekOrigin.End: - newPos = end_ + offset; - break; - } - - if ( newPos < start_ ) { - throw new ArgumentException("Negative position is invalid"); - } - - if ( newPos >= end_ ) { - throw new IOException("Cannot seek past end"); - } - readPos_ = newPos; - return readPos_; - } - - /// - /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. - /// - /// An I/O error occurs. - public override void Flush() - { - // Nothing to do. - } - - /// - /// Gets or sets the position within the current stream. - /// - /// - /// The current position within the stream. - /// An I/O error occurs. - /// The stream does not support seeking. - /// Methods were called after the stream was closed. - public override long Position { - get { return readPos_ - start_; } - set { - long newPos = start_ + value; - - if ( newPos < start_ ) { - throw new ArgumentException("Negative position is invalid"); - } - - if ( newPos >= end_ ) { - throw new InvalidOperationException("Cannot seek past end"); - } - readPos_ = newPos; - } - } - - /// - /// Gets the length in bytes of the stream. - /// - /// - /// A long value representing the length of the stream in bytes. - /// A class derived from Stream does not support seeking. - /// Methods were called after the stream was closed. - public override long Length { - get { return length_; } - } - - /// - /// Gets a value indicating whether the current stream supports writing. - /// - /// false - /// true if the stream supports writing; otherwise, false. - public override bool CanWrite { - get { return false; } - } - - /// - /// Gets a value indicating whether the current stream supports seeking. - /// - /// true - /// true if the stream supports seeking; otherwise, false. - public override bool CanSeek { - get { return true; } - } - - /// - /// Gets a value indicating whether the current stream supports reading. - /// - /// true. - /// true if the stream supports reading; otherwise, false. - public override bool CanRead { - get { return true; } - } - + + static void WriteEncryptionHeader(Stream stream, long crcValue) + { + byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; + Random rnd = new Random(); + rnd.NextBytes(cryptBuffer); + cryptBuffer[11] = (byte)(crcValue >> 24); + stream.Write(cryptBuffer, 0, cryptBuffer.Length); + } + + #endregion + + #region Instance Fields + bool isDisposed_; + string name_; + string comment_; + string rawPassword_; + Stream baseStream_; + bool isStreamOwner; + long offsetOfFirstEntry; + ZipEntry[] entries_; + byte[] key; + bool isNewArchive_; + + // Default is dynamic which is not backwards compatible and can cause problems + // with XP's built in compression which cant read Zip64 archives. + // However it does avoid the situation were a large file is added and cannot be completed correctly. + // Hint: Set always ZipEntry size before they are added to an archive and this setting isnt needed. + UseZip64 useZip64_ = UseZip64.Dynamic ; + + #region Zip Update Instance Fields + ArrayList updates_; + long updateCount_; // Count is managed manually as updates_ can contain nulls! + Hashtable updateIndex_; + IArchiveStorage archiveStorage_; + IDynamicDataSource updateDataSource_; + bool contentsEdited_; + int bufferSize_ = DefaultBufferSize; + byte[] copyBuffer_; + ZipString newComment_; + bool commentEdited_; + IEntryFactory updateEntryFactory_ = new ZipEntryFactory(); + #endregion + #endregion + + #region Support Classes + /// + /// Represents a string from a which is stored as an array of bytes. + /// + class ZipString + { + #region Constructors + /// + /// Initialise a with a string. + /// + /// The textual string form. + public ZipString(string comment) + { + comment_ = comment; + isSourceString_ = true; + } + + /// + /// Initialise a using a string in its binary 'raw' form. + /// + /// + public ZipString(byte[] rawString) + { + rawComment_ = rawString; + } + #endregion + + /// + /// Get a value indicating the original source of data for this instance. + /// True if the source was a string; false if the source was binary data. + /// + public bool IsSourceString + { + get { return isSourceString_; } + } + + /// + /// Get the length of the comment when represented as raw bytes. + /// + public int RawLength + { + get { + MakeBytesAvailable(); + return rawComment_.Length; + } + } + + /// + /// Get the comment in its 'raw' form as plain bytes. + /// + public byte[] RawComment + { + get { + MakeBytesAvailable(); + return (byte[])rawComment_.Clone(); + } + } + + /// + /// Reset the comment to its initial state. + /// + public void Reset() + { + if ( isSourceString_ ) { + rawComment_ = null; + } + else { + comment_ = null; + } + } + + void MakeTextAvailable() + { + if ( comment_ == null ) { + comment_ = ZipConstants.ConvertToString(rawComment_); + } + } + + void MakeBytesAvailable() + { + if ( rawComment_ == null ) { + rawComment_ = ZipConstants.ConvertToArray(comment_); + } + } + + /// + /// Implicit conversion of comment to a string. + /// + /// The to convert to a string. + /// The textual equivalent for the input value. + static public implicit operator string(ZipString zipString) + { + zipString.MakeTextAvailable(); + return zipString.comment_; + } + + #region Instance Fields + string comment_; + byte[] rawComment_; + bool isSourceString_; + #endregion + } + + /// + /// An enumerator for Zip entries + /// + class ZipEntryEnumerator : IEnumerator + { + #region Constructors + public ZipEntryEnumerator(ZipEntry[] entries) + { + array = entries; + } + + #endregion + #region IEnumerator Members + public object Current + { + get { + return array[index]; + } + } + + public void Reset() + { + index = -1; + } + + public bool MoveNext() + { + return (++index < array.Length); + } + #endregion + #region Instance Fields + ZipEntry[] array; + int index = -1; + #endregion + } + + /// + /// An is a stream that you can write uncompressed data + /// to and flush, but cannot read, seek or do anything else to. + /// + class UncompressedStream : Stream + { + #region Constructors + public UncompressedStream(Stream baseStream) + { + baseStream_ = baseStream; + } + + #endregion + + /// + /// Close this stream instance. + /// + public override void Close() + { + // Do nothing + } + + /// + /// Gets a value indicating whether the current stream supports reading. + /// + public override bool CanRead + { + get { + return false; + } + } + + /// + /// Write any buffered data to underlying storage. + /// + public override void Flush() + { + baseStream_.Flush(); + } + + /// + /// Gets a value indicating whether the current stream supports writing. + /// + public override bool CanWrite + { + get { + return baseStream_.CanWrite; + } + } + + /// + /// Gets a value indicating whether the current stream supports seeking. + /// + public override bool CanSeek + { + get { + return false; + } + } + + /// + /// Get the length in bytes of the stream. + /// + public override long Length + { + get { + return 0; + } + } + + /// + /// Gets or sets the position within the current stream. + /// + public override long Position + { + get { + return baseStream_.Position; + } + + set + { + } + } + + /// + /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. + /// + /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. + /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. + /// The maximum number of bytes to be read from the current stream. + /// + /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. + /// + /// The sum of offset and count is larger than the buffer length. + /// Methods were called after the stream was closed. + /// The stream does not support reading. + /// buffer is null. + /// An I/O error occurs. + /// offset or count is negative. + public override int Read(byte[] buffer, int offset, int count) + { + return 0; + } + + /// + /// Sets the position within the current stream. + /// + /// A byte offset relative to the origin parameter. + /// A value of type indicating the reference point used to obtain the new position. + /// + /// The new position within the current stream. + /// + /// An I/O error occurs. + /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. + /// Methods were called after the stream was closed. + public override long Seek(long offset, SeekOrigin origin) + { + return 0; + } + + /// + /// Sets the length of the current stream. + /// + /// The desired length of the current stream in bytes. + /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. + /// An I/O error occurs. + /// Methods were called after the stream was closed. + public override void SetLength(long value) + { + } + + /// + /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. + /// + /// An array of bytes. This method copies count bytes from buffer to the current stream. + /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. + /// The number of bytes to be written to the current stream. + /// An I/O error occurs. + /// The stream does not support writing. + /// Methods were called after the stream was closed. + /// buffer is null. + /// The sum of offset and count is greater than the buffer length. + /// offset or count is negative. + public override void Write(byte[] buffer, int offset, int count) + { + baseStream_.Write(buffer, offset, count); + } + + #region Instance Fields + Stream baseStream_; + #endregion + } + + /// + /// A is an + /// whose data is only a part or subsection of a file. + /// + class PartialInputStream : Stream + { + #region Constructors + /// + /// Initialise a new instance of the class. + /// + /// The containing the underlying stream to use for IO. + /// The start of the partial data. + /// The length of the partial data. + public PartialInputStream(ZipFile zipFile, long start, long length) + { + start_ = start; + length_ = length; + + // Although this is the only time the zipfile is used + // keeping a reference here prevents premature closure of + // this zip file and thus the baseStream_. + + // Code like this will cause apparently random failures depending + // on the size of the files and when garbage is collected. + // + // ZipFile z = new ZipFile (stream); + // Stream reader = z.GetInputStream(0); + // uses reader here.... + zipFile_ = zipFile; + baseStream_ = zipFile_.baseStream_; + readPos_ = start; + end_ = start + length; + } + #endregion + + /// + /// Read a byte from this stream. + /// + /// Returns the byte read or -1 on end of stream. + public override int ReadByte() + { + if (readPos_ >= end_) { + // -1 is the correct value at end of stream. + return -1; + } + + lock( baseStream_ ) { + baseStream_.Seek(readPos_++, SeekOrigin.Begin); + return baseStream_.ReadByte(); + } + } + + /// + /// Close this partial input stream. + /// + /// + /// The underlying stream is not closed. Close the parent ZipFile class to do that. + /// + public override void Close() + { + // Do nothing at all! + } + + /// + /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. + /// + /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source. + /// The zero-based byte offset in buffer at which to begin storing the data read from the current stream. + /// The maximum number of bytes to be read from the current stream. + /// + /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. + /// + /// The sum of offset and count is larger than the buffer length. + /// Methods were called after the stream was closed. + /// The stream does not support reading. + /// buffer is null. + /// An I/O error occurs. + /// offset or count is negative. + public override int Read(byte[] buffer, int offset, int count) + { + lock(baseStream_) { + if (count > end_ - readPos_) { + count = (int) (end_ - readPos_); + if (count == 0) { + return 0; + } + } + + baseStream_.Seek(readPos_, SeekOrigin.Begin); + int readCount = baseStream_.Read(buffer, offset, count); + if (readCount > 0) { + readPos_ += readCount; + } + return readCount; + } + } + + /// + /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. + /// + /// An array of bytes. This method copies count bytes from buffer to the current stream. + /// The zero-based byte offset in buffer at which to begin copying bytes to the current stream. + /// The number of bytes to be written to the current stream. + /// An I/O error occurs. + /// The stream does not support writing. + /// Methods were called after the stream was closed. + /// buffer is null. + /// The sum of offset and count is greater than the buffer length. + /// offset or count is negative. + public override void Write(byte[] buffer, int offset, int count) + { + throw new NotSupportedException(); + } + + /// + /// When overridden in a derived class, sets the length of the current stream. + /// + /// The desired length of the current stream in bytes. + /// The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output. + /// An I/O error occurs. + /// Methods were called after the stream was closed. + public override void SetLength(long value) + { + throw new NotSupportedException(); + } + + /// + /// When overridden in a derived class, sets the position within the current stream. + /// + /// A byte offset relative to the origin parameter. + /// A value of type indicating the reference point used to obtain the new position. + /// + /// The new position within the current stream. + /// + /// An I/O error occurs. + /// The stream does not support seeking, such as if the stream is constructed from a pipe or console output. + /// Methods were called after the stream was closed. + public override long Seek(long offset, SeekOrigin origin) + { + long newPos = readPos_; + + switch ( origin ) + { + case SeekOrigin.Begin: + newPos = start_ + offset; + break; + + case SeekOrigin.Current: + newPos = readPos_ + offset; + break; + + case SeekOrigin.End: + newPos = end_ + offset; + break; + } + + if ( newPos < start_ ) { + throw new ArgumentException("Negative position is invalid"); + } + + if ( newPos >= end_ ) { + throw new IOException("Cannot seek past end"); + } + readPos_ = newPos; + return readPos_; + } + + /// + /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device. + /// + /// An I/O error occurs. + public override void Flush() + { + // Nothing to do. + } + + /// + /// Gets or sets the position within the current stream. + /// + /// + /// The current position within the stream. + /// An I/O error occurs. + /// The stream does not support seeking. + /// Methods were called after the stream was closed. + public override long Position { + get { return readPos_ - start_; } + set { + long newPos = start_ + value; + + if ( newPos < start_ ) { + throw new ArgumentException("Negative position is invalid"); + } + + if ( newPos >= end_ ) { + throw new InvalidOperationException("Cannot seek past end"); + } + readPos_ = newPos; + } + } + + /// + /// Gets the length in bytes of the stream. + /// + /// + /// A long value representing the length of the stream in bytes. + /// A class derived from Stream does not support seeking. + /// Methods were called after the stream was closed. + public override long Length { + get { return length_; } + } + + /// + /// Gets a value indicating whether the current stream supports writing. + /// + /// false + /// true if the stream supports writing; otherwise, false. + public override bool CanWrite { + get { return false; } + } + + /// + /// Gets a value indicating whether the current stream supports seeking. + /// + /// true + /// true if the stream supports seeking; otherwise, false. + public override bool CanSeek { + get { return true; } + } + + /// + /// Gets a value indicating whether the current stream supports reading. + /// + /// true. + /// true if the stream supports reading; otherwise, false. + public override bool CanRead { + get { return true; } + } + #if !NET_1_0 && !NET_1_1 && !NETCF_1_0 - /// - /// Gets a value that determines whether the current stream can time out. - /// - /// - /// A value that determines whether the current stream can time out. - public override bool CanTimeout { - get { return baseStream_.CanTimeout; } - } -#endif - #region Instance Fields - ZipFile zipFile_; - Stream baseStream_; - long start_; - long length_; - long readPos_; - long end_; - #endregion - } - #endregion - } - - #endregion - - #region DataSources - /// - /// Provides a static way to obtain a source of data for an entry. - /// - public interface IStaticDataSource - { - /// - /// Get a source of data by creating a new stream. - /// - /// Returns a to use for compression input. - /// Ideally a new stream is created and opened to achieve this, to avoid locking problems. - Stream GetSource(); - } - - /// - /// Represents a source of data that can dynamically provide - /// multiple data sources based on the parameters passed. - /// - public interface IDynamicDataSource - { - /// - /// Get a data source. - /// - /// The to get a source for. - /// The name for data if known. - /// Returns a to use for compression input. - /// Ideally a new stream is created and opened to achieve this, to avoid locking problems. - Stream GetSource(ZipEntry entry, string name); - } - - /// - /// Default implementation of a for use with files stored on disk. - /// - public class StaticDiskDataSource : IStaticDataSource - { - /// - /// Initialise a new instnace of - /// - /// The name of the file to obtain data from. - public StaticDiskDataSource(string fileName) - { - fileName_ = fileName; - } - - #region IDataSource Members - - /// - /// Get a providing data. - /// - /// Returns a provising data. - public Stream GetSource() - { - return File.Open(fileName_, FileMode.Open, FileAccess.Read, FileShare.Read); - } - - #endregion - #region Instance Fields - string fileName_; - #endregion - } - - - /// - /// Default implementation of for files stored on disk. - /// - public class DynamicDiskDataSource : IDynamicDataSource - { - /// - /// Initialise a default instance of . - /// - public DynamicDiskDataSource() - { - } - - #region IDataSource Members - /// - /// Get a providing data for an entry. - /// - /// The entry to provide data for. - /// The file name for data if known. - /// Returns a stream providing data; or null if not available - public Stream GetSource(ZipEntry entry, string name) - { - Stream result = null; - - if ( name != null ) { - result = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read); - } - - return result; - } - - #endregion - } - - #endregion - - #region Archive Storage - /// - /// Defines facilities for data storage when updating Zip Archives. - /// - public interface IArchiveStorage - { - /// - /// Get the to apply during updates. - /// - FileUpdateMode UpdateMode { get; } - - /// - /// Get an empty that can be used for temporary output. - /// - /// Returns a temporary output - /// - Stream GetTemporaryOutput(); - - /// - /// Convert a temporary output stream to a final stream. - /// - /// The resulting final - /// - Stream ConvertTemporaryToFinal(); - - /// - /// Make a temporary copy of the original stream. - /// - /// The to copy. - /// Returns a temporary output that is a copy of the input. - Stream MakeTemporaryCopy(Stream stream); - - /// - /// Return a stream suitable for performing direct updates on the original source. - /// - /// The current stream. - /// Returns a stream suitable for direct updating. - /// This may be the current stream passed. - Stream OpenForDirectUpdate(Stream stream); - - /// - /// Dispose of this instance. - /// - void Dispose(); - } - - /// - /// An abstract suitable for extension by inheritance. - /// - abstract public class BaseArchiveStorage : IArchiveStorage - { - #region Constructors - /// - /// Initializes a new instance of the class. - /// - /// The update mode. - protected BaseArchiveStorage(FileUpdateMode updateMode) - { - updateMode_ = updateMode; - } - #endregion - - #region IArchiveStorage Members - - /// - /// Gets a temporary output - /// - /// Returns the temporary output stream. - /// - public abstract Stream GetTemporaryOutput(); - - /// - /// Converts the temporary to its final form. - /// - /// Returns a that can be used to read - /// the final storage for the archive. - /// - public abstract Stream ConvertTemporaryToFinal(); - - /// - /// Make a temporary copy of a . - /// - /// The to make a copy of. - /// Returns a temporary output that is a copy of the input. - public abstract Stream MakeTemporaryCopy(Stream stream); - - /// - /// Return a stream suitable for performing direct updates on the original source. - /// - /// The to open for direct update. - /// Returns a stream suitable for direct updating. - public abstract Stream OpenForDirectUpdate(Stream stream); - - /// - /// Disposes this instance. - /// - public abstract void Dispose(); - - /// - /// Gets the update mode applicable. - /// - /// The update mode. - public FileUpdateMode UpdateMode - { - get { - return updateMode_; - } - } - - #endregion - - #region Instance Fields - FileUpdateMode updateMode_; - #endregion - } - - /// - /// An implementation suitable for hard disks. - /// - public class DiskArchiveStorage : BaseArchiveStorage - { - #region Constructors - /// - /// Initializes a new instance of the class. - /// - /// The file. - /// The update mode. - public DiskArchiveStorage(ZipFile file, FileUpdateMode updateMode) - : base(updateMode) - { - if ( file.Name == null ) { - throw new ZipException("Cant handle non file archives"); - } - - fileName_ = file.Name; - } - - /// - /// Initializes a new instance of the class. - /// - /// The file. - public DiskArchiveStorage(ZipFile file) - : this(file, FileUpdateMode.Safe) - { - } - #endregion - - #region IArchiveStorage Members - - /// - /// Gets a temporary output for performing updates on. - /// - /// Returns the temporary output stream. - public override Stream GetTemporaryOutput() - { - if ( temporaryName_ != null ) { - temporaryName_ = GetTempFileName(temporaryName_, true); - temporaryStream_ = File.Open(temporaryName_, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); - } - else { - // Determine where to place files based on internal strategy. - // Currently this is always done in system temp directory. - temporaryName_ = Path.GetTempFileName(); - temporaryStream_ = File.Open(temporaryName_, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); - } - - return temporaryStream_; - } - - /// - /// Converts a temporary to its final form. - /// - /// Returns a that can be used to read - /// the final storage for the archive. - public override Stream ConvertTemporaryToFinal() - { - if ( temporaryStream_ == null ) { - throw new ZipException("No temporary stream has been created"); - } - - Stream result = null; - - string moveTempName = GetTempFileName(fileName_, false); - bool newFileCreated = false; - - try { - temporaryStream_.Close(); - File.Move(fileName_, moveTempName); - File.Move(temporaryName_, fileName_); - newFileCreated = true; - File.Delete(moveTempName); - - result = File.Open(fileName_, FileMode.Open, FileAccess.Read, FileShare.Read); - } - catch(Exception) { - result = null; - - // Try to roll back changes... - if ( !newFileCreated ) { - File.Move(moveTempName, fileName_); - File.Delete(temporaryName_); - } - - throw; - } - - return result; - } - - /// - /// Make a temporary copy of a stream. - /// - /// The to copy. - /// Returns a temporary output that is a copy of the input. - public override Stream MakeTemporaryCopy(Stream stream) - { - stream.Close(); - - temporaryName_ = GetTempFileName(fileName_, true); - File.Copy(fileName_, temporaryName_, true); - - temporaryStream_ = new FileStream(temporaryName_, - FileMode.Open, - FileAccess.ReadWrite); - return temporaryStream_; - } - - /// - /// Return a stream suitable for performing direct updates on the original source. - /// - /// The current stream. - /// Returns a stream suitable for direct updating. - /// If the stream is not null this is used as is. - public override Stream OpenForDirectUpdate(Stream stream) - { - Stream result; - if ((stream == null) || !stream.CanWrite) - { - if (stream != null) { - stream.Close(); - } - - result = new FileStream(fileName_, - FileMode.Open, - FileAccess.ReadWrite); - } - else - { - result = stream; - } - - return result; - } - - /// - /// Disposes this instance. - /// - public override void Dispose() - { - if ( temporaryStream_ != null ) { - temporaryStream_.Close(); - } - } - - #endregion - - #region Internal routines - static string GetTempFileName(string original, bool makeTempFile) - { - string result = null; - - if ( original == null ) { - result = Path.GetTempFileName(); - } - else { - int counter = 0; - int suffixSeed = DateTime.Now.Second; - - while ( result == null ) { - counter += 1; - string newName = string.Format("{0}.{1}{2}.tmp", original, suffixSeed, counter); - if ( !File.Exists(newName) ) { - if ( makeTempFile) { - try { - // Try and create the file. - using ( FileStream stream = File.Create(newName) ) { - } - result = newName; - } - catch { - suffixSeed = DateTime.Now.Second; - } - } - else { - result = newName; - } - } - } - } - return result; - } - #endregion - - #region Instance Fields - Stream temporaryStream_; - string fileName_; - string temporaryName_; - #endregion - } - - /// - /// An implementation suitable for in memory streams. - /// - public class MemoryArchiveStorage : BaseArchiveStorage - { - #region Constructors - /// - /// Initializes a new instance of the class. - /// - public MemoryArchiveStorage() - : base(FileUpdateMode.Direct) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The to use - /// This constructor is for testing as memory streams dont really require safe mode. - public MemoryArchiveStorage(FileUpdateMode updateMode) - : base(updateMode) - { - } - - #endregion - - #region Properties - /// - /// Get the stream returned by if this was in fact called. - /// - public MemoryStream FinalStream - { - get { return finalStream_; } - } - - #endregion - - #region IArchiveStorage Members - - /// - /// Gets the temporary output - /// - /// Returns the temporary output stream. - public override Stream GetTemporaryOutput() - { - temporaryStream_ = new MemoryStream(); - return temporaryStream_; - } - - /// - /// Converts the temporary to its final form. - /// - /// Returns a that can be used to read - /// the final storage for the archive. - public override Stream ConvertTemporaryToFinal() - { - if ( temporaryStream_ == null ) { - throw new ZipException("No temporary stream has been created"); - } - - finalStream_ = new MemoryStream(temporaryStream_.ToArray()); - return finalStream_; - } - - /// - /// Make a temporary copy of the original stream. - /// - /// The to copy. - /// Returns a temporary output that is a copy of the input. - public override Stream MakeTemporaryCopy(Stream stream) - { - temporaryStream_ = new MemoryStream(); - stream.Position = 0; - StreamUtils.Copy(stream, temporaryStream_, new byte[4096]); - return temporaryStream_; - } - - /// - /// Return a stream suitable for performing direct updates on the original source. - /// - /// The original source stream - /// Returns a stream suitable for direct updating. - /// If the passed is not null this is used; - /// otherwise a new is returned. - public override Stream OpenForDirectUpdate(Stream stream) - { - Stream result; - if ((stream == null) || !stream.CanWrite) { - - result = new MemoryStream(); - - if (stream != null) { - stream.Position = 0; - StreamUtils.Copy(stream, result, new byte[4096]); - - stream.Close(); - } - } - else { - result = stream; - } - - return result; - } - - /// - /// Disposes this instance. - /// - public override void Dispose() - { - if ( temporaryStream_ != null ) { - temporaryStream_.Close(); - } - } - - #endregion - - #region Instance Fields - MemoryStream temporaryStream_; - MemoryStream finalStream_; - #endregion - } - - #endregion + /// + /// Gets a value that determines whether the current stream can time out. + /// + /// + /// A value that determines whether the current stream can time out. + public override bool CanTimeout { + get { return baseStream_.CanTimeout; } + } +#endif + #region Instance Fields + ZipFile zipFile_; + Stream baseStream_; + long start_; + long length_; + long readPos_; + long end_; + #endregion + } + #endregion + } + + #endregion + + #region DataSources + /// + /// Provides a static way to obtain a source of data for an entry. + /// + public interface IStaticDataSource + { + /// + /// Get a source of data by creating a new stream. + /// + /// Returns a to use for compression input. + /// Ideally a new stream is created and opened to achieve this, to avoid locking problems. + Stream GetSource(); + } + + /// + /// Represents a source of data that can dynamically provide + /// multiple data sources based on the parameters passed. + /// + public interface IDynamicDataSource + { + /// + /// Get a data source. + /// + /// The to get a source for. + /// The name for data if known. + /// Returns a to use for compression input. + /// Ideally a new stream is created and opened to achieve this, to avoid locking problems. + Stream GetSource(ZipEntry entry, string name); + } + + /// + /// Default implementation of a for use with files stored on disk. + /// + public class StaticDiskDataSource : IStaticDataSource + { + /// + /// Initialise a new instnace of + /// + /// The name of the file to obtain data from. + public StaticDiskDataSource(string fileName) + { + fileName_ = fileName; + } + + #region IDataSource Members + + /// + /// Get a providing data. + /// + /// Returns a provising data. + public Stream GetSource() + { + return File.Open(fileName_, FileMode.Open, FileAccess.Read, FileShare.Read); + } + + #endregion + #region Instance Fields + string fileName_; + #endregion + } + + + /// + /// Default implementation of for files stored on disk. + /// + public class DynamicDiskDataSource : IDynamicDataSource + { + /// + /// Initialise a default instance of . + /// + public DynamicDiskDataSource() + { + } + + #region IDataSource Members + /// + /// Get a providing data for an entry. + /// + /// The entry to provide data for. + /// The file name for data if known. + /// Returns a stream providing data; or null if not available + public Stream GetSource(ZipEntry entry, string name) + { + Stream result = null; + + if ( name != null ) { + result = File.Open(name, FileMode.Open, FileAccess.Read, FileShare.Read); + } + + return result; + } + + #endregion + } + + #endregion + + #region Archive Storage + /// + /// Defines facilities for data storage when updating Zip Archives. + /// + public interface IArchiveStorage + { + /// + /// Get the to apply during updates. + /// + FileUpdateMode UpdateMode { get; } + + /// + /// Get an empty that can be used for temporary output. + /// + /// Returns a temporary output + /// + Stream GetTemporaryOutput(); + + /// + /// Convert a temporary output stream to a final stream. + /// + /// The resulting final + /// + Stream ConvertTemporaryToFinal(); + + /// + /// Make a temporary copy of the original stream. + /// + /// The to copy. + /// Returns a temporary output that is a copy of the input. + Stream MakeTemporaryCopy(Stream stream); + + /// + /// Return a stream suitable for performing direct updates on the original source. + /// + /// The current stream. + /// Returns a stream suitable for direct updating. + /// This may be the current stream passed. + Stream OpenForDirectUpdate(Stream stream); + + /// + /// Dispose of this instance. + /// + void Dispose(); + } + + /// + /// An abstract suitable for extension by inheritance. + /// + abstract public class BaseArchiveStorage : IArchiveStorage + { + #region Constructors + /// + /// Initializes a new instance of the class. + /// + /// The update mode. + protected BaseArchiveStorage(FileUpdateMode updateMode) + { + updateMode_ = updateMode; + } + #endregion + + #region IArchiveStorage Members + + /// + /// Gets a temporary output + /// + /// Returns the temporary output stream. + /// + public abstract Stream GetTemporaryOutput(); + + /// + /// Converts the temporary to its final form. + /// + /// Returns a that can be used to read + /// the final storage for the archive. + /// + public abstract Stream ConvertTemporaryToFinal(); + + /// + /// Make a temporary copy of a . + /// + /// The to make a copy of. + /// Returns a temporary output that is a copy of the input. + public abstract Stream MakeTemporaryCopy(Stream stream); + + /// + /// Return a stream suitable for performing direct updates on the original source. + /// + /// The to open for direct update. + /// Returns a stream suitable for direct updating. + public abstract Stream OpenForDirectUpdate(Stream stream); + + /// + /// Disposes this instance. + /// + public abstract void Dispose(); + + /// + /// Gets the update mode applicable. + /// + /// The update mode. + public FileUpdateMode UpdateMode + { + get { + return updateMode_; + } + } + + #endregion + + #region Instance Fields + FileUpdateMode updateMode_; + #endregion + } + + /// + /// An implementation suitable for hard disks. + /// + public class DiskArchiveStorage : BaseArchiveStorage + { + #region Constructors + /// + /// Initializes a new instance of the class. + /// + /// The file. + /// The update mode. + public DiskArchiveStorage(ZipFile file, FileUpdateMode updateMode) + : base(updateMode) + { + if ( file.Name == null ) { + throw new ZipException("Cant handle non file archives"); + } + + fileName_ = file.Name; + } + + /// + /// Initializes a new instance of the class. + /// + /// The file. + public DiskArchiveStorage(ZipFile file) + : this(file, FileUpdateMode.Safe) + { + } + #endregion + + #region IArchiveStorage Members + + /// + /// Gets a temporary output for performing updates on. + /// + /// Returns the temporary output stream. + public override Stream GetTemporaryOutput() + { + if ( temporaryName_ != null ) { + temporaryName_ = GetTempFileName(temporaryName_, true); + temporaryStream_ = File.Open(temporaryName_, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); + } + else { + // Determine where to place files based on internal strategy. + // Currently this is always done in system temp directory. + temporaryName_ = Path.GetTempFileName(); + temporaryStream_ = File.Open(temporaryName_, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); + } + + return temporaryStream_; + } + + /// + /// Converts a temporary to its final form. + /// + /// Returns a that can be used to read + /// the final storage for the archive. + public override Stream ConvertTemporaryToFinal() + { + if ( temporaryStream_ == null ) { + throw new ZipException("No temporary stream has been created"); + } + + Stream result = null; + + string moveTempName = GetTempFileName(fileName_, false); + bool newFileCreated = false; + + try { + temporaryStream_.Close(); + File.Move(fileName_, moveTempName); + File.Move(temporaryName_, fileName_); + newFileCreated = true; + File.Delete(moveTempName); + + result = File.Open(fileName_, FileMode.Open, FileAccess.Read, FileShare.Read); + } + catch(Exception) { + result = null; + + // Try to roll back changes... + if ( !newFileCreated ) { + File.Move(moveTempName, fileName_); + File.Delete(temporaryName_); + } + + throw; + } + + return result; + } + + /// + /// Make a temporary copy of a stream. + /// + /// The to copy. + /// Returns a temporary output that is a copy of the input. + public override Stream MakeTemporaryCopy(Stream stream) + { + stream.Close(); + + temporaryName_ = GetTempFileName(fileName_, true); + File.Copy(fileName_, temporaryName_, true); + + temporaryStream_ = new FileStream(temporaryName_, + FileMode.Open, + FileAccess.ReadWrite); + return temporaryStream_; + } + + /// + /// Return a stream suitable for performing direct updates on the original source. + /// + /// The current stream. + /// Returns a stream suitable for direct updating. + /// If the stream is not null this is used as is. + public override Stream OpenForDirectUpdate(Stream stream) + { + Stream result; + if ((stream == null) || !stream.CanWrite) + { + if (stream != null) { + stream.Close(); + } + + result = new FileStream(fileName_, + FileMode.Open, + FileAccess.ReadWrite); + } + else + { + result = stream; + } + + return result; + } + + /// + /// Disposes this instance. + /// + public override void Dispose() + { + if ( temporaryStream_ != null ) { + temporaryStream_.Close(); + } + } + + #endregion + + #region Internal routines + static string GetTempFileName(string original, bool makeTempFile) + { + string result = null; + + if ( original == null ) { + result = Path.GetTempFileName(); + } + else { + int counter = 0; + int suffixSeed = DateTime.Now.Second; + + while ( result == null ) { + counter += 1; + string newName = string.Format("{0}.{1}{2}.tmp", original, suffixSeed, counter); + if ( !File.Exists(newName) ) { + if ( makeTempFile) { + try { + // Try and create the file. + using ( FileStream stream = File.Create(newName) ) { + } + result = newName; + } + catch { + suffixSeed = DateTime.Now.Second; + } + } + else { + result = newName; + } + } + } + } + return result; + } + #endregion + + #region Instance Fields + Stream temporaryStream_; + string fileName_; + string temporaryName_; + #endregion + } + + /// + /// An implementation suitable for in memory streams. + /// + public class MemoryArchiveStorage : BaseArchiveStorage + { + #region Constructors + /// + /// Initializes a new instance of the class. + /// + public MemoryArchiveStorage() + : base(FileUpdateMode.Direct) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The to use + /// This constructor is for testing as memory streams dont really require safe mode. + public MemoryArchiveStorage(FileUpdateMode updateMode) + : base(updateMode) + { + } + + #endregion + + #region Properties + /// + /// Get the stream returned by if this was in fact called. + /// + public MemoryStream FinalStream + { + get { return finalStream_; } + } + + #endregion + + #region IArchiveStorage Members + + /// + /// Gets the temporary output + /// + /// Returns the temporary output stream. + public override Stream GetTemporaryOutput() + { + temporaryStream_ = new MemoryStream(); + return temporaryStream_; + } + + /// + /// Converts the temporary to its final form. + /// + /// Returns a that can be used to read + /// the final storage for the archive. + public override Stream ConvertTemporaryToFinal() + { + if ( temporaryStream_ == null ) { + throw new ZipException("No temporary stream has been created"); + } + + finalStream_ = new MemoryStream(temporaryStream_.ToArray()); + return finalStream_; + } + + /// + /// Make a temporary copy of the original stream. + /// + /// The to copy. + /// Returns a temporary output that is a copy of the input. + public override Stream MakeTemporaryCopy(Stream stream) + { + temporaryStream_ = new MemoryStream(); + stream.Position = 0; + StreamUtils.Copy(stream, temporaryStream_, new byte[4096]); + return temporaryStream_; + } + + /// + /// Return a stream suitable for performing direct updates on the original source. + /// + /// The original source stream + /// Returns a stream suitable for direct updating. + /// If the passed is not null this is used; + /// otherwise a new is returned. + public override Stream OpenForDirectUpdate(Stream stream) + { + Stream result; + if ((stream == null) || !stream.CanWrite) { + + result = new MemoryStream(); + + if (stream != null) { + stream.Position = 0; + StreamUtils.Copy(stream, result, new byte[4096]); + + stream.Close(); + } + } + else { + result = stream; + } + + return result; + } + + /// + /// Disposes this instance. + /// + public override void Dispose() + { + if ( temporaryStream_ != null ) { + temporaryStream_.Close(); + } + } + + #endregion + + #region Instance Fields + MemoryStream temporaryStream_; + MemoryStream finalStream_; + #endregion + } + + #endregion } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipHelperStream.cs b/External/Tools/AppMan/ZipLib/Zip/ZipHelperStream.cs index a2f905d6c8..30854f35e0 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipHelperStream.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipHelperStream.cs @@ -40,584 +40,584 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// Holds data pertinent to a data descriptor. - /// - public class DescriptorData - { - /// - /// Get /set the compressed size of data. - /// - public long CompressedSize - { - get { return compressedSize; } - set { compressedSize = value; } - } - - /// - /// Get / set the uncompressed size of data - /// - public long Size - { - get { return size; } - set { size = value; } - } - - /// - /// Get /set the crc value. - /// - public long Crc - { - get { return crc; } - set { crc = (value & 0xffffffff); } - } - - #region Instance Fields - long size; - long compressedSize; - long crc; - #endregion - } - - class EntryPatchData - { - public long SizePatchOffset - { - get { return sizePatchOffset_; } - set { sizePatchOffset_ = value; } - } - - public long CrcPatchOffset - { - get { return crcPatchOffset_; } - set { crcPatchOffset_ = value; } - } - - #region Instance Fields - long sizePatchOffset_; - long crcPatchOffset_; - #endregion - } - - /// - /// This class assists with writing/reading from Zip files. - /// - internal class ZipHelperStream : Stream - { - #region Constructors - /// - /// Initialise an instance of this class. - /// - /// The name of the file to open. - public ZipHelperStream(string name) - { - stream_ = new FileStream(name, FileMode.Open, FileAccess.ReadWrite); - isOwner_ = true; - } - - /// - /// Initialise a new instance of . - /// - /// The stream to use. - public ZipHelperStream(Stream stream) - { - stream_ = stream; - } - #endregion - - /// - /// Get / set a value indicating wether the the underlying stream is owned or not. - /// - /// If the stream is owned it is closed when this instance is closed. - public bool IsStreamOwner - { - get { return isOwner_; } - set { isOwner_ = value; } - } - - #region Base Stream Methods - public override bool CanRead - { - get { return stream_.CanRead; } - } - - public override bool CanSeek - { - get { return stream_.CanSeek; } - } + /// + /// Holds data pertinent to a data descriptor. + /// + public class DescriptorData + { + /// + /// Get /set the compressed size of data. + /// + public long CompressedSize + { + get { return compressedSize; } + set { compressedSize = value; } + } + + /// + /// Get / set the uncompressed size of data + /// + public long Size + { + get { return size; } + set { size = value; } + } + + /// + /// Get /set the crc value. + /// + public long Crc + { + get { return crc; } + set { crc = (value & 0xffffffff); } + } + + #region Instance Fields + long size; + long compressedSize; + long crc; + #endregion + } + + class EntryPatchData + { + public long SizePatchOffset + { + get { return sizePatchOffset_; } + set { sizePatchOffset_ = value; } + } + + public long CrcPatchOffset + { + get { return crcPatchOffset_; } + set { crcPatchOffset_ = value; } + } + + #region Instance Fields + long sizePatchOffset_; + long crcPatchOffset_; + #endregion + } + + /// + /// This class assists with writing/reading from Zip files. + /// + internal class ZipHelperStream : Stream + { + #region Constructors + /// + /// Initialise an instance of this class. + /// + /// The name of the file to open. + public ZipHelperStream(string name) + { + stream_ = new FileStream(name, FileMode.Open, FileAccess.ReadWrite); + isOwner_ = true; + } + + /// + /// Initialise a new instance of . + /// + /// The stream to use. + public ZipHelperStream(Stream stream) + { + stream_ = stream; + } + #endregion + + /// + /// Get / set a value indicating wether the the underlying stream is owned or not. + /// + /// If the stream is owned it is closed when this instance is closed. + public bool IsStreamOwner + { + get { return isOwner_; } + set { isOwner_ = value; } + } + + #region Base Stream Methods + public override bool CanRead + { + get { return stream_.CanRead; } + } + + public override bool CanSeek + { + get { return stream_.CanSeek; } + } #if !NET_1_0 && !NET_1_1 && !NETCF_1_0 - public override bool CanTimeout - { - get { return stream_.CanTimeout; } - } + public override bool CanTimeout + { + get { return stream_.CanTimeout; } + } #endif - public override long Length - { - get { return stream_.Length; } - } - - public override long Position - { - get { return stream_.Position; } - set { stream_.Position = value; } - } - - public override bool CanWrite - { - get { return stream_.CanWrite; } - } - - public override void Flush() - { - stream_.Flush(); - } - - public override long Seek(long offset, SeekOrigin origin) - { - return stream_.Seek(offset, origin); - } - - public override void SetLength(long value) - { - stream_.SetLength(value); - } - - public override int Read(byte[] buffer, int offset, int count) - { - return stream_.Read(buffer, offset, count); - } - - public override void Write(byte[] buffer, int offset, int count) - { - stream_.Write(buffer, offset, count); - } - - /// - /// Close the stream. - /// - /// - /// The underlying stream is closed only if is true. - /// - override public void Close() - { - Stream toClose = stream_; - stream_ = null; - if (isOwner_ && (toClose != null)) - { - isOwner_ = false; - toClose.Close(); - } - } - #endregion - - // Write the local file header - // TODO: ZipHelperStream.WriteLocalHeader is not yet used and needs checking for ZipFile and ZipOuptutStream usage - void WriteLocalHeader(ZipEntry entry, EntryPatchData patchData) - { - CompressionMethod method = entry.CompressionMethod; - bool headerInfoAvailable = true; // How to get this? - bool patchEntryHeader = false; - - WriteLEInt(ZipConstants.LocalHeaderSignature); - - WriteLEShort(entry.Version); - WriteLEShort(entry.Flags); - WriteLEShort((byte)method); - WriteLEInt((int)entry.DosTime); - - if (headerInfoAvailable == true) { - WriteLEInt((int)entry.Crc); - if ( entry.LocalHeaderRequiresZip64 ) { - WriteLEInt(-1); - WriteLEInt(-1); - } - else { - WriteLEInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); - WriteLEInt((int)entry.Size); - } - } else { - if (patchData != null) { - patchData.CrcPatchOffset = stream_.Position; - } - WriteLEInt(0); // Crc - - if ( patchData != null ) { - patchData.SizePatchOffset = stream_.Position; - } - - // For local header both sizes appear in Zip64 Extended Information - if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { - WriteLEInt(-1); - WriteLEInt(-1); - } - else { - WriteLEInt(0); // Compressed size - WriteLEInt(0); // Uncompressed size - } - } - - byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); - - if (name.Length > 0xFFFF) { - throw new ZipException("Entry name too long."); - } - - ZipExtraData ed = new ZipExtraData(entry.ExtraData); - - if (entry.LocalHeaderRequiresZip64 && (headerInfoAvailable || patchEntryHeader)) { - ed.StartNewEntry(); - if (headerInfoAvailable) { - ed.AddLeLong(entry.Size); - ed.AddLeLong(entry.CompressedSize); - } - else { - ed.AddLeLong(-1); - ed.AddLeLong(-1); - } - ed.AddNewEntry(1); - - if ( !ed.Find(1) ) { - throw new ZipException("Internal error cant find extra data"); - } - - if ( patchData != null ) { - patchData.SizePatchOffset = ed.CurrentReadIndex; - } - } - else { - ed.Delete(1); - } - - byte[] extra = ed.GetEntryData(); - - WriteLEShort(name.Length); - WriteLEShort(extra.Length); - - if ( name.Length > 0 ) { - stream_.Write(name, 0, name.Length); - } - - if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { - patchData.SizePatchOffset += stream_.Position; - } - - if ( extra.Length > 0 ) { - stream_.Write(extra, 0, extra.Length); - } - } - - /// - /// Locates a block with the desired . - /// - /// The signature to find. - /// Location, marking the end of block. - /// Minimum size of the block. - /// The maximum variable data. - /// Eeturns the offset of the first byte after the signature; -1 if not found - public long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) - { - long pos = endLocation - minimumBlockSize; - if ( pos < 0 ) { - return -1; - } - - long giveUpMarker = Math.Max(pos - maximumVariableData, 0); - - // TODO: This loop could be optimised for speed. - do { - if ( pos < giveUpMarker ) { - return -1; - } - Seek(pos--, SeekOrigin.Begin); - } while ( ReadLEInt() != signature ); - - return Position; - } - - /// - /// Write Zip64 end of central directory records (File header and locator). - /// - /// The number of entries in the central directory. - /// The size of entries in the central directory. - /// The offset of the dentral directory. - public void WriteZip64EndOfCentralDirectory(long noOfEntries, long sizeEntries, long centralDirOffset) - { - long centralSignatureOffset = stream_.Position; - WriteLEInt(ZipConstants.Zip64CentralFileHeaderSignature); - WriteLELong(44); // Size of this record (total size of remaining fields in header or full size - 12) - WriteLEShort(ZipConstants.VersionMadeBy); // Version made by - WriteLEShort(ZipConstants.VersionZip64); // Version to extract - WriteLEInt(0); // Number of this disk - WriteLEInt(0); // number of the disk with the start of the central directory - WriteLELong(noOfEntries); // No of entries on this disk - WriteLELong(noOfEntries); // Total No of entries in central directory - WriteLELong(sizeEntries); // Size of the central directory - WriteLELong(centralDirOffset); // offset of start of central directory - // zip64 extensible data sector not catered for here (variable size) - - // Write the Zip64 end of central directory locator - WriteLEInt(ZipConstants.Zip64CentralDirLocatorSignature); - - // no of the disk with the start of the zip64 end of central directory - WriteLEInt(0); - - // relative offset of the zip64 end of central directory record - WriteLELong(centralSignatureOffset); - - // total number of disks - WriteLEInt(1); - } - - /// - /// Write the required records to end the central directory. - /// - /// The number of entries in the directory. - /// The size of the entries in the directory. - /// The start of the central directory. - /// The archive comment. (This can be null). - public void WriteEndOfCentralDirectory(long noOfEntries, long sizeEntries, - long startOfCentralDirectory, byte[] comment) - { - - if ( (noOfEntries >= 0xffff) || - (startOfCentralDirectory >= 0xffffffff) || - (sizeEntries >= 0xffffffff) ) { - WriteZip64EndOfCentralDirectory(noOfEntries, sizeEntries, startOfCentralDirectory); - } - - WriteLEInt(ZipConstants.EndOfCentralDirectorySignature); - - // TODO: ZipFile Multi disk handling not done - WriteLEShort(0); // number of this disk - WriteLEShort(0); // no of disk with start of central dir - - - // Number of entries - if ( noOfEntries >= 0xffff ) { - WriteLEUshort(0xffff); // Zip64 marker - WriteLEUshort(0xffff); - } - else { - WriteLEShort(( short )noOfEntries); // entries in central dir for this disk - WriteLEShort(( short )noOfEntries); // total entries in central directory - } - - // Size of the central directory - if ( sizeEntries >= 0xffffffff ) { - WriteLEUint(0xffffffff); // Zip64 marker - } - else { - WriteLEInt(( int )sizeEntries); - } - - - // offset of start of central directory - if ( startOfCentralDirectory >= 0xffffffff ) { - WriteLEUint(0xffffffff); // Zip64 marker - } - else { - WriteLEInt(( int )startOfCentralDirectory); - } - - int commentLength = (comment != null) ? comment.Length : 0; - - if ( commentLength > 0xffff ) { - throw new ZipException(string.Format("Comment length({0}) is too long can only be 64K", commentLength)); - } - - WriteLEShort(commentLength); - - if ( commentLength > 0 ) { - Write(comment, 0, comment.Length); - } - } - - #region LE value reading/writing - /// - /// Read an unsigned short in little endian byte order. - /// - /// Returns the value read. - /// - /// An i/o error occurs. - /// - /// - /// The file ends prematurely - /// - public int ReadLEShort() - { - int byteValue1 = stream_.ReadByte(); - - if (byteValue1 < 0) { - throw new EndOfStreamException(); - } - - int byteValue2 = stream_.ReadByte(); - if (byteValue2 < 0) { - throw new EndOfStreamException(); - } - - return byteValue1 | (byteValue2 << 8); - } - - /// - /// Read an int in little endian byte order. - /// - /// Returns the value read. - /// - /// An i/o error occurs. - /// - /// - /// The file ends prematurely - /// - public int ReadLEInt() - { - return ReadLEShort() | (ReadLEShort() << 16); - } - - /// - /// Read a long in little endian byte order. - /// - /// The value read. - public long ReadLELong() - { - return (uint)ReadLEInt() | ((long)ReadLEInt() << 32); - } - - /// - /// Write an unsigned short in little endian byte order. - /// - /// The value to write. - public void WriteLEShort(int value) - { - stream_.WriteByte(( byte )(value & 0xff)); - stream_.WriteByte(( byte )((value >> 8) & 0xff)); - } - - /// - /// Write a ushort in little endian byte order. - /// - /// The value to write. - public void WriteLEUshort(ushort value) - { - stream_.WriteByte(( byte )(value & 0xff)); - stream_.WriteByte(( byte )(value >> 8)); - } - - /// - /// Write an int in little endian byte order. - /// - /// The value to write. - public void WriteLEInt(int value) - { - WriteLEShort(value); - WriteLEShort(value >> 16); - } - - /// - /// Write a uint in little endian byte order. - /// - /// The value to write. - public void WriteLEUint(uint value) - { - WriteLEUshort(( ushort )(value & 0xffff)); - WriteLEUshort(( ushort )(value >> 16)); - } - - /// - /// Write a long in little endian byte order. - /// - /// The value to write. - public void WriteLELong(long value) - { - WriteLEInt(( int )value); - WriteLEInt(( int )(value >> 32)); - } - - /// - /// Write a ulong in little endian byte order. - /// - /// The value to write. - public void WriteLEUlong(ulong value) - { - WriteLEUint(( uint )(value & 0xffffffff)); - WriteLEUint(( uint )(value >> 32)); - } - - #endregion - - /// - /// Write a data descriptor. - /// - /// The entry to write a descriptor for. - /// Returns the number of descriptor bytes written. - public int WriteDataDescriptor(ZipEntry entry) - { - if (entry == null) { - throw new ArgumentNullException("entry"); - } - - int result=0; - - // Add data descriptor if flagged as required - if ((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) - { - // The signature is not PKZIP originally but is now described as optional - // in the PKZIP Appnote documenting trhe format. - WriteLEInt(ZipConstants.DataDescriptorSignature); - WriteLEInt(unchecked((int)(entry.Crc))); - - result+=8; - - if (entry.LocalHeaderRequiresZip64) - { - WriteLELong(entry.CompressedSize); - WriteLELong(entry.Size); - result+=16; - } - else - { - WriteLEInt((int)entry.CompressedSize); - WriteLEInt((int)entry.Size); - result+=8; - } - } - - return result; - } - - /// - /// Read data descriptor at the end of compressed data. - /// - /// if set to true [zip64]. - /// The data to fill in. - /// Returns the number of bytes read in the descriptor. - public void ReadDataDescriptor(bool zip64, DescriptorData data) - { - int intValue = ReadLEInt(); - - // In theory this may not be a descriptor according to PKZIP appnote. - // In practise its always there. - if (intValue != ZipConstants.DataDescriptorSignature) { - throw new ZipException("Data descriptor signature not found"); - } - - data.Crc = ReadLEInt(); - - if (zip64) { - data.CompressedSize = ReadLELong(); - data.Size = ReadLELong(); - } - else { - data.CompressedSize = ReadLEInt(); - data.Size = ReadLEInt(); - } - } - - #region Instance Fields - bool isOwner_; - Stream stream_; - #endregion - } + public override long Length + { + get { return stream_.Length; } + } + + public override long Position + { + get { return stream_.Position; } + set { stream_.Position = value; } + } + + public override bool CanWrite + { + get { return stream_.CanWrite; } + } + + public override void Flush() + { + stream_.Flush(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + return stream_.Seek(offset, origin); + } + + public override void SetLength(long value) + { + stream_.SetLength(value); + } + + public override int Read(byte[] buffer, int offset, int count) + { + return stream_.Read(buffer, offset, count); + } + + public override void Write(byte[] buffer, int offset, int count) + { + stream_.Write(buffer, offset, count); + } + + /// + /// Close the stream. + /// + /// + /// The underlying stream is closed only if is true. + /// + override public void Close() + { + Stream toClose = stream_; + stream_ = null; + if (isOwner_ && (toClose != null)) + { + isOwner_ = false; + toClose.Close(); + } + } + #endregion + + // Write the local file header + // TODO: ZipHelperStream.WriteLocalHeader is not yet used and needs checking for ZipFile and ZipOuptutStream usage + void WriteLocalHeader(ZipEntry entry, EntryPatchData patchData) + { + CompressionMethod method = entry.CompressionMethod; + bool headerInfoAvailable = true; // How to get this? + bool patchEntryHeader = false; + + WriteLEInt(ZipConstants.LocalHeaderSignature); + + WriteLEShort(entry.Version); + WriteLEShort(entry.Flags); + WriteLEShort((byte)method); + WriteLEInt((int)entry.DosTime); + + if (headerInfoAvailable == true) { + WriteLEInt((int)entry.Crc); + if ( entry.LocalHeaderRequiresZip64 ) { + WriteLEInt(-1); + WriteLEInt(-1); + } + else { + WriteLEInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); + WriteLEInt((int)entry.Size); + } + } else { + if (patchData != null) { + patchData.CrcPatchOffset = stream_.Position; + } + WriteLEInt(0); // Crc + + if ( patchData != null ) { + patchData.SizePatchOffset = stream_.Position; + } + + // For local header both sizes appear in Zip64 Extended Information + if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { + WriteLEInt(-1); + WriteLEInt(-1); + } + else { + WriteLEInt(0); // Compressed size + WriteLEInt(0); // Uncompressed size + } + } + + byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); + + if (name.Length > 0xFFFF) { + throw new ZipException("Entry name too long."); + } + + ZipExtraData ed = new ZipExtraData(entry.ExtraData); + + if (entry.LocalHeaderRequiresZip64 && (headerInfoAvailable || patchEntryHeader)) { + ed.StartNewEntry(); + if (headerInfoAvailable) { + ed.AddLeLong(entry.Size); + ed.AddLeLong(entry.CompressedSize); + } + else { + ed.AddLeLong(-1); + ed.AddLeLong(-1); + } + ed.AddNewEntry(1); + + if ( !ed.Find(1) ) { + throw new ZipException("Internal error cant find extra data"); + } + + if ( patchData != null ) { + patchData.SizePatchOffset = ed.CurrentReadIndex; + } + } + else { + ed.Delete(1); + } + + byte[] extra = ed.GetEntryData(); + + WriteLEShort(name.Length); + WriteLEShort(extra.Length); + + if ( name.Length > 0 ) { + stream_.Write(name, 0, name.Length); + } + + if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { + patchData.SizePatchOffset += stream_.Position; + } + + if ( extra.Length > 0 ) { + stream_.Write(extra, 0, extra.Length); + } + } + + /// + /// Locates a block with the desired . + /// + /// The signature to find. + /// Location, marking the end of block. + /// Minimum size of the block. + /// The maximum variable data. + /// Eeturns the offset of the first byte after the signature; -1 if not found + public long LocateBlockWithSignature(int signature, long endLocation, int minimumBlockSize, int maximumVariableData) + { + long pos = endLocation - minimumBlockSize; + if ( pos < 0 ) { + return -1; + } + + long giveUpMarker = Math.Max(pos - maximumVariableData, 0); + + // TODO: This loop could be optimised for speed. + do { + if ( pos < giveUpMarker ) { + return -1; + } + Seek(pos--, SeekOrigin.Begin); + } while ( ReadLEInt() != signature ); + + return Position; + } + + /// + /// Write Zip64 end of central directory records (File header and locator). + /// + /// The number of entries in the central directory. + /// The size of entries in the central directory. + /// The offset of the dentral directory. + public void WriteZip64EndOfCentralDirectory(long noOfEntries, long sizeEntries, long centralDirOffset) + { + long centralSignatureOffset = stream_.Position; + WriteLEInt(ZipConstants.Zip64CentralFileHeaderSignature); + WriteLELong(44); // Size of this record (total size of remaining fields in header or full size - 12) + WriteLEShort(ZipConstants.VersionMadeBy); // Version made by + WriteLEShort(ZipConstants.VersionZip64); // Version to extract + WriteLEInt(0); // Number of this disk + WriteLEInt(0); // number of the disk with the start of the central directory + WriteLELong(noOfEntries); // No of entries on this disk + WriteLELong(noOfEntries); // Total No of entries in central directory + WriteLELong(sizeEntries); // Size of the central directory + WriteLELong(centralDirOffset); // offset of start of central directory + // zip64 extensible data sector not catered for here (variable size) + + // Write the Zip64 end of central directory locator + WriteLEInt(ZipConstants.Zip64CentralDirLocatorSignature); + + // no of the disk with the start of the zip64 end of central directory + WriteLEInt(0); + + // relative offset of the zip64 end of central directory record + WriteLELong(centralSignatureOffset); + + // total number of disks + WriteLEInt(1); + } + + /// + /// Write the required records to end the central directory. + /// + /// The number of entries in the directory. + /// The size of the entries in the directory. + /// The start of the central directory. + /// The archive comment. (This can be null). + public void WriteEndOfCentralDirectory(long noOfEntries, long sizeEntries, + long startOfCentralDirectory, byte[] comment) + { + + if ( (noOfEntries >= 0xffff) || + (startOfCentralDirectory >= 0xffffffff) || + (sizeEntries >= 0xffffffff) ) { + WriteZip64EndOfCentralDirectory(noOfEntries, sizeEntries, startOfCentralDirectory); + } + + WriteLEInt(ZipConstants.EndOfCentralDirectorySignature); + + // TODO: ZipFile Multi disk handling not done + WriteLEShort(0); // number of this disk + WriteLEShort(0); // no of disk with start of central dir + + + // Number of entries + if ( noOfEntries >= 0xffff ) { + WriteLEUshort(0xffff); // Zip64 marker + WriteLEUshort(0xffff); + } + else { + WriteLEShort(( short )noOfEntries); // entries in central dir for this disk + WriteLEShort(( short )noOfEntries); // total entries in central directory + } + + // Size of the central directory + if ( sizeEntries >= 0xffffffff ) { + WriteLEUint(0xffffffff); // Zip64 marker + } + else { + WriteLEInt(( int )sizeEntries); + } + + + // offset of start of central directory + if ( startOfCentralDirectory >= 0xffffffff ) { + WriteLEUint(0xffffffff); // Zip64 marker + } + else { + WriteLEInt(( int )startOfCentralDirectory); + } + + int commentLength = (comment != null) ? comment.Length : 0; + + if ( commentLength > 0xffff ) { + throw new ZipException(string.Format("Comment length({0}) is too long can only be 64K", commentLength)); + } + + WriteLEShort(commentLength); + + if ( commentLength > 0 ) { + Write(comment, 0, comment.Length); + } + } + + #region LE value reading/writing + /// + /// Read an unsigned short in little endian byte order. + /// + /// Returns the value read. + /// + /// An i/o error occurs. + /// + /// + /// The file ends prematurely + /// + public int ReadLEShort() + { + int byteValue1 = stream_.ReadByte(); + + if (byteValue1 < 0) { + throw new EndOfStreamException(); + } + + int byteValue2 = stream_.ReadByte(); + if (byteValue2 < 0) { + throw new EndOfStreamException(); + } + + return byteValue1 | (byteValue2 << 8); + } + + /// + /// Read an int in little endian byte order. + /// + /// Returns the value read. + /// + /// An i/o error occurs. + /// + /// + /// The file ends prematurely + /// + public int ReadLEInt() + { + return ReadLEShort() | (ReadLEShort() << 16); + } + + /// + /// Read a long in little endian byte order. + /// + /// The value read. + public long ReadLELong() + { + return (uint)ReadLEInt() | ((long)ReadLEInt() << 32); + } + + /// + /// Write an unsigned short in little endian byte order. + /// + /// The value to write. + public void WriteLEShort(int value) + { + stream_.WriteByte(( byte )(value & 0xff)); + stream_.WriteByte(( byte )((value >> 8) & 0xff)); + } + + /// + /// Write a ushort in little endian byte order. + /// + /// The value to write. + public void WriteLEUshort(ushort value) + { + stream_.WriteByte(( byte )(value & 0xff)); + stream_.WriteByte(( byte )(value >> 8)); + } + + /// + /// Write an int in little endian byte order. + /// + /// The value to write. + public void WriteLEInt(int value) + { + WriteLEShort(value); + WriteLEShort(value >> 16); + } + + /// + /// Write a uint in little endian byte order. + /// + /// The value to write. + public void WriteLEUint(uint value) + { + WriteLEUshort(( ushort )(value & 0xffff)); + WriteLEUshort(( ushort )(value >> 16)); + } + + /// + /// Write a long in little endian byte order. + /// + /// The value to write. + public void WriteLELong(long value) + { + WriteLEInt(( int )value); + WriteLEInt(( int )(value >> 32)); + } + + /// + /// Write a ulong in little endian byte order. + /// + /// The value to write. + public void WriteLEUlong(ulong value) + { + WriteLEUint(( uint )(value & 0xffffffff)); + WriteLEUint(( uint )(value >> 32)); + } + + #endregion + + /// + /// Write a data descriptor. + /// + /// The entry to write a descriptor for. + /// Returns the number of descriptor bytes written. + public int WriteDataDescriptor(ZipEntry entry) + { + if (entry == null) { + throw new ArgumentNullException("entry"); + } + + int result=0; + + // Add data descriptor if flagged as required + if ((entry.Flags & (int)GeneralBitFlags.Descriptor) != 0) + { + // The signature is not PKZIP originally but is now described as optional + // in the PKZIP Appnote documenting trhe format. + WriteLEInt(ZipConstants.DataDescriptorSignature); + WriteLEInt(unchecked((int)(entry.Crc))); + + result+=8; + + if (entry.LocalHeaderRequiresZip64) + { + WriteLELong(entry.CompressedSize); + WriteLELong(entry.Size); + result+=16; + } + else + { + WriteLEInt((int)entry.CompressedSize); + WriteLEInt((int)entry.Size); + result+=8; + } + } + + return result; + } + + /// + /// Read data descriptor at the end of compressed data. + /// + /// if set to true [zip64]. + /// The data to fill in. + /// Returns the number of bytes read in the descriptor. + public void ReadDataDescriptor(bool zip64, DescriptorData data) + { + int intValue = ReadLEInt(); + + // In theory this may not be a descriptor according to PKZIP appnote. + // In practise its always there. + if (intValue != ZipConstants.DataDescriptorSignature) { + throw new ZipException("Data descriptor signature not found"); + } + + data.Crc = ReadLEInt(); + + if (zip64) { + data.CompressedSize = ReadLELong(); + data.Size = ReadLELong(); + } + else { + data.CompressedSize = ReadLEInt(); + data.Size = ReadLEInt(); + } + } + + #region Instance Fields + bool isOwner_; + Stream stream_; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipInputStream.cs b/External/Tools/AppMan/ZipLib/Zip/ZipInputStream.cs index b481ea1649..ba8445ab71 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipInputStream.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipInputStream.cs @@ -38,7 +38,7 @@ // exception statement from your version. // HISTORY -// 2010-05-25 Z-1663 Fixed exception when testing local header compressed size of -1 +// 2010-05-25 Z-1663 Fixed exception when testing local header compressed size of -1 using System; using System.IO; @@ -53,87 +53,87 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// This is an InflaterInputStream that reads the files baseInputStream an zip archive - /// one after another. It has a special method to get the zip entry of - /// the next file. The zip entry contains information about the file name - /// size, compressed size, Crc, etc. - /// It includes support for Stored and Deflated entries. - ///
    - ///
    Author of the original java version : Jochen Hoenicke - ///
    - /// - /// This sample shows how to read a zip file - /// - /// using System; - /// using System.Text; - /// using System.IO; - /// - /// using ICSharpCode.SharpZipLib.Zip; - /// - /// class MainClass - /// { - /// public static void Main(string[] args) - /// { - /// using ( ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]))) { - /// - /// ZipEntry theEntry; - /// const int size = 2048; - /// byte[] data = new byte[2048]; - /// - /// while ((theEntry = s.GetNextEntry()) != null) { - /// if ( entry.IsFile ) { - /// Console.Write("Show contents (y/n) ?"); - /// if (Console.ReadLine() == "y") { - /// while (true) { - /// size = s.Read(data, 0, data.Length); - /// if (size > 0) { - /// Console.Write(new ASCIIEncoding().GetString(data, 0, size)); - /// } else { - /// break; - /// } - /// } - /// } - /// } - /// } - /// } - /// } - /// } - /// - /// - public class ZipInputStream : InflaterInputStream - { - #region Instance Fields - - /// - /// Delegate for reading bytes from a stream. - /// - delegate int ReadDataHandler(byte[] b, int offset, int length); - - /// - /// The current reader this instance. - /// - ReadDataHandler internalReader; - - Crc32 crc = new Crc32(); - ZipEntry entry; - - long size; - int method; - int flags; - string password; - #endregion - - #region Constructors - /// - /// Creates a new Zip input stream, for reading a zip archive. - /// - /// The underlying providing data. - public ZipInputStream(Stream baseInputStream) - : base(baseInputStream, new Inflater(true)) - { - internalReader = new ReadDataHandler(ReadingNotAvailable); - } + /// + /// This is an InflaterInputStream that reads the files baseInputStream an zip archive + /// one after another. It has a special method to get the zip entry of + /// the next file. The zip entry contains information about the file name + /// size, compressed size, Crc, etc. + /// It includes support for Stored and Deflated entries. + ///
    + ///
    Author of the original java version : Jochen Hoenicke + ///
    + /// + /// This sample shows how to read a zip file + /// + /// using System; + /// using System.Text; + /// using System.IO; + /// + /// using ICSharpCode.SharpZipLib.Zip; + /// + /// class MainClass + /// { + /// public static void Main(string[] args) + /// { + /// using ( ZipInputStream s = new ZipInputStream(File.OpenRead(args[0]))) { + /// + /// ZipEntry theEntry; + /// const int size = 2048; + /// byte[] data = new byte[2048]; + /// + /// while ((theEntry = s.GetNextEntry()) != null) { + /// if ( entry.IsFile ) { + /// Console.Write("Show contents (y/n) ?"); + /// if (Console.ReadLine() == "y") { + /// while (true) { + /// size = s.Read(data, 0, data.Length); + /// if (size > 0) { + /// Console.Write(new ASCIIEncoding().GetString(data, 0, size)); + /// } else { + /// break; + /// } + /// } + /// } + /// } + /// } + /// } + /// } + /// } + /// + /// + public class ZipInputStream : InflaterInputStream + { + #region Instance Fields + + /// + /// Delegate for reading bytes from a stream. + /// + delegate int ReadDataHandler(byte[] b, int offset, int length); + + /// + /// The current reader this instance. + /// + ReadDataHandler internalReader; + + Crc32 crc = new Crc32(); + ZipEntry entry; + + long size; + int method; + int flags; + string password; + #endregion + + #region Constructors + /// + /// Creates a new Zip input stream, for reading a zip archive. + /// + /// The underlying providing data. + public ZipInputStream(Stream baseInputStream) + : base(baseInputStream, new Inflater(true)) + { + internalReader = new ReadDataHandler(ReadingNotAvailable); + } /// /// Creates a new Zip input stream, for reading a zip archive. @@ -146,530 +146,530 @@ public ZipInputStream( Stream baseInputStream, int bufferSize ) internalReader = new ReadDataHandler(ReadingNotAvailable); } #endregion - - /// - /// Optional password used for encryption when non-null - /// - /// A password for all encrypted entries in this - public string Password - { - get { - return password; - } - set { - password = value; - } - } - - - /// - /// Gets a value indicating if there is a current entry and it can be decompressed - /// - /// - /// The entry can only be decompressed if the library supports the zip features required to extract it. - /// See the ZipEntry Version property for more details. - /// - public bool CanDecompressEntry { - get { - return (entry != null) && entry.CanDecompress; - } - } - - /// - /// Advances to the next entry in the archive - /// - /// - /// The next entry in the archive or null if there are no more entries. - /// - /// - /// If the previous entry is still open CloseEntry is called. - /// - /// - /// Input stream is closed - /// - /// - /// Password is not set, password is invalid, compression method is invalid, - /// version required to extract is not supported - /// - public ZipEntry GetNextEntry() - { - if (crc == null) { - throw new InvalidOperationException("Closed."); - } - - if (entry != null) { - CloseEntry(); - } - - int header = inputBuffer.ReadLeInt(); - - if (header == ZipConstants.CentralHeaderSignature || - header == ZipConstants.EndOfCentralDirectorySignature || - header == ZipConstants.CentralHeaderDigitalSignature || - header == ZipConstants.ArchiveExtraDataSignature || - header == ZipConstants.Zip64CentralFileHeaderSignature) { - // No more individual entries exist - Close(); - return null; - } - - // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found - // Spanning signature is same as descriptor signature and is untested as yet. - if ( (header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature) ) { - header = inputBuffer.ReadLeInt(); - } - - if (header != ZipConstants.LocalHeaderSignature) { - throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header)); - } - - short versionRequiredToExtract = (short)inputBuffer.ReadLeShort(); - - flags = inputBuffer.ReadLeShort(); - method = inputBuffer.ReadLeShort(); - uint dostime = (uint)inputBuffer.ReadLeInt(); - int crc2 = inputBuffer.ReadLeInt(); - csize = inputBuffer.ReadLeInt(); - size = inputBuffer.ReadLeInt(); - int nameLen = inputBuffer.ReadLeShort(); - int extraLen = inputBuffer.ReadLeShort(); - - bool isCrypted = (flags & 1) == 1; - - byte[] buffer = new byte[nameLen]; - inputBuffer.ReadRawBuffer(buffer); - - string name = ZipConstants.ConvertToStringExt(flags, buffer); - - entry = new ZipEntry(name, versionRequiredToExtract); - entry.Flags = flags; - - entry.CompressionMethod = (CompressionMethod)method; - - if ((flags & 8) == 0) { - entry.Crc = crc2 & 0xFFFFFFFFL; - entry.Size = size & 0xFFFFFFFFL; - entry.CompressedSize = csize & 0xFFFFFFFFL; - - entry.CryptoCheckValue = (byte)((crc2 >> 24) & 0xff); - - } else { - - // This allows for GNU, WinZip and possibly other archives, the PKZIP spec - // says these values are zero under these circumstances. - if (crc2 != 0) { - entry.Crc = crc2 & 0xFFFFFFFFL; - } - - if (size != 0) { - entry.Size = size & 0xFFFFFFFFL; - } - - if (csize != 0) { - entry.CompressedSize = csize & 0xFFFFFFFFL; - } - - entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff); - } - - entry.DosTime = dostime; - - // If local header requires Zip64 is true then the extended header should contain - // both values. - - // Handle extra data if present. This can set/alter some fields of the entry. - if (extraLen > 0) { - byte[] extra = new byte[extraLen]; - inputBuffer.ReadRawBuffer(extra); - entry.ExtraData = extra; - } - - entry.ProcessExtraData(true); - if ( entry.CompressedSize >= 0 ) { - csize = entry.CompressedSize; - } - - if ( entry.Size >= 0 ) { - size = entry.Size; - } - - if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size))) { - throw new ZipException("Stored, but compressed != uncompressed"); - } - - // Determine how to handle reading of data if this is attempted. - if (entry.IsCompressionMethodSupported()) { - internalReader = new ReadDataHandler(InitialRead); - } else { - internalReader = new ReadDataHandler(ReadingNotSupported); - } - - return entry; - } - - /// - /// Read data descriptor at the end of compressed data. - /// - void ReadDataDescriptor() - { - if (inputBuffer.ReadLeInt() != ZipConstants.DataDescriptorSignature) { - throw new ZipException("Data descriptor signature not found"); - } - - entry.Crc = inputBuffer.ReadLeInt() & 0xFFFFFFFFL; - - if ( entry.LocalHeaderRequiresZip64 ) { - csize = inputBuffer.ReadLeLong(); - size = inputBuffer.ReadLeLong(); - } else { - csize = inputBuffer.ReadLeInt(); - size = inputBuffer.ReadLeInt(); - } - entry.CompressedSize = csize; - entry.Size = size; - } - - /// - /// Complete cleanup as the final part of closing. - /// - /// True if the crc value should be tested - void CompleteCloseEntry(bool testCrc) - { - StopDecrypting(); - - if ((flags & 8) != 0) { - ReadDataDescriptor(); - } - - size = 0; - - if ( testCrc && - ((crc.Value & 0xFFFFFFFFL) != entry.Crc) && (entry.Crc != -1)) { - throw new ZipException("CRC mismatch"); - } - - crc.Reset(); - - if (method == (int)CompressionMethod.Deflated) { - inf.Reset(); - } - entry = null; - } - - /// - /// Closes the current zip entry and moves to the next one. - /// - /// - /// The stream is closed - /// - /// - /// The Zip stream ends early - /// - public void CloseEntry() - { - if (crc == null) { - throw new InvalidOperationException("Closed"); - } - - if (entry == null) { - return; - } - - if (method == (int)CompressionMethod.Deflated) { - if ((flags & 8) != 0) { - // We don't know how much we must skip, read until end. - byte[] tmp = new byte[4096]; - - // Read will close this entry - while (Read(tmp, 0, tmp.Length) > 0) { - } - return; - } - - csize -= inf.TotalIn; - inputBuffer.Available += inf.RemainingInput; - } - - if ( (inputBuffer.Available > csize) && (csize >= 0) ) { - inputBuffer.Available = (int)((long)inputBuffer.Available - csize); - } else { - csize -= inputBuffer.Available; - inputBuffer.Available = 0; - while (csize != 0) { - long skipped = base.Skip(csize); - - if (skipped <= 0) { - throw new ZipException("Zip archive ends early."); - } - - csize -= skipped; - } - } - - CompleteCloseEntry(false); - } - - /// - /// Returns 1 if there is an entry available - /// Otherwise returns 0. - /// - public override int Available { - get { - return entry != null ? 1 : 0; - } - } - - /// - /// Returns the current size that can be read from the current entry if available - /// - /// Thrown if the entry size is not known. - /// Thrown if no entry is currently available. - public override long Length - { - get { - if ( entry != null ) { - if ( entry.Size >= 0 ) { - return entry.Size; - } else { - throw new ZipException("Length not available for the current entry"); - } - } - else { - throw new InvalidOperationException("No current entry"); - } - } - - } - - /// - /// Reads a byte from the current zip entry. - /// - /// - /// The byte or -1 if end of stream is reached. - /// - public override int ReadByte() - { - byte[] b = new byte[1]; - if (Read(b, 0, 1) <= 0) { - return -1; - } - return b[0] & 0xff; - } - - /// - /// Handle attempts to read by throwing an . - /// - /// The destination array to store data in. - /// The offset at which data read should be stored. - /// The maximum number of bytes to read. - /// Returns the number of bytes actually read. - int ReadingNotAvailable(byte[] destination, int offset, int count) - { - throw new InvalidOperationException("Unable to read from this stream"); - } - - /// - /// Handle attempts to read from this entry by throwing an exception - /// - int ReadingNotSupported(byte[] destination, int offset, int count) - { - throw new ZipException("The compression method for this entry is not supported"); - } - - /// - /// Perform the initial read on an entry which may include - /// reading encryption headers and setting up inflation. - /// - /// The destination to fill with data read. - /// The offset to start reading at. - /// The maximum number of bytes to read. - /// The actual number of bytes read. - int InitialRead(byte[] destination, int offset, int count) - { - if ( !CanDecompressEntry ) { - throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version.ToString() + ")"); - } - - // Handle encryption if required. - if (entry.IsCrypted) { + + /// + /// Optional password used for encryption when non-null + /// + /// A password for all encrypted entries in this + public string Password + { + get { + return password; + } + set { + password = value; + } + } + + + /// + /// Gets a value indicating if there is a current entry and it can be decompressed + /// + /// + /// The entry can only be decompressed if the library supports the zip features required to extract it. + /// See the ZipEntry Version property for more details. + /// + public bool CanDecompressEntry { + get { + return (entry != null) && entry.CanDecompress; + } + } + + /// + /// Advances to the next entry in the archive + /// + /// + /// The next entry in the archive or null if there are no more entries. + /// + /// + /// If the previous entry is still open CloseEntry is called. + /// + /// + /// Input stream is closed + /// + /// + /// Password is not set, password is invalid, compression method is invalid, + /// version required to extract is not supported + /// + public ZipEntry GetNextEntry() + { + if (crc == null) { + throw new InvalidOperationException("Closed."); + } + + if (entry != null) { + CloseEntry(); + } + + int header = inputBuffer.ReadLeInt(); + + if (header == ZipConstants.CentralHeaderSignature || + header == ZipConstants.EndOfCentralDirectorySignature || + header == ZipConstants.CentralHeaderDigitalSignature || + header == ZipConstants.ArchiveExtraDataSignature || + header == ZipConstants.Zip64CentralFileHeaderSignature) { + // No more individual entries exist + Close(); + return null; + } + + // -jr- 07-Dec-2003 Ignore spanning temporary signatures if found + // Spanning signature is same as descriptor signature and is untested as yet. + if ( (header == ZipConstants.SpanningTempSignature) || (header == ZipConstants.SpanningSignature) ) { + header = inputBuffer.ReadLeInt(); + } + + if (header != ZipConstants.LocalHeaderSignature) { + throw new ZipException("Wrong Local header signature: 0x" + String.Format("{0:X}", header)); + } + + short versionRequiredToExtract = (short)inputBuffer.ReadLeShort(); + + flags = inputBuffer.ReadLeShort(); + method = inputBuffer.ReadLeShort(); + uint dostime = (uint)inputBuffer.ReadLeInt(); + int crc2 = inputBuffer.ReadLeInt(); + csize = inputBuffer.ReadLeInt(); + size = inputBuffer.ReadLeInt(); + int nameLen = inputBuffer.ReadLeShort(); + int extraLen = inputBuffer.ReadLeShort(); + + bool isCrypted = (flags & 1) == 1; + + byte[] buffer = new byte[nameLen]; + inputBuffer.ReadRawBuffer(buffer); + + string name = ZipConstants.ConvertToStringExt(flags, buffer); + + entry = new ZipEntry(name, versionRequiredToExtract); + entry.Flags = flags; + + entry.CompressionMethod = (CompressionMethod)method; + + if ((flags & 8) == 0) { + entry.Crc = crc2 & 0xFFFFFFFFL; + entry.Size = size & 0xFFFFFFFFL; + entry.CompressedSize = csize & 0xFFFFFFFFL; + + entry.CryptoCheckValue = (byte)((crc2 >> 24) & 0xff); + + } else { + + // This allows for GNU, WinZip and possibly other archives, the PKZIP spec + // says these values are zero under these circumstances. + if (crc2 != 0) { + entry.Crc = crc2 & 0xFFFFFFFFL; + } + + if (size != 0) { + entry.Size = size & 0xFFFFFFFFL; + } + + if (csize != 0) { + entry.CompressedSize = csize & 0xFFFFFFFFL; + } + + entry.CryptoCheckValue = (byte)((dostime >> 8) & 0xff); + } + + entry.DosTime = dostime; + + // If local header requires Zip64 is true then the extended header should contain + // both values. + + // Handle extra data if present. This can set/alter some fields of the entry. + if (extraLen > 0) { + byte[] extra = new byte[extraLen]; + inputBuffer.ReadRawBuffer(extra); + entry.ExtraData = extra; + } + + entry.ProcessExtraData(true); + if ( entry.CompressedSize >= 0 ) { + csize = entry.CompressedSize; + } + + if ( entry.Size >= 0 ) { + size = entry.Size; + } + + if (method == (int)CompressionMethod.Stored && (!isCrypted && csize != size || (isCrypted && csize - ZipConstants.CryptoHeaderSize != size))) { + throw new ZipException("Stored, but compressed != uncompressed"); + } + + // Determine how to handle reading of data if this is attempted. + if (entry.IsCompressionMethodSupported()) { + internalReader = new ReadDataHandler(InitialRead); + } else { + internalReader = new ReadDataHandler(ReadingNotSupported); + } + + return entry; + } + + /// + /// Read data descriptor at the end of compressed data. + /// + void ReadDataDescriptor() + { + if (inputBuffer.ReadLeInt() != ZipConstants.DataDescriptorSignature) { + throw new ZipException("Data descriptor signature not found"); + } + + entry.Crc = inputBuffer.ReadLeInt() & 0xFFFFFFFFL; + + if ( entry.LocalHeaderRequiresZip64 ) { + csize = inputBuffer.ReadLeLong(); + size = inputBuffer.ReadLeLong(); + } else { + csize = inputBuffer.ReadLeInt(); + size = inputBuffer.ReadLeInt(); + } + entry.CompressedSize = csize; + entry.Size = size; + } + + /// + /// Complete cleanup as the final part of closing. + /// + /// True if the crc value should be tested + void CompleteCloseEntry(bool testCrc) + { + StopDecrypting(); + + if ((flags & 8) != 0) { + ReadDataDescriptor(); + } + + size = 0; + + if ( testCrc && + ((crc.Value & 0xFFFFFFFFL) != entry.Crc) && (entry.Crc != -1)) { + throw new ZipException("CRC mismatch"); + } + + crc.Reset(); + + if (method == (int)CompressionMethod.Deflated) { + inf.Reset(); + } + entry = null; + } + + /// + /// Closes the current zip entry and moves to the next one. + /// + /// + /// The stream is closed + /// + /// + /// The Zip stream ends early + /// + public void CloseEntry() + { + if (crc == null) { + throw new InvalidOperationException("Closed"); + } + + if (entry == null) { + return; + } + + if (method == (int)CompressionMethod.Deflated) { + if ((flags & 8) != 0) { + // We don't know how much we must skip, read until end. + byte[] tmp = new byte[4096]; + + // Read will close this entry + while (Read(tmp, 0, tmp.Length) > 0) { + } + return; + } + + csize -= inf.TotalIn; + inputBuffer.Available += inf.RemainingInput; + } + + if ( (inputBuffer.Available > csize) && (csize >= 0) ) { + inputBuffer.Available = (int)((long)inputBuffer.Available - csize); + } else { + csize -= inputBuffer.Available; + inputBuffer.Available = 0; + while (csize != 0) { + long skipped = base.Skip(csize); + + if (skipped <= 0) { + throw new ZipException("Zip archive ends early."); + } + + csize -= skipped; + } + } + + CompleteCloseEntry(false); + } + + /// + /// Returns 1 if there is an entry available + /// Otherwise returns 0. + /// + public override int Available { + get { + return entry != null ? 1 : 0; + } + } + + /// + /// Returns the current size that can be read from the current entry if available + /// + /// Thrown if the entry size is not known. + /// Thrown if no entry is currently available. + public override long Length + { + get { + if ( entry != null ) { + if ( entry.Size >= 0 ) { + return entry.Size; + } else { + throw new ZipException("Length not available for the current entry"); + } + } + else { + throw new InvalidOperationException("No current entry"); + } + } + + } + + /// + /// Reads a byte from the current zip entry. + /// + /// + /// The byte or -1 if end of stream is reached. + /// + public override int ReadByte() + { + byte[] b = new byte[1]; + if (Read(b, 0, 1) <= 0) { + return -1; + } + return b[0] & 0xff; + } + + /// + /// Handle attempts to read by throwing an . + /// + /// The destination array to store data in. + /// The offset at which data read should be stored. + /// The maximum number of bytes to read. + /// Returns the number of bytes actually read. + int ReadingNotAvailable(byte[] destination, int offset, int count) + { + throw new InvalidOperationException("Unable to read from this stream"); + } + + /// + /// Handle attempts to read from this entry by throwing an exception + /// + int ReadingNotSupported(byte[] destination, int offset, int count) + { + throw new ZipException("The compression method for this entry is not supported"); + } + + /// + /// Perform the initial read on an entry which may include + /// reading encryption headers and setting up inflation. + /// + /// The destination to fill with data read. + /// The offset to start reading at. + /// The maximum number of bytes to read. + /// The actual number of bytes read. + int InitialRead(byte[] destination, int offset, int count) + { + if ( !CanDecompressEntry ) { + throw new ZipException("Library cannot extract this entry. Version required is (" + entry.Version.ToString() + ")"); + } + + // Handle encryption if required. + if (entry.IsCrypted) { #if NETCF_1_0 - throw new ZipException("Encryption not supported for Compact Framework 1.0"); + throw new ZipException("Encryption not supported for Compact Framework 1.0"); #else - if (password == null) { - throw new ZipException("No password set."); - } - - // Generate and set crypto transform... - PkzipClassicManaged managed = new PkzipClassicManaged(); - byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); - - inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null); - - byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; - inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize); - - if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) { - throw new ZipException("Invalid password"); - } - - if (csize >= ZipConstants.CryptoHeaderSize) { - csize -= ZipConstants.CryptoHeaderSize; - } - else if ( (entry.Flags & (int)GeneralBitFlags.Descriptor) == 0 ) { - throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize)); - } -#endif - } else { + if (password == null) { + throw new ZipException("No password set."); + } + + // Generate and set crypto transform... + PkzipClassicManaged managed = new PkzipClassicManaged(); + byte[] key = PkzipClassic.GenerateKeys(ZipConstants.ConvertToArray(password)); + + inputBuffer.CryptoTransform = managed.CreateDecryptor(key, null); + + byte[] cryptbuffer = new byte[ZipConstants.CryptoHeaderSize]; + inputBuffer.ReadClearTextBuffer(cryptbuffer, 0, ZipConstants.CryptoHeaderSize); + + if (cryptbuffer[ZipConstants.CryptoHeaderSize - 1] != entry.CryptoCheckValue) { + throw new ZipException("Invalid password"); + } + + if (csize >= ZipConstants.CryptoHeaderSize) { + csize -= ZipConstants.CryptoHeaderSize; + } + else if ( (entry.Flags & (int)GeneralBitFlags.Descriptor) == 0 ) { + throw new ZipException(string.Format("Entry compressed size {0} too small for encryption", csize)); + } +#endif + } else { #if !NETCF_1_0 - inputBuffer.CryptoTransform = null; -#endif - } - - if ((csize > 0) || ((flags & (int)GeneralBitFlags.Descriptor) != 0)) { - if ((method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0)) { - inputBuffer.SetInflaterInput(inf); - } - - internalReader = new ReadDataHandler(BodyRead); - return BodyRead(destination, offset, count); - } - else { - internalReader = new ReadDataHandler(ReadingNotAvailable); - return 0; - } - } - - /// - /// Read a block of bytes from the stream. - /// - /// The destination for the bytes. - /// The index to start storing data. - /// The number of bytes to attempt to read. - /// Returns the number of bytes read. - /// Zero bytes read means end of stream. - public override int Read(byte[] buffer, int offset, int count) - { - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } - - if ( offset < 0 ) { + inputBuffer.CryptoTransform = null; +#endif + } + + if ((csize > 0) || ((flags & (int)GeneralBitFlags.Descriptor) != 0)) { + if ((method == (int)CompressionMethod.Deflated) && (inputBuffer.Available > 0)) { + inputBuffer.SetInflaterInput(inf); + } + + internalReader = new ReadDataHandler(BodyRead); + return BodyRead(destination, offset, count); + } + else { + internalReader = new ReadDataHandler(ReadingNotAvailable); + return 0; + } + } + + /// + /// Read a block of bytes from the stream. + /// + /// The destination for the bytes. + /// The index to start storing data. + /// The number of bytes to attempt to read. + /// Returns the number of bytes read. + /// Zero bytes read means end of stream. + public override int Read(byte[] buffer, int offset, int count) + { + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } + + if ( offset < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); -#endif - } + throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); +#endif + } - if ( count < 0 ) { + if ( count < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "Cannot be negative"); + throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif - } - - if ( (buffer.Length - offset) < count ) { - throw new ArgumentException("Invalid offset/count combination"); - } - - return internalReader(buffer, offset, count); - } - - /// - /// Reads a block of bytes from the current zip entry. - /// - /// - /// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream. - /// - /// - /// An i/o error occured. - /// - /// - /// The deflated stream is corrupted. - /// - /// - /// The stream is not open. - /// - int BodyRead(byte[] buffer, int offset, int count) - { - if ( crc == null ) { - throw new InvalidOperationException("Closed"); - } - - if ( (entry == null) || (count <= 0) ) { - return 0; - } - - if ( offset + count > buffer.Length ) { - throw new ArgumentException("Offset + count exceeds buffer size"); - } - - bool finished = false; - - switch (method) { - case (int)CompressionMethod.Deflated: - count = base.Read(buffer, offset, count); - if (count <= 0) { - if (!inf.IsFinished) { - throw new ZipException("Inflater not finished!"); - } - inputBuffer.Available = inf.RemainingInput; - - // A csize of -1 is from an unpatched local header - if ((flags & 8) == 0 && - (inf.TotalIn != csize && csize != 0xFFFFFFFF && csize != -1 || inf.TotalOut != size)) { - throw new ZipException("Size mismatch: " + csize + ";" + size + " <-> " + inf.TotalIn + ";" + inf.TotalOut); - } - inf.Reset(); - finished = true; - } - break; - - case (int)CompressionMethod.Stored: - if ( (count > csize) && (csize >= 0) ) { - count = (int)csize; - } - - if ( count > 0 ) { - count = inputBuffer.ReadClearTextBuffer(buffer, offset, count); - if (count > 0) { - csize -= count; - size -= count; - } - } - - if (csize == 0) { - finished = true; - } else { - if (count < 0) { - throw new ZipException("EOF in stored block"); - } - } - break; - } - - if (count > 0) { - crc.Update(buffer, offset, count); - } - - if (finished) { - CompleteCloseEntry(true); - } - - return count; - } - - /// - /// Closes the zip input stream - /// - public override void Close() - { - internalReader = new ReadDataHandler(ReadingNotAvailable); - crc = null; - entry = null; - - base.Close(); - } - } + } + + if ( (buffer.Length - offset) < count ) { + throw new ArgumentException("Invalid offset/count combination"); + } + + return internalReader(buffer, offset, count); + } + + /// + /// Reads a block of bytes from the current zip entry. + /// + /// + /// The number of bytes read (this may be less than the length requested, even before the end of stream), or 0 on end of stream. + /// + /// + /// An i/o error occured. + /// + /// + /// The deflated stream is corrupted. + /// + /// + /// The stream is not open. + /// + int BodyRead(byte[] buffer, int offset, int count) + { + if ( crc == null ) { + throw new InvalidOperationException("Closed"); + } + + if ( (entry == null) || (count <= 0) ) { + return 0; + } + + if ( offset + count > buffer.Length ) { + throw new ArgumentException("Offset + count exceeds buffer size"); + } + + bool finished = false; + + switch (method) { + case (int)CompressionMethod.Deflated: + count = base.Read(buffer, offset, count); + if (count <= 0) { + if (!inf.IsFinished) { + throw new ZipException("Inflater not finished!"); + } + inputBuffer.Available = inf.RemainingInput; + + // A csize of -1 is from an unpatched local header + if ((flags & 8) == 0 && + (inf.TotalIn != csize && csize != 0xFFFFFFFF && csize != -1 || inf.TotalOut != size)) { + throw new ZipException("Size mismatch: " + csize + ";" + size + " <-> " + inf.TotalIn + ";" + inf.TotalOut); + } + inf.Reset(); + finished = true; + } + break; + + case (int)CompressionMethod.Stored: + if ( (count > csize) && (csize >= 0) ) { + count = (int)csize; + } + + if ( count > 0 ) { + count = inputBuffer.ReadClearTextBuffer(buffer, offset, count); + if (count > 0) { + csize -= count; + size -= count; + } + } + + if (csize == 0) { + finished = true; + } else { + if (count < 0) { + throw new ZipException("EOF in stored block"); + } + } + break; + } + + if (count > 0) { + crc.Update(buffer, offset, count); + } + + if (finished) { + CompleteCloseEntry(true); + } + + return count; + } + + /// + /// Closes the zip input stream + /// + public override void Close() + { + internalReader = new ReadDataHandler(ReadingNotAvailable); + crc = null; + entry = null; + + base.Close(); + } + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipNameTransform.cs b/External/Tools/AppMan/ZipLib/Zip/ZipNameTransform.cs index 9dc1176c27..5055e571c8 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipNameTransform.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipNameTransform.cs @@ -42,228 +42,228 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// ZipNameTransform transforms names as per the Zip file naming convention. - /// - /// The use of absolute names is supported although its use is not valid - /// according to Zip naming conventions, and should not be used if maximum compatability is desired. - public class ZipNameTransform : INameTransform - { - #region Constructors - /// - /// Initialize a new instance of - /// - public ZipNameTransform() - { - } + /// + /// ZipNameTransform transforms names as per the Zip file naming convention. + /// + /// The use of absolute names is supported although its use is not valid + /// according to Zip naming conventions, and should not be used if maximum compatability is desired. + public class ZipNameTransform : INameTransform + { + #region Constructors + /// + /// Initialize a new instance of + /// + public ZipNameTransform() + { + } - /// - /// Initialize a new instance of - /// - /// The string to trim from the front of paths if found. - public ZipNameTransform(string trimPrefix) - { - TrimPrefix = trimPrefix; - } - #endregion - - /// - /// Static constructor. - /// - static ZipNameTransform() - { - char[] invalidPathChars; + /// + /// Initialize a new instance of + /// + /// The string to trim from the front of paths if found. + public ZipNameTransform(string trimPrefix) + { + TrimPrefix = trimPrefix; + } + #endregion + + /// + /// Static constructor. + /// + static ZipNameTransform() + { + char[] invalidPathChars; #if NET_1_0 || NET_1_1 || NETCF_1_0 - invalidPathChars = Path.InvalidPathChars; + invalidPathChars = Path.InvalidPathChars; #else - invalidPathChars = Path.GetInvalidPathChars(); + invalidPathChars = Path.GetInvalidPathChars(); #endif - int howMany = invalidPathChars.Length + 2; + int howMany = invalidPathChars.Length + 2; - InvalidEntryCharsRelaxed = new char[howMany]; - Array.Copy(invalidPathChars, 0, InvalidEntryCharsRelaxed, 0, invalidPathChars.Length); - InvalidEntryCharsRelaxed[howMany - 1] = '*'; - InvalidEntryCharsRelaxed[howMany - 2] = '?'; + InvalidEntryCharsRelaxed = new char[howMany]; + Array.Copy(invalidPathChars, 0, InvalidEntryCharsRelaxed, 0, invalidPathChars.Length); + InvalidEntryCharsRelaxed[howMany - 1] = '*'; + InvalidEntryCharsRelaxed[howMany - 2] = '?'; - howMany = invalidPathChars.Length + 4; - InvalidEntryChars = new char[howMany]; - Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length); - InvalidEntryChars[howMany - 1] = ':'; - InvalidEntryChars[howMany - 2] = '\\'; - InvalidEntryChars[howMany - 3] = '*'; - InvalidEntryChars[howMany - 4] = '?'; - } + howMany = invalidPathChars.Length + 4; + InvalidEntryChars = new char[howMany]; + Array.Copy(invalidPathChars, 0, InvalidEntryChars, 0, invalidPathChars.Length); + InvalidEntryChars[howMany - 1] = ':'; + InvalidEntryChars[howMany - 2] = '\\'; + InvalidEntryChars[howMany - 3] = '*'; + InvalidEntryChars[howMany - 4] = '?'; + } - /// - /// Transform a windows directory name according to the Zip file naming conventions. - /// - /// The directory name to transform. - /// The transformed name. - public string TransformDirectory(string name) - { - name = TransformFile(name); - if (name.Length > 0) { - if ( !name.EndsWith("/") ) { - name += "/"; - } - } - else { - throw new ZipException("Cannot have an empty directory name"); - } - return name; - } - - /// - /// Transform a windows file name according to the Zip file naming conventions. - /// - /// The file name to transform. - /// The transformed name. - public string TransformFile(string name) - { - if (name != null) { - string lowerName = name.ToLower(); - if ( (trimPrefix_ != null) && (lowerName.IndexOf(trimPrefix_) == 0) ) { - name = name.Substring(trimPrefix_.Length); - } + /// + /// Transform a windows directory name according to the Zip file naming conventions. + /// + /// The directory name to transform. + /// The transformed name. + public string TransformDirectory(string name) + { + name = TransformFile(name); + if (name.Length > 0) { + if ( !name.EndsWith("/") ) { + name += "/"; + } + } + else { + throw new ZipException("Cannot have an empty directory name"); + } + return name; + } + + /// + /// Transform a windows file name according to the Zip file naming conventions. + /// + /// The file name to transform. + /// The transformed name. + public string TransformFile(string name) + { + if (name != null) { + string lowerName = name.ToLower(); + if ( (trimPrefix_ != null) && (lowerName.IndexOf(trimPrefix_) == 0) ) { + name = name.Substring(trimPrefix_.Length); + } - name = name.Replace(@"\", "/"); - name = WindowsPathUtils.DropPathRoot(name); + name = name.Replace(@"\", "/"); + name = WindowsPathUtils.DropPathRoot(name); - // Drop any leading slashes. - while ((name.Length > 0) && (name[0] == '/')) - { - name = name.Remove(0, 1); - } + // Drop any leading slashes. + while ((name.Length > 0) && (name[0] == '/')) + { + name = name.Remove(0, 1); + } - // Drop any trailing slashes. - while ((name.Length > 0) && (name[name.Length - 1] == '/')) - { - name = name.Remove(name.Length - 1, 1); - } + // Drop any trailing slashes. + while ((name.Length > 0) && (name[name.Length - 1] == '/')) + { + name = name.Remove(name.Length - 1, 1); + } - // Convert consecutive // characters to / - int index = name.IndexOf("//"); - while (index >= 0) - { - name = name.Remove(index, 1); - index = name.IndexOf("//"); - } + // Convert consecutive // characters to / + int index = name.IndexOf("//"); + while (index >= 0) + { + name = name.Remove(index, 1); + index = name.IndexOf("//"); + } - name = MakeValidName(name, '_'); - } - else { - name = string.Empty; - } - return name; - } - - /// - /// Get/set the path prefix to be trimmed from paths if present. - /// - /// The prefix is trimmed before any conversion from - /// a windows path is done. - public string TrimPrefix - { - get { return trimPrefix_; } - set { - trimPrefix_ = value; - if (trimPrefix_ != null) { - trimPrefix_ = trimPrefix_.ToLower(); - } - } - } + name = MakeValidName(name, '_'); + } + else { + name = string.Empty; + } + return name; + } + + /// + /// Get/set the path prefix to be trimmed from paths if present. + /// + /// The prefix is trimmed before any conversion from + /// a windows path is done. + public string TrimPrefix + { + get { return trimPrefix_; } + set { + trimPrefix_ = value; + if (trimPrefix_ != null) { + trimPrefix_ = trimPrefix_.ToLower(); + } + } + } - /// - /// Force a name to be valid by replacing invalid characters with a fixed value - /// - /// The name to force valid - /// The replacement character to use. - /// Returns a valid name - static string MakeValidName(string name, char replacement) - { - int index = name.IndexOfAny(InvalidEntryChars); - if (index >= 0) { - StringBuilder builder = new StringBuilder(name); + /// + /// Force a name to be valid by replacing invalid characters with a fixed value + /// + /// The name to force valid + /// The replacement character to use. + /// Returns a valid name + static string MakeValidName(string name, char replacement) + { + int index = name.IndexOfAny(InvalidEntryChars); + if (index >= 0) { + StringBuilder builder = new StringBuilder(name); - while (index >= 0 ) { - builder[index] = replacement; + while (index >= 0 ) { + builder[index] = replacement; - if (index >= name.Length) { - index = -1; - } - else { - index = name.IndexOfAny(InvalidEntryChars, index + 1); - } - } - name = builder.ToString(); - } + if (index >= name.Length) { + index = -1; + } + else { + index = name.IndexOfAny(InvalidEntryChars, index + 1); + } + } + name = builder.ToString(); + } - if (name.Length > 0xffff) { - throw new PathTooLongException(); - } + if (name.Length > 0xffff) { + throw new PathTooLongException(); + } - return name; - } + return name; + } - /// - /// Test a name to see if it is a valid name for a zip entry. - /// - /// The name to test. - /// If true checking is relaxed about windows file names and absolute paths. - /// Returns true if the name is a valid zip name; false otherwise. - /// Zip path names are actually in Unix format, and should only contain relative paths. - /// This means that any path stored should not contain a drive or - /// device letter, or a leading slash. All slashes should forward slashes '/'. - /// An empty name is valid for a file where the input comes from standard input. - /// A null name is not considered valid. - /// - public static bool IsValidName(string name, bool relaxed) - { - bool result = (name != null); + /// + /// Test a name to see if it is a valid name for a zip entry. + /// + /// The name to test. + /// If true checking is relaxed about windows file names and absolute paths. + /// Returns true if the name is a valid zip name; false otherwise. + /// Zip path names are actually in Unix format, and should only contain relative paths. + /// This means that any path stored should not contain a drive or + /// device letter, or a leading slash. All slashes should forward slashes '/'. + /// An empty name is valid for a file where the input comes from standard input. + /// A null name is not considered valid. + /// + public static bool IsValidName(string name, bool relaxed) + { + bool result = (name != null); - if ( result ) { - if ( relaxed ) { - result = name.IndexOfAny(InvalidEntryCharsRelaxed) < 0; - } - else { - result = - (name.IndexOfAny(InvalidEntryChars) < 0) && - (name.IndexOf('/') != 0); - } - } + if ( result ) { + if ( relaxed ) { + result = name.IndexOfAny(InvalidEntryCharsRelaxed) < 0; + } + else { + result = + (name.IndexOfAny(InvalidEntryChars) < 0) && + (name.IndexOf('/') != 0); + } + } - return result; - } + return result; + } - /// - /// Test a name to see if it is a valid name for a zip entry. - /// - /// The name to test. - /// Returns true if the name is a valid zip name; false otherwise. - /// Zip path names are actually in unix format, - /// and should only contain relative paths if a path is present. - /// This means that the path stored should not contain a drive or - /// device letter, or a leading slash. All slashes should forward slashes '/'. - /// An empty name is valid where the input comes from standard input. - /// A null name is not considered valid. - /// - public static bool IsValidName(string name) - { - bool result = - (name != null) && - (name.IndexOfAny(InvalidEntryChars) < 0) && - (name.IndexOf('/') != 0) - ; - return result; - } + /// + /// Test a name to see if it is a valid name for a zip entry. + /// + /// The name to test. + /// Returns true if the name is a valid zip name; false otherwise. + /// Zip path names are actually in unix format, + /// and should only contain relative paths if a path is present. + /// This means that the path stored should not contain a drive or + /// device letter, or a leading slash. All slashes should forward slashes '/'. + /// An empty name is valid where the input comes from standard input. + /// A null name is not considered valid. + /// + public static bool IsValidName(string name) + { + bool result = + (name != null) && + (name.IndexOfAny(InvalidEntryChars) < 0) && + (name.IndexOf('/') != 0) + ; + return result; + } - #region Instance Fields - string trimPrefix_; - #endregion - - #region Class Fields - static readonly char[] InvalidEntryChars; - static readonly char[] InvalidEntryCharsRelaxed; - #endregion - } + #region Instance Fields + string trimPrefix_; + #endregion + + #region Class Fields + static readonly char[] InvalidEntryChars; + static readonly char[] InvalidEntryCharsRelaxed; + #endregion + } } diff --git a/External/Tools/AppMan/ZipLib/Zip/ZipOutputStream.cs b/External/Tools/AppMan/ZipLib/Zip/ZipOutputStream.cs index eae41712b4..c88122b8b1 100644 --- a/External/Tools/AppMan/ZipLib/Zip/ZipOutputStream.cs +++ b/External/Tools/AppMan/ZipLib/Zip/ZipOutputStream.cs @@ -38,8 +38,8 @@ // exception statement from your version. // HISTORY -// 22-12-2009 Z-1649 Added AES support -// 22-02-2010 Z-1648 Zero byte entries would create invalid zip files +// 22-12-2009 Z-1649 Added AES support +// 22-02-2010 Z-1648 Zero byte entries would create invalid zip files using System; using System.IO; @@ -51,62 +51,62 @@ namespace ICSharpCode.SharpZipLib.Zip { - /// - /// This is a DeflaterOutputStream that writes the files into a zip - /// archive one after another. It has a special method to start a new - /// zip entry. The zip entries contains information about the file name - /// size, compressed size, CRC, etc. - /// - /// It includes support for Stored and Deflated entries. - /// This class is not thread safe. - ///
    - ///
    Author of the original java version : Jochen Hoenicke - ///
    - /// This sample shows how to create a zip file - /// - /// using System; - /// using System.IO; - /// - /// using ICSharpCode.SharpZipLib.Core; - /// using ICSharpCode.SharpZipLib.Zip; - /// - /// class MainClass - /// { - /// public static void Main(string[] args) - /// { - /// string[] filenames = Directory.GetFiles(args[0]); - /// byte[] buffer = new byte[4096]; - /// - /// using ( ZipOutputStream s = new ZipOutputStream(File.Create(args[1])) ) { - /// - /// s.SetLevel(9); // 0 - store only to 9 - means best compression - /// - /// foreach (string file in filenames) { - /// ZipEntry entry = new ZipEntry(file); - /// s.PutNextEntry(entry); - /// - /// using (FileStream fs = File.OpenRead(file)) { - /// StreamUtils.Copy(fs, s, buffer); - /// } - /// } - /// } - /// } - /// } - /// - /// - public class ZipOutputStream : DeflaterOutputStream - { - #region Constructors - /// - /// Creates a new Zip output stream, writing a zip archive. - /// - /// - /// The output stream to which the archive contents are written. - /// - public ZipOutputStream(Stream baseOutputStream) - : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true)) - { - } + /// + /// This is a DeflaterOutputStream that writes the files into a zip + /// archive one after another. It has a special method to start a new + /// zip entry. The zip entries contains information about the file name + /// size, compressed size, CRC, etc. + /// + /// It includes support for Stored and Deflated entries. + /// This class is not thread safe. + ///
    + ///
    Author of the original java version : Jochen Hoenicke + ///
    + /// This sample shows how to create a zip file + /// + /// using System; + /// using System.IO; + /// + /// using ICSharpCode.SharpZipLib.Core; + /// using ICSharpCode.SharpZipLib.Zip; + /// + /// class MainClass + /// { + /// public static void Main(string[] args) + /// { + /// string[] filenames = Directory.GetFiles(args[0]); + /// byte[] buffer = new byte[4096]; + /// + /// using ( ZipOutputStream s = new ZipOutputStream(File.Create(args[1])) ) { + /// + /// s.SetLevel(9); // 0 - store only to 9 - means best compression + /// + /// foreach (string file in filenames) { + /// ZipEntry entry = new ZipEntry(file); + /// s.PutNextEntry(entry); + /// + /// using (FileStream fs = File.OpenRead(file)) { + /// StreamUtils.Copy(fs, s, buffer); + /// } + /// } + /// } + /// } + /// } + /// + /// + public class ZipOutputStream : DeflaterOutputStream + { + #region Constructors + /// + /// Creates a new Zip output stream, writing a zip archive. + /// + /// + /// The output stream to which the archive contents are written. + /// + public ZipOutputStream(Stream baseOutputStream) + : base(baseOutputStream, new Deflater(Deflater.DEFAULT_COMPRESSION, true)) + { + } /// /// Creates a new Zip output stream, writing a zip archive. @@ -118,783 +118,783 @@ public ZipOutputStream( Stream baseOutputStream, int bufferSize ) { } #endregion - - /// - /// Gets a flag value of true if the central header has been added for this archive; false if it has not been added. - /// - /// No further entries can be added once this has been done. - public bool IsFinished - { - get { - return entries == null; - } - } - - /// - /// Set the zip file comment. - /// - /// - /// The comment text for the entire archive. - /// - /// - /// The converted comment is longer than 0xffff bytes. - /// - public void SetComment(string comment) - { - // TODO: Its not yet clear how to handle unicode comments here. - byte[] commentBytes = ZipConstants.ConvertToArray(comment); - if (commentBytes.Length > 0xffff) { - throw new ArgumentOutOfRangeException("comment"); - } - zipComment = commentBytes; - } - - /// - /// Sets the compression level. The new level will be activated - /// immediately. - /// - /// The new compression level (1 to 9). - /// - /// Level specified is not supported. - /// - /// - public void SetLevel(int level) - { - deflater_.SetLevel(level); - defaultCompressionLevel = level; - } - - /// - /// Get the current deflater compression level - /// - /// The current compression level - public int GetLevel() - { - return deflater_.GetLevel(); - } - - /// - /// Get / set a value indicating how Zip64 Extension usage is determined when adding entries. - /// - /// Older archivers may not understand Zip64 extensions. - /// If backwards compatability is an issue be careful when adding entries to an archive. - /// Setting this property to off is workable but less desirable as in those circumstances adding a file - /// larger then 4GB will fail. - public UseZip64 UseZip64 - { - get { return useZip64_; } - set { useZip64_ = value; } - } - - /// - /// Write an unsigned short in little endian byte order. - /// - private void WriteLeShort(int value) - { - unchecked { - baseOutputStream_.WriteByte((byte)(value & 0xff)); - baseOutputStream_.WriteByte((byte)((value >> 8) & 0xff)); - } - } - - /// - /// Write an int in little endian byte order. - /// - private void WriteLeInt(int value) - { - unchecked { - WriteLeShort(value); - WriteLeShort(value >> 16); - } - } - - /// - /// Write an int in little endian byte order. - /// - private void WriteLeLong(long value) - { - unchecked { - WriteLeInt((int)value); - WriteLeInt((int)(value >> 32)); - } - } - - /// - /// Starts a new Zip entry. It automatically closes the previous - /// entry if present. - /// All entry elements bar name are optional, but must be correct if present. - /// If the compression method is stored and the output is not patchable - /// the compression for that entry is automatically changed to deflate level 0 - /// - /// - /// the entry. - /// - /// - /// if entry passed is null. - /// - /// - /// if an I/O error occured. - /// - /// - /// if stream was finished - /// - /// - /// Too many entries in the Zip file
    - /// Entry name is too long
    - /// Finish has already been called
    - ///
    - public void PutNextEntry(ZipEntry entry) - { - if ( entry == null ) { - throw new ArgumentNullException("entry"); - } - - if (entries == null) { - throw new InvalidOperationException("ZipOutputStream was finished"); - } - - if (curEntry != null) { - CloseEntry(); - } - - if (entries.Count == int.MaxValue) { - throw new ZipException("Too many entries for Zip file"); - } - - CompressionMethod method = entry.CompressionMethod; - int compressionLevel = defaultCompressionLevel; - - // Clear flags that the library manages internally - entry.Flags &= (int)GeneralBitFlags.UnicodeText; - patchEntryHeader = false; - - bool headerInfoAvailable; - - // No need to compress - definitely no data. - if (entry.Size == 0) - { - entry.CompressedSize = entry.Size; - entry.Crc = 0; - method = CompressionMethod.Stored; - headerInfoAvailable = true; - } - else - { - headerInfoAvailable = (entry.Size >= 0) && entry.HasCrc; - - // Switch to deflation if storing isnt possible. - if (method == CompressionMethod.Stored) - { - if (!headerInfoAvailable) - { - if (!CanPatchEntries) - { - // Can't patch entries so storing is not possible. - method = CompressionMethod.Deflated; - compressionLevel = 0; - } - } - else // entry.size must be > 0 - { - entry.CompressedSize = entry.Size; - headerInfoAvailable = entry.HasCrc; - } - } - } - - if (headerInfoAvailable == false) { - if (CanPatchEntries == false) { - // Only way to record size and compressed size is to append a data descriptor - // after compressed data. - - // Stored entries of this form have already been converted to deflating. - entry.Flags |= 8; - } else { - patchEntryHeader = true; - } - } - - if (Password != null) { - entry.IsCrypted = true; - if (entry.Crc < 0) { - // Need to append a data descriptor as the crc isnt available for use - // with encryption, the date is used instead. Setting the flag - // indicates this to the decompressor. - entry.Flags |= 8; - } - } - - entry.Offset = offset; - entry.CompressionMethod = (CompressionMethod)method; - - curMethod = method; - sizePatchPos = -1; - - if ( (useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic)) ) { - entry.ForceZip64(); - } - - // Write the local file header - WriteLeInt(ZipConstants.LocalHeaderSignature); - - WriteLeShort(entry.Version); - WriteLeShort(entry.Flags); - WriteLeShort((byte)entry.CompressionMethodForHeader); - WriteLeInt((int)entry.DosTime); - - // TODO: Refactor header writing. Its done in several places. - if (headerInfoAvailable == true) { - WriteLeInt((int)entry.Crc); - if ( entry.LocalHeaderRequiresZip64 ) { - WriteLeInt(-1); - WriteLeInt(-1); - } - else { - WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); - WriteLeInt((int)entry.Size); - } - } else { - if (patchEntryHeader) { - crcPatchPos = baseOutputStream_.Position; - } - WriteLeInt(0); // Crc - - if ( patchEntryHeader ) { - sizePatchPos = baseOutputStream_.Position; - } - - // For local header both sizes appear in Zip64 Extended Information - if ( entry.LocalHeaderRequiresZip64 || patchEntryHeader ) { - WriteLeInt(-1); - WriteLeInt(-1); - } - else { - WriteLeInt(0); // Compressed size - WriteLeInt(0); // Uncompressed size - } - } - - byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); - - if (name.Length > 0xFFFF) { - throw new ZipException("Entry name too long."); - } - - ZipExtraData ed = new ZipExtraData(entry.ExtraData); - - if (entry.LocalHeaderRequiresZip64) { - ed.StartNewEntry(); - if (headerInfoAvailable) { - ed.AddLeLong(entry.Size); - ed.AddLeLong(entry.CompressedSize); - } - else { - ed.AddLeLong(-1); - ed.AddLeLong(-1); - } - ed.AddNewEntry(1); - - if ( !ed.Find(1) ) { - throw new ZipException("Internal error cant find extra data"); - } - - if ( patchEntryHeader ) { - sizePatchPos = ed.CurrentReadIndex; - } - } - else { - ed.Delete(1); - } + + /// + /// Gets a flag value of true if the central header has been added for this archive; false if it has not been added. + /// + /// No further entries can be added once this has been done. + public bool IsFinished + { + get { + return entries == null; + } + } + + /// + /// Set the zip file comment. + /// + /// + /// The comment text for the entire archive. + /// + /// + /// The converted comment is longer than 0xffff bytes. + /// + public void SetComment(string comment) + { + // TODO: Its not yet clear how to handle unicode comments here. + byte[] commentBytes = ZipConstants.ConvertToArray(comment); + if (commentBytes.Length > 0xffff) { + throw new ArgumentOutOfRangeException("comment"); + } + zipComment = commentBytes; + } + + /// + /// Sets the compression level. The new level will be activated + /// immediately. + /// + /// The new compression level (1 to 9). + /// + /// Level specified is not supported. + /// + /// + public void SetLevel(int level) + { + deflater_.SetLevel(level); + defaultCompressionLevel = level; + } + + /// + /// Get the current deflater compression level + /// + /// The current compression level + public int GetLevel() + { + return deflater_.GetLevel(); + } + + /// + /// Get / set a value indicating how Zip64 Extension usage is determined when adding entries. + /// + /// Older archivers may not understand Zip64 extensions. + /// If backwards compatability is an issue be careful when adding entries to an archive. + /// Setting this property to off is workable but less desirable as in those circumstances adding a file + /// larger then 4GB will fail. + public UseZip64 UseZip64 + { + get { return useZip64_; } + set { useZip64_ = value; } + } + + /// + /// Write an unsigned short in little endian byte order. + /// + private void WriteLeShort(int value) + { + unchecked { + baseOutputStream_.WriteByte((byte)(value & 0xff)); + baseOutputStream_.WriteByte((byte)((value >> 8) & 0xff)); + } + } + + /// + /// Write an int in little endian byte order. + /// + private void WriteLeInt(int value) + { + unchecked { + WriteLeShort(value); + WriteLeShort(value >> 16); + } + } + + /// + /// Write an int in little endian byte order. + /// + private void WriteLeLong(long value) + { + unchecked { + WriteLeInt((int)value); + WriteLeInt((int)(value >> 32)); + } + } + + /// + /// Starts a new Zip entry. It automatically closes the previous + /// entry if present. + /// All entry elements bar name are optional, but must be correct if present. + /// If the compression method is stored and the output is not patchable + /// the compression for that entry is automatically changed to deflate level 0 + /// + /// + /// the entry. + /// + /// + /// if entry passed is null. + /// + /// + /// if an I/O error occured. + /// + /// + /// if stream was finished + /// + /// + /// Too many entries in the Zip file
    + /// Entry name is too long
    + /// Finish has already been called
    + ///
    + public void PutNextEntry(ZipEntry entry) + { + if ( entry == null ) { + throw new ArgumentNullException("entry"); + } + + if (entries == null) { + throw new InvalidOperationException("ZipOutputStream was finished"); + } + + if (curEntry != null) { + CloseEntry(); + } + + if (entries.Count == int.MaxValue) { + throw new ZipException("Too many entries for Zip file"); + } + + CompressionMethod method = entry.CompressionMethod; + int compressionLevel = defaultCompressionLevel; + + // Clear flags that the library manages internally + entry.Flags &= (int)GeneralBitFlags.UnicodeText; + patchEntryHeader = false; + + bool headerInfoAvailable; + + // No need to compress - definitely no data. + if (entry.Size == 0) + { + entry.CompressedSize = entry.Size; + entry.Crc = 0; + method = CompressionMethod.Stored; + headerInfoAvailable = true; + } + else + { + headerInfoAvailable = (entry.Size >= 0) && entry.HasCrc; + + // Switch to deflation if storing isnt possible. + if (method == CompressionMethod.Stored) + { + if (!headerInfoAvailable) + { + if (!CanPatchEntries) + { + // Can't patch entries so storing is not possible. + method = CompressionMethod.Deflated; + compressionLevel = 0; + } + } + else // entry.size must be > 0 + { + entry.CompressedSize = entry.Size; + headerInfoAvailable = entry.HasCrc; + } + } + } + + if (headerInfoAvailable == false) { + if (CanPatchEntries == false) { + // Only way to record size and compressed size is to append a data descriptor + // after compressed data. + + // Stored entries of this form have already been converted to deflating. + entry.Flags |= 8; + } else { + patchEntryHeader = true; + } + } + + if (Password != null) { + entry.IsCrypted = true; + if (entry.Crc < 0) { + // Need to append a data descriptor as the crc isnt available for use + // with encryption, the date is used instead. Setting the flag + // indicates this to the decompressor. + entry.Flags |= 8; + } + } + + entry.Offset = offset; + entry.CompressionMethod = (CompressionMethod)method; + + curMethod = method; + sizePatchPos = -1; + + if ( (useZip64_ == UseZip64.On) || ((entry.Size < 0) && (useZip64_ == UseZip64.Dynamic)) ) { + entry.ForceZip64(); + } + + // Write the local file header + WriteLeInt(ZipConstants.LocalHeaderSignature); + + WriteLeShort(entry.Version); + WriteLeShort(entry.Flags); + WriteLeShort((byte)entry.CompressionMethodForHeader); + WriteLeInt((int)entry.DosTime); + + // TODO: Refactor header writing. Its done in several places. + if (headerInfoAvailable == true) { + WriteLeInt((int)entry.Crc); + if ( entry.LocalHeaderRequiresZip64 ) { + WriteLeInt(-1); + WriteLeInt(-1); + } + else { + WriteLeInt(entry.IsCrypted ? (int)entry.CompressedSize + ZipConstants.CryptoHeaderSize : (int)entry.CompressedSize); + WriteLeInt((int)entry.Size); + } + } else { + if (patchEntryHeader) { + crcPatchPos = baseOutputStream_.Position; + } + WriteLeInt(0); // Crc + + if ( patchEntryHeader ) { + sizePatchPos = baseOutputStream_.Position; + } + + // For local header both sizes appear in Zip64 Extended Information + if ( entry.LocalHeaderRequiresZip64 || patchEntryHeader ) { + WriteLeInt(-1); + WriteLeInt(-1); + } + else { + WriteLeInt(0); // Compressed size + WriteLeInt(0); // Uncompressed size + } + } + + byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); + + if (name.Length > 0xFFFF) { + throw new ZipException("Entry name too long."); + } + + ZipExtraData ed = new ZipExtraData(entry.ExtraData); + + if (entry.LocalHeaderRequiresZip64) { + ed.StartNewEntry(); + if (headerInfoAvailable) { + ed.AddLeLong(entry.Size); + ed.AddLeLong(entry.CompressedSize); + } + else { + ed.AddLeLong(-1); + ed.AddLeLong(-1); + } + ed.AddNewEntry(1); + + if ( !ed.Find(1) ) { + throw new ZipException("Internal error cant find extra data"); + } + + if ( patchEntryHeader ) { + sizePatchPos = ed.CurrentReadIndex; + } + } + else { + ed.Delete(1); + } #if !NET_1_1 && !NETCF_2_0 - if (entry.AESKeySize > 0) { - AddExtraDataAES(entry, ed); - } + if (entry.AESKeySize > 0) { + AddExtraDataAES(entry, ed); + } #endif - byte[] extra = ed.GetEntryData(); - - WriteLeShort(name.Length); - WriteLeShort(extra.Length); - - if ( name.Length > 0 ) { - baseOutputStream_.Write(name, 0, name.Length); - } - - if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { - sizePatchPos += baseOutputStream_.Position; - } - - if ( extra.Length > 0 ) { - baseOutputStream_.Write(extra, 0, extra.Length); - } - - offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length; - // Fix offsetOfCentraldir for AES - if (entry.AESKeySize > 0) - offset += entry.AESOverheadSize; - - // Activate the entry. - curEntry = entry; - crc.Reset(); - if (method == CompressionMethod.Deflated) { - deflater_.Reset(); - deflater_.SetLevel(compressionLevel); - } - size = 0; - - if (entry.IsCrypted) { + byte[] extra = ed.GetEntryData(); + + WriteLeShort(name.Length); + WriteLeShort(extra.Length); + + if ( name.Length > 0 ) { + baseOutputStream_.Write(name, 0, name.Length); + } + + if ( entry.LocalHeaderRequiresZip64 && patchEntryHeader ) { + sizePatchPos += baseOutputStream_.Position; + } + + if ( extra.Length > 0 ) { + baseOutputStream_.Write(extra, 0, extra.Length); + } + + offset += ZipConstants.LocalHeaderBaseSize + name.Length + extra.Length; + // Fix offsetOfCentraldir for AES + if (entry.AESKeySize > 0) + offset += entry.AESOverheadSize; + + // Activate the entry. + curEntry = entry; + crc.Reset(); + if (method == CompressionMethod.Deflated) { + deflater_.Reset(); + deflater_.SetLevel(compressionLevel); + } + size = 0; + + if (entry.IsCrypted) { #if !NET_1_1 && !NETCF_2_0 - if (entry.AESKeySize > 0) { - WriteAESHeader(entry); - } else + if (entry.AESKeySize > 0) { + WriteAESHeader(entry); + } else #endif - { - if (entry.Crc < 0) { // so testing Zip will says its ok - WriteEncryptionHeader(entry.DosTime << 16); - } else { - WriteEncryptionHeader(entry.Crc); - } - } - } - } - - /// - /// Closes the current entry, updating header and footer information as required - /// - /// - /// An I/O error occurs. - /// - /// - /// No entry is active. - /// - public void CloseEntry() - { - if (curEntry == null) { - throw new InvalidOperationException("No open entry"); - } - - long csize = size; - - // First finish the deflater, if appropriate - if (curMethod == CompressionMethod.Deflated) { - if (size >= 0) { - base.Finish(); - csize = deflater_.TotalOut; - } - else { - deflater_.Reset(); - } - } - - // Write the AES Authentication Code (a hash of the compressed and encrypted data) - if (curEntry.AESKeySize > 0) { - baseOutputStream_.Write(AESAuthCode, 0, 10); - } - - if (curEntry.Size < 0) { - curEntry.Size = size; - } else if (curEntry.Size != size) { - throw new ZipException("size was " + size + ", but I expected " + curEntry.Size); - } - - if (curEntry.CompressedSize < 0) { - curEntry.CompressedSize = csize; - } else if (curEntry.CompressedSize != csize) { - throw new ZipException("compressed size was " + csize + ", but I expected " + curEntry.CompressedSize); - } - - if (curEntry.Crc < 0) { - curEntry.Crc = crc.Value; - } else if (curEntry.Crc != crc.Value) { - throw new ZipException("crc was " + crc.Value + ", but I expected " + curEntry.Crc); - } - - offset += csize; - - if (curEntry.IsCrypted) { - if (curEntry.AESKeySize > 0) { - curEntry.CompressedSize += curEntry.AESOverheadSize; - - } else { - curEntry.CompressedSize += ZipConstants.CryptoHeaderSize; - } - } - - // Patch the header if possible - if (patchEntryHeader) { - patchEntryHeader = false; - - long curPos = baseOutputStream_.Position; - baseOutputStream_.Seek(crcPatchPos, SeekOrigin.Begin); - WriteLeInt((int)curEntry.Crc); - - if ( curEntry.LocalHeaderRequiresZip64 ) { - - if ( sizePatchPos == -1 ) { - throw new ZipException("Entry requires zip64 but this has been turned off"); - } - - baseOutputStream_.Seek(sizePatchPos, SeekOrigin.Begin); - WriteLeLong(curEntry.Size); - WriteLeLong(curEntry.CompressedSize); - } - else { - WriteLeInt((int)curEntry.CompressedSize); - WriteLeInt((int)curEntry.Size); - } - baseOutputStream_.Seek(curPos, SeekOrigin.Begin); - } - - // Add data descriptor if flagged as required - if ((curEntry.Flags & 8) != 0) { - WriteLeInt(ZipConstants.DataDescriptorSignature); - WriteLeInt(unchecked((int)curEntry.Crc)); - - if ( curEntry.LocalHeaderRequiresZip64 ) { - WriteLeLong(curEntry.CompressedSize); - WriteLeLong(curEntry.Size); - offset += ZipConstants.Zip64DataDescriptorSize; - } - else { - WriteLeInt((int)curEntry.CompressedSize); - WriteLeInt((int)curEntry.Size); - offset += ZipConstants.DataDescriptorSize; - } - } - - entries.Add(curEntry); - curEntry = null; - } - - void WriteEncryptionHeader(long crcValue) - { - offset += ZipConstants.CryptoHeaderSize; - - InitializePassword(Password); - - byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; - Random rnd = new Random(); - rnd.NextBytes(cryptBuffer); - cryptBuffer[11] = (byte)(crcValue >> 24); - - EncryptBlock(cryptBuffer, 0, cryptBuffer.Length); - baseOutputStream_.Write(cryptBuffer, 0, cryptBuffer.Length); - } + { + if (entry.Crc < 0) { // so testing Zip will says its ok + WriteEncryptionHeader(entry.DosTime << 16); + } else { + WriteEncryptionHeader(entry.Crc); + } + } + } + } + + /// + /// Closes the current entry, updating header and footer information as required + /// + /// + /// An I/O error occurs. + /// + /// + /// No entry is active. + /// + public void CloseEntry() + { + if (curEntry == null) { + throw new InvalidOperationException("No open entry"); + } + + long csize = size; + + // First finish the deflater, if appropriate + if (curMethod == CompressionMethod.Deflated) { + if (size >= 0) { + base.Finish(); + csize = deflater_.TotalOut; + } + else { + deflater_.Reset(); + } + } + + // Write the AES Authentication Code (a hash of the compressed and encrypted data) + if (curEntry.AESKeySize > 0) { + baseOutputStream_.Write(AESAuthCode, 0, 10); + } + + if (curEntry.Size < 0) { + curEntry.Size = size; + } else if (curEntry.Size != size) { + throw new ZipException("size was " + size + ", but I expected " + curEntry.Size); + } + + if (curEntry.CompressedSize < 0) { + curEntry.CompressedSize = csize; + } else if (curEntry.CompressedSize != csize) { + throw new ZipException("compressed size was " + csize + ", but I expected " + curEntry.CompressedSize); + } + + if (curEntry.Crc < 0) { + curEntry.Crc = crc.Value; + } else if (curEntry.Crc != crc.Value) { + throw new ZipException("crc was " + crc.Value + ", but I expected " + curEntry.Crc); + } + + offset += csize; + + if (curEntry.IsCrypted) { + if (curEntry.AESKeySize > 0) { + curEntry.CompressedSize += curEntry.AESOverheadSize; + + } else { + curEntry.CompressedSize += ZipConstants.CryptoHeaderSize; + } + } + + // Patch the header if possible + if (patchEntryHeader) { + patchEntryHeader = false; + + long curPos = baseOutputStream_.Position; + baseOutputStream_.Seek(crcPatchPos, SeekOrigin.Begin); + WriteLeInt((int)curEntry.Crc); + + if ( curEntry.LocalHeaderRequiresZip64 ) { + + if ( sizePatchPos == -1 ) { + throw new ZipException("Entry requires zip64 but this has been turned off"); + } + + baseOutputStream_.Seek(sizePatchPos, SeekOrigin.Begin); + WriteLeLong(curEntry.Size); + WriteLeLong(curEntry.CompressedSize); + } + else { + WriteLeInt((int)curEntry.CompressedSize); + WriteLeInt((int)curEntry.Size); + } + baseOutputStream_.Seek(curPos, SeekOrigin.Begin); + } + + // Add data descriptor if flagged as required + if ((curEntry.Flags & 8) != 0) { + WriteLeInt(ZipConstants.DataDescriptorSignature); + WriteLeInt(unchecked((int)curEntry.Crc)); + + if ( curEntry.LocalHeaderRequiresZip64 ) { + WriteLeLong(curEntry.CompressedSize); + WriteLeLong(curEntry.Size); + offset += ZipConstants.Zip64DataDescriptorSize; + } + else { + WriteLeInt((int)curEntry.CompressedSize); + WriteLeInt((int)curEntry.Size); + offset += ZipConstants.DataDescriptorSize; + } + } + + entries.Add(curEntry); + curEntry = null; + } + + void WriteEncryptionHeader(long crcValue) + { + offset += ZipConstants.CryptoHeaderSize; + + InitializePassword(Password); + + byte[] cryptBuffer = new byte[ZipConstants.CryptoHeaderSize]; + Random rnd = new Random(); + rnd.NextBytes(cryptBuffer); + cryptBuffer[11] = (byte)(crcValue >> 24); + + EncryptBlock(cryptBuffer, 0, cryptBuffer.Length); + baseOutputStream_.Write(cryptBuffer, 0, cryptBuffer.Length); + } #if !NET_1_1 && !NETCF_2_0 - private static void AddExtraDataAES(ZipEntry entry, ZipExtraData extraData) { - - // Vendor Version: AE-1 IS 1. AE-2 is 2. With AE-2 no CRC is required and 0 is stored. - const int VENDOR_VERSION = 2; - // Vendor ID is the two ASCII characters "AE". - const int VENDOR_ID = 0x4541; //not 6965; - extraData.StartNewEntry(); - // Pack AES extra data field see http://www.winzip.com/aes_info.htm - //extraData.AddLeShort(7); // Data size (currently 7) - extraData.AddLeShort(VENDOR_VERSION); // 2 = AE-2 - extraData.AddLeShort(VENDOR_ID); // "AE" - extraData.AddData(entry.AESEncryptionStrength); // 1 = 128, 2 = 192, 3 = 256 - extraData.AddLeShort((int)entry.CompressionMethod); // The actual compression method used to compress the file - extraData.AddNewEntry(0x9901); - } - - // Replaces WriteEncryptionHeader for AES - // - private void WriteAESHeader(ZipEntry entry) { - byte[] salt; - byte[] pwdVerifier; - InitializeAESPassword(entry, Password, out salt, out pwdVerifier); - // File format for AES: - // Size (bytes) Content - // ------------ ------- - // Variable Salt value - // 2 Password verification value - // Variable Encrypted file data - // 10 Authentication code - // - // Value in the "compressed size" fields of the local file header and the central directory entry - // is the total size of all the items listed above. In other words, it is the total size of the - // salt value, password verification value, encrypted data, and authentication code. - baseOutputStream_.Write(salt, 0, salt.Length); - baseOutputStream_.Write(pwdVerifier, 0, pwdVerifier.Length); - } + private static void AddExtraDataAES(ZipEntry entry, ZipExtraData extraData) { + + // Vendor Version: AE-1 IS 1. AE-2 is 2. With AE-2 no CRC is required and 0 is stored. + const int VENDOR_VERSION = 2; + // Vendor ID is the two ASCII characters "AE". + const int VENDOR_ID = 0x4541; //not 6965; + extraData.StartNewEntry(); + // Pack AES extra data field see http://www.winzip.com/aes_info.htm + //extraData.AddLeShort(7); // Data size (currently 7) + extraData.AddLeShort(VENDOR_VERSION); // 2 = AE-2 + extraData.AddLeShort(VENDOR_ID); // "AE" + extraData.AddData(entry.AESEncryptionStrength); // 1 = 128, 2 = 192, 3 = 256 + extraData.AddLeShort((int)entry.CompressionMethod); // The actual compression method used to compress the file + extraData.AddNewEntry(0x9901); + } + + // Replaces WriteEncryptionHeader for AES + // + private void WriteAESHeader(ZipEntry entry) { + byte[] salt; + byte[] pwdVerifier; + InitializeAESPassword(entry, Password, out salt, out pwdVerifier); + // File format for AES: + // Size (bytes) Content + // ------------ ------- + // Variable Salt value + // 2 Password verification value + // Variable Encrypted file data + // 10 Authentication code + // + // Value in the "compressed size" fields of the local file header and the central directory entry + // is the total size of all the items listed above. In other words, it is the total size of the + // salt value, password verification value, encrypted data, and authentication code. + baseOutputStream_.Write(salt, 0, salt.Length); + baseOutputStream_.Write(pwdVerifier, 0, pwdVerifier.Length); + } #endif - /// - /// Writes the given buffer to the current entry. - /// - /// The buffer containing data to write. - /// The offset of the first byte to write. - /// The number of bytes to write. - /// Archive size is invalid - /// No entry is active. - public override void Write(byte[] buffer, int offset, int count) - { - if (curEntry == null) { - throw new InvalidOperationException("No open entry."); - } - - if ( buffer == null ) { - throw new ArgumentNullException("buffer"); - } - - if ( offset < 0 ) { + /// + /// Writes the given buffer to the current entry. + /// + /// The buffer containing data to write. + /// The offset of the first byte to write. + /// The number of bytes to write. + /// Archive size is invalid + /// No entry is active. + public override void Write(byte[] buffer, int offset, int count) + { + if (curEntry == null) { + throw new InvalidOperationException("No open entry."); + } + + if ( buffer == null ) { + throw new ArgumentNullException("buffer"); + } + + if ( offset < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("offset"); + throw new ArgumentOutOfRangeException("offset"); #else - throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); + throw new ArgumentOutOfRangeException("offset", "Cannot be negative"); #endif - } + } - if ( count < 0 ) { + if ( count < 0 ) { #if NETCF_1_0 - throw new ArgumentOutOfRangeException("count"); + throw new ArgumentOutOfRangeException("count"); #else - throw new ArgumentOutOfRangeException("count", "Cannot be negative"); + throw new ArgumentOutOfRangeException("count", "Cannot be negative"); #endif - } - - if ( (buffer.Length - offset) < count ) { - throw new ArgumentException("Invalid offset/count combination"); - } - - crc.Update(buffer, offset, count); - size += count; - - switch (curMethod) { - case CompressionMethod.Deflated: - base.Write(buffer, offset, count); - break; - - case CompressionMethod.Stored: - if (Password != null) { - CopyAndEncrypt(buffer, offset, count); - } else { - baseOutputStream_.Write(buffer, offset, count); - } - break; - } - } - - void CopyAndEncrypt(byte[] buffer, int offset, int count) - { - const int CopyBufferSize = 4096; - byte[] localBuffer = new byte[CopyBufferSize]; - while ( count > 0 ) { - int bufferCount = (count < CopyBufferSize) ? count : CopyBufferSize; - - Array.Copy(buffer, offset, localBuffer, 0, bufferCount); - EncryptBlock(localBuffer, 0, bufferCount); - baseOutputStream_.Write(localBuffer, 0, bufferCount); - count -= bufferCount; - offset += bufferCount; - } - } - - /// - /// Finishes the stream. This will write the central directory at the - /// end of the zip file and flush the stream. - /// - /// - /// This is automatically called when the stream is closed. - /// - /// - /// An I/O error occurs. - /// - /// - /// Comment exceeds the maximum length
    - /// Entry name exceeds the maximum length - ///
    - public override void Finish() - { - if (entries == null) { - return; - } - - if (curEntry != null) { - CloseEntry(); - } - - long numEntries = entries.Count; - long sizeEntries = 0; - - foreach (ZipEntry entry in entries) { - WriteLeInt(ZipConstants.CentralHeaderSignature); - WriteLeShort(ZipConstants.VersionMadeBy); - WriteLeShort(entry.Version); - WriteLeShort(entry.Flags); - WriteLeShort((short)entry.CompressionMethodForHeader); - WriteLeInt((int)entry.DosTime); - WriteLeInt((int)entry.Crc); - - if ( entry.IsZip64Forced() || - (entry.CompressedSize >= uint.MaxValue) ) - { - WriteLeInt(-1); - } - else { - WriteLeInt((int)entry.CompressedSize); - } - - if ( entry.IsZip64Forced() || - (entry.Size >= uint.MaxValue) ) - { - WriteLeInt(-1); - } - else { - WriteLeInt((int)entry.Size); - } - - byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); - - if (name.Length > 0xffff) { - throw new ZipException("Name too long."); - } - - ZipExtraData ed = new ZipExtraData(entry.ExtraData); - - if ( entry.CentralHeaderRequiresZip64 ) { - ed.StartNewEntry(); - if ( entry.IsZip64Forced() || - (entry.Size >= 0xffffffff) ) - { - ed.AddLeLong(entry.Size); - } - - if ( entry.IsZip64Forced() || - (entry.CompressedSize >= 0xffffffff) ) - { - ed.AddLeLong(entry.CompressedSize); - } - - if ( entry.Offset >= 0xffffffff ) - { - ed.AddLeLong(entry.Offset); - } - - ed.AddNewEntry(1); - } - else { - ed.Delete(1); - } + } + + if ( (buffer.Length - offset) < count ) { + throw new ArgumentException("Invalid offset/count combination"); + } + + crc.Update(buffer, offset, count); + size += count; + + switch (curMethod) { + case CompressionMethod.Deflated: + base.Write(buffer, offset, count); + break; + + case CompressionMethod.Stored: + if (Password != null) { + CopyAndEncrypt(buffer, offset, count); + } else { + baseOutputStream_.Write(buffer, offset, count); + } + break; + } + } + + void CopyAndEncrypt(byte[] buffer, int offset, int count) + { + const int CopyBufferSize = 4096; + byte[] localBuffer = new byte[CopyBufferSize]; + while ( count > 0 ) { + int bufferCount = (count < CopyBufferSize) ? count : CopyBufferSize; + + Array.Copy(buffer, offset, localBuffer, 0, bufferCount); + EncryptBlock(localBuffer, 0, bufferCount); + baseOutputStream_.Write(localBuffer, 0, bufferCount); + count -= bufferCount; + offset += bufferCount; + } + } + + /// + /// Finishes the stream. This will write the central directory at the + /// end of the zip file and flush the stream. + /// + /// + /// This is automatically called when the stream is closed. + /// + /// + /// An I/O error occurs. + /// + /// + /// Comment exceeds the maximum length
    + /// Entry name exceeds the maximum length + ///
    + public override void Finish() + { + if (entries == null) { + return; + } + + if (curEntry != null) { + CloseEntry(); + } + + long numEntries = entries.Count; + long sizeEntries = 0; + + foreach (ZipEntry entry in entries) { + WriteLeInt(ZipConstants.CentralHeaderSignature); + WriteLeShort(ZipConstants.VersionMadeBy); + WriteLeShort(entry.Version); + WriteLeShort(entry.Flags); + WriteLeShort((short)entry.CompressionMethodForHeader); + WriteLeInt((int)entry.DosTime); + WriteLeInt((int)entry.Crc); + + if ( entry.IsZip64Forced() || + (entry.CompressedSize >= uint.MaxValue) ) + { + WriteLeInt(-1); + } + else { + WriteLeInt((int)entry.CompressedSize); + } + + if ( entry.IsZip64Forced() || + (entry.Size >= uint.MaxValue) ) + { + WriteLeInt(-1); + } + else { + WriteLeInt((int)entry.Size); + } + + byte[] name = ZipConstants.ConvertToArray(entry.Flags, entry.Name); + + if (name.Length > 0xffff) { + throw new ZipException("Name too long."); + } + + ZipExtraData ed = new ZipExtraData(entry.ExtraData); + + if ( entry.CentralHeaderRequiresZip64 ) { + ed.StartNewEntry(); + if ( entry.IsZip64Forced() || + (entry.Size >= 0xffffffff) ) + { + ed.AddLeLong(entry.Size); + } + + if ( entry.IsZip64Forced() || + (entry.CompressedSize >= 0xffffffff) ) + { + ed.AddLeLong(entry.CompressedSize); + } + + if ( entry.Offset >= 0xffffffff ) + { + ed.AddLeLong(entry.Offset); + } + + ed.AddNewEntry(1); + } + else { + ed.Delete(1); + } #if !NET_1_1 && !NETCF_2_0 - if (entry.AESKeySize > 0) { - AddExtraDataAES(entry, ed); - } + if (entry.AESKeySize > 0) { + AddExtraDataAES(entry, ed); + } #endif - byte[] extra = ed.GetEntryData(); - - byte[] entryComment = - (entry.Comment != null) ? - ZipConstants.ConvertToArray(entry.Flags, entry.Comment) : - new byte[0]; - - if (entryComment.Length > 0xffff) { - throw new ZipException("Comment too long."); - } - - WriteLeShort(name.Length); - WriteLeShort(extra.Length); - WriteLeShort(entryComment.Length); - WriteLeShort(0); // disk number - WriteLeShort(0); // internal file attributes - // external file attributes - - if (entry.ExternalFileAttributes != -1) { - WriteLeInt(entry.ExternalFileAttributes); - } else { - if (entry.IsDirectory) { // mark entry as directory (from nikolam.AT.perfectinfo.com) - WriteLeInt(16); - } else { - WriteLeInt(0); - } - } - - if ( entry.Offset >= uint.MaxValue ) { - WriteLeInt(-1); - } - else { - WriteLeInt((int)entry.Offset); - } - - if ( name.Length > 0 ) { - baseOutputStream_.Write(name, 0, name.Length); - } - - if ( extra.Length > 0 ) { - baseOutputStream_.Write(extra, 0, extra.Length); - } - - if ( entryComment.Length > 0 ) { - baseOutputStream_.Write(entryComment, 0, entryComment.Length); - } - - sizeEntries += ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + entryComment.Length; - } - - using ( ZipHelperStream zhs = new ZipHelperStream(baseOutputStream_) ) { - zhs.WriteEndOfCentralDirectory(numEntries, sizeEntries, offset, zipComment); - } - - entries = null; - } - - #region Instance Fields - /// - /// The entries for the archive. - /// - ArrayList entries = new ArrayList(); - - /// - /// Used to track the crc of data added to entries. - /// - Crc32 crc = new Crc32(); - - /// - /// The current entry being added. - /// - ZipEntry curEntry; - - int defaultCompressionLevel = Deflater.DEFAULT_COMPRESSION; - - CompressionMethod curMethod = CompressionMethod.Deflated; - - /// - /// Used to track the size of data for an entry during writing. - /// - long size; - - /// - /// Offset to be recorded for each entry in the central header. - /// - long offset; - - /// - /// Comment for the entire archive recorded in central header. - /// - byte[] zipComment = new byte[0]; - - /// - /// Flag indicating that header patching is required for the current entry. - /// - bool patchEntryHeader; - - /// - /// Position to patch crc - /// - long crcPatchPos = -1; - - /// - /// Position to patch size. - /// - long sizePatchPos = -1; - - // Default is dynamic which is not backwards compatible and can cause problems - // with XP's built in compression which cant read Zip64 archives. - // However it does avoid the situation were a large file is added and cannot be completed correctly. - // NOTE: Setting the size for entries before they are added is the best solution! - UseZip64 useZip64_ = UseZip64.Dynamic; - #endregion - } + byte[] extra = ed.GetEntryData(); + + byte[] entryComment = + (entry.Comment != null) ? + ZipConstants.ConvertToArray(entry.Flags, entry.Comment) : + new byte[0]; + + if (entryComment.Length > 0xffff) { + throw new ZipException("Comment too long."); + } + + WriteLeShort(name.Length); + WriteLeShort(extra.Length); + WriteLeShort(entryComment.Length); + WriteLeShort(0); // disk number + WriteLeShort(0); // internal file attributes + // external file attributes + + if (entry.ExternalFileAttributes != -1) { + WriteLeInt(entry.ExternalFileAttributes); + } else { + if (entry.IsDirectory) { // mark entry as directory (from nikolam.AT.perfectinfo.com) + WriteLeInt(16); + } else { + WriteLeInt(0); + } + } + + if ( entry.Offset >= uint.MaxValue ) { + WriteLeInt(-1); + } + else { + WriteLeInt((int)entry.Offset); + } + + if ( name.Length > 0 ) { + baseOutputStream_.Write(name, 0, name.Length); + } + + if ( extra.Length > 0 ) { + baseOutputStream_.Write(extra, 0, extra.Length); + } + + if ( entryComment.Length > 0 ) { + baseOutputStream_.Write(entryComment, 0, entryComment.Length); + } + + sizeEntries += ZipConstants.CentralHeaderBaseSize + name.Length + extra.Length + entryComment.Length; + } + + using ( ZipHelperStream zhs = new ZipHelperStream(baseOutputStream_) ) { + zhs.WriteEndOfCentralDirectory(numEntries, sizeEntries, offset, zipComment); + } + + entries = null; + } + + #region Instance Fields + /// + /// The entries for the archive. + /// + ArrayList entries = new ArrayList(); + + /// + /// Used to track the crc of data added to entries. + /// + Crc32 crc = new Crc32(); + + /// + /// The current entry being added. + /// + ZipEntry curEntry; + + int defaultCompressionLevel = Deflater.DEFAULT_COMPRESSION; + + CompressionMethod curMethod = CompressionMethod.Deflated; + + /// + /// Used to track the size of data for an entry during writing. + /// + long size; + + /// + /// Offset to be recorded for each entry in the central header. + /// + long offset; + + /// + /// Comment for the entire archive recorded in central header. + /// + byte[] zipComment = new byte[0]; + + /// + /// Flag indicating that header patching is required for the current entry. + /// + bool patchEntryHeader; + + /// + /// Position to patch crc + /// + long crcPatchPos = -1; + + /// + /// Position to patch size. + /// + long sizePatchPos = -1; + + // Default is dynamic which is not backwards compatible and can cause problems + // with XP's built in compression which cant read Zip64 archives. + // However it does avoid the situation were a large file is added and cannot be completed correctly. + // NOTE: Setting the size for entries before they are added is the best solution! + UseZip64 useZip64_ = UseZip64.Dynamic; + #endregion + } } diff --git a/External/Tools/Bridge/DMG/app.plist b/External/Tools/Bridge/DMG/app.plist deleted file mode 100644 index d7bfa96d75..0000000000 --- a/External/Tools/Bridge/DMG/app.plist +++ /dev/null @@ -1,20 +0,0 @@ - - - - - CFBundleIconFile - FDIcon.icns - CFBundlePackageType - APPL - CFBundleGetInfoString - Created by Qt/QMake - CFBundleSignature - ???? - CFBundleExecutable - FlashDevelopBridge - CFBundleIdentifier - org.flashdevelop.FlashDevelopBridge - LSUIElement - 1 - - diff --git a/External/Tools/Bridge/DMG/package.sh b/External/Tools/Bridge/DMG/package.sh deleted file mode 100644 index d9166cb301..0000000000 --- a/External/Tools/Bridge/DMG/package.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/bin/bash -DIR="FlashDevelop Bridge" -APP="FlashDevelopBridge.app" -DMG="FlashDevelop Bridge" - -echo Cleanup... -if [ ! -d "$DIR" ]; then - mkdir "$DIR" -elif [ -d "$DIR/$APP" ]; then - rm -rf "$DIR/$APP" -fi - -if [ -e "$DMG.dmg" ]; then - rm -rf "$DMG.dmg" -fi - -cp -r "../../FlashDevelopBridge-build-desktop/$APP" "$DIR/$APP" - -echo Include Qt dependencies... -macdeployqt "$DIR/$APP" -no-plugins - -echo Package DMG -hdiutil create -fs HFS+ -volname "$DMG" -srcfolder "$DIR" "$DMG.dmg" diff --git a/External/Tools/Bridge/Deploy/app.plist b/External/Tools/Bridge/Deploy/app.plist new file mode 100644 index 0000000000..7c03ac4390 --- /dev/null +++ b/External/Tools/Bridge/Deploy/app.plist @@ -0,0 +1,20 @@ + + + + + CFBundleIconFile + AppIcon.icns + CFBundlePackageType + APPL + CFBundleGetInfoString + FlashDevelop helper utility + CFBundleSignature + ???? + CFBundleExecutable + FlashDevelop Bridge + CFBundleIdentifier + org.flashdevelop.FlashDevelopBridge + LSUIElement + 1 + + diff --git a/External/Tools/Bridge/Deploy/package.sh b/External/Tools/Bridge/Deploy/package.sh new file mode 100644 index 0000000000..5ff41db555 --- /dev/null +++ b/External/Tools/Bridge/Deploy/package.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +DIR="tmp" +APP="FlashDevelop Bridge.app" +DMG="FlashDevelop-Bridge.dmg" + +PATH=/Users/Mika/QtSDK/5.3.2/5.3/clang_64/bin:$PATH +export PATH + +echo Remove old files... +if [ ! -d "$DIR" ]; then + mkdir "$DIR" +elif [ -d "$DIR/$APP" ]; then + rm -rf "$DIR/$APP" +fi +if [ -e "$DMG" ]; then + rm -rf "$DMG" +fi + +echo Copy clean build... +cp -r "../Bin/Release/$APP" "$DIR/$APP" + +echo Include Qt dependencies... +macdeployqt "$DIR/$APP" + +echo Add FDEXE.sh... +cp "FDEXE.sh" "$DIR/$APP/Contents/MacOS/FDEXE.sh" +chmod +x "$DIR/$APP/Contents/MacOS/FDEXE.sh" + +echo Package DMG... +hdiutil create -fs HFS+ -volname "$DMG" -srcfolder "$DIR" "$DMG" diff --git a/External/Tools/Bridge/FlashDevelopBridge.pro b/External/Tools/Bridge/FlashDevelopBridge.pro index 9a8c748cb5..ad0ce59399 100644 --- a/External/Tools/Bridge/FlashDevelopBridge.pro +++ b/External/Tools/Bridge/FlashDevelopBridge.pro @@ -4,30 +4,30 @@ # #------------------------------------------------- -QT += core gui +QT += core +QT += gui QT += network +QT += widgets -TARGET = FlashDevelopBridge +TARGET = "FlashDevelop Bridge" TEMPLATE = app - -SOURCES += main.cpp\ - mainwindow.cpp \ +SOURCES += main.cpp \ + mainwindow.cpp \ filesystemwatcherex.cpp \ bridgeserver.cpp \ bridgethread.cpp -HEADERS += mainwindow.h \ +HEADERS += mainwindow.h \ filesystemwatcherex.h \ bridgeserver.h \ bridgethread.h \ simplelog.h -FORMS += mainwindow.ui +FORMS += mainwindow.ui -RESOURCES += \ - res.qrc +RESOURCES += res.qrc -ICON = images/FDIcon.icns +ICON = Images/AppIcon.icns -QMAKE_INFO_PLIST = DMG/app.plist +QMAKE_INFO_PLIST = Deploy/app.plist diff --git a/External/Tools/Bridge/Images/AppIcon.icns b/External/Tools/Bridge/Images/AppIcon.icns new file mode 100644 index 0000000000..cd7e73b062 Binary files /dev/null and b/External/Tools/Bridge/Images/AppIcon.icns differ diff --git a/External/Tools/Bridge/Images/TrayIcon.png b/External/Tools/Bridge/Images/TrayIcon.png new file mode 100644 index 0000000000..ba43ed4720 Binary files /dev/null and b/External/Tools/Bridge/Images/TrayIcon.png differ diff --git a/External/Tools/Bridge/bridgeserver.cpp b/External/Tools/Bridge/bridgeserver.cpp index bd356e29ec..369a08d2b2 100644 --- a/External/Tools/Bridge/bridgeserver.cpp +++ b/External/Tools/Bridge/bridgeserver.cpp @@ -4,24 +4,17 @@ #include #include #include - #include "bridgeserver.h" #include "bridgethread.h" - -BridgeServer::BridgeServer(QObject *parent) - : QTcpServer(parent) +BridgeServer::BridgeServer(QObject *parent) : QTcpServer(parent) { runningThreads = 0; - QSettings settings; settings.beginGroup("server"); - qDebug() << "Connecting:" << settings.value("host").toString() << settings.value("port").toInt(); - QHostAddress host(settings.value("host").toString()); listen(host, settings.value("port").toInt()); - qDebug() << (isListening() ? "Success" : "Failure"); } @@ -30,7 +23,7 @@ void BridgeServer::notifyStatus() emit bridgeStatus(runningThreads, watched.keys().count()); } -void BridgeServer::incomingConnection(int socketDescriptor) +void BridgeServer::incomingConnection(qintptr socketDescriptor) { BridgeThread *thread = new BridgeThread(socketDescriptor, 0); connect(thread, SIGNAL(disconnected()), this, SLOT(threadDisconnected())); @@ -42,22 +35,17 @@ void BridgeServer::incomingConnection(int socketDescriptor) void BridgeServer::command(QString cmd, QString value) { BridgeThread *thread = (BridgeThread*)sender(); - //qDebug() << cmd << value; - + qDebug() << cmd << value; if (cmd == "watch") { releaseHandler(thread); - BridgeHandler *handler = createWatchHandler(value); handler->useCount++; thread->handler = handler; connect(handler, SIGNAL(notifyChanged(QString)), thread, SLOT(sendMessage(QString))); } - else if (cmd == "unwatch") releaseHandler(thread); - else if (cmd == "open") openDocument(value); - else qDebug() << cmd << value; } @@ -66,10 +54,8 @@ void BridgeServer::openDocument(QString path) BridgeHandler handler; QString localPath = handler.getLocalPath(path.replace('\\', '/')); qDebug() << "Open:" << localPath; - QFile file(localPath); - if (file.exists()) - QDesktopServices::openUrl(QUrl::fromLocalFile(localPath)); + if (file.exists()) QDesktopServices::openUrl(QUrl::fromLocalFile(localPath)); else qDebug() << "File not found:" << path; } @@ -90,7 +76,7 @@ BridgeHandler* BridgeServer::createWatchHandler(QString path) void BridgeServer::threadDisconnected() { BridgeThread *thread = (BridgeThread*)sender(); - //qDebug() << "disconnected" << thread; + qDebug() << "disconnected" << thread; releaseHandler(thread); thread->deleteLater(); runningThreads--; @@ -102,9 +88,7 @@ void BridgeServer::releaseHandler(BridgeThread *thread) if (thread->handler != 0) { disconnect(thread->handler, SIGNAL(notifyChanged(QString)), thread, SLOT(sendMessage(QString))); - - if (--thread->handler->useCount <= 0) - watched.remove(thread->handler->watched); + if (--thread->handler->useCount <= 0) watched.remove(thread->handler->watched); thread->handler = 0; } } diff --git a/External/Tools/Bridge/bridgeserver.h b/External/Tools/Bridge/bridgeserver.h index 9f4f07d724..778f92f1a8 100644 --- a/External/Tools/Bridge/bridgeserver.h +++ b/External/Tools/Bridge/bridgeserver.h @@ -8,10 +8,8 @@ class BridgeServer : public QTcpServer { Q_OBJECT - QHash watched; int runningThreads; - void releaseHandler(BridgeThread *thread); void openDocument(QString path); void notifyStatus(); @@ -21,7 +19,7 @@ class BridgeServer : public QTcpServer BridgeHandler *createWatchHandler(QString path); protected: - void incomingConnection(int socketDescriptor); + void incomingConnection(qintptr socketDescriptor); signals: void bridgeStatus(int threads, int watchers); diff --git a/External/Tools/Bridge/bridgethread.cpp b/External/Tools/Bridge/bridgethread.cpp index a556ede283..5e4a14ff41 100644 --- a/External/Tools/Bridge/bridgethread.cpp +++ b/External/Tools/Bridge/bridgethread.cpp @@ -2,25 +2,29 @@ #include #include #include "bridgethread.h" - #define EOL "*" +bool BridgeThread::pathNotified = false; + BridgeThread::BridgeThread(int descriptor, QObject *parent) : QObject(parent) { socketDescriptor = descriptor; handler = 0; client = new QTcpSocket(); - if (!client->setSocketDescriptor(socketDescriptor)) { - //emit error(client.error()); qDebug() << "Socket init error:" << client->errorString(); return; } - + if (!BridgeThread::pathNotified) + { + qDebug() << "Notify bridge path..."; + BridgeThread::pathNotified = true; + QString path = QCoreApplication::applicationDirPath(); + BridgeThread::sendMessage("BRIDGE:" + path.toUtf8()); + } connect(client, SIGNAL(disconnected()), this, SLOT(client_disconnected())); connect(client, SIGNAL(readyRead()), this, SLOT(client_readyRead())); - timer.setSingleShot(true); connect(&timer, SIGNAL(timeout()), this, SLOT(timer_elapsed())); } @@ -71,12 +75,10 @@ void BridgeThread::client_disconnected() void BridgeThread::sendMessage(QString message) { QMutexLocker locker(&mutex); - if (!queue.contains(message)) - queue << message; + if (!queue.contains(message)) queue << message; timer.start(100); } - /* COMMANDS HANDLING */ BridgeHandler::BridgeHandler(QObject *parent) : QObject(parent) @@ -103,7 +105,6 @@ void BridgeHandler::command(QString name, QString param) void BridgeHandler::watchPath(QString param) { watched = param; - QStringList hasFilter(param.split('*')); if (hasFilter.length() > 1) { @@ -111,22 +112,17 @@ void BridgeHandler::watchPath(QString param) remotePath = hasFilter[0].replace('\\', '/'); } else remotePath = param.replace('\\', '/'); - localPath = getLocalPath(remotePath); - bool isDir = localPath.endsWith('/'); if (isDir) { remotePath.chop(1); localPath.chop(1); } - watchedPath = localPath; - //qDebug() << "watch" << watchedPath << filter; - + qDebug() << "watch" << watchedPath << filter; fsw = new FileSystemWatcherEx(this); connect(fsw, SIGNAL(fileSystemChanged(QString)), this, SLOT(localChanged(QString))); - if (isSpecial) { watchedPath = getSpecialPath(); @@ -162,7 +158,6 @@ QString BridgeHandler::getLocalPath(QString path) } } if (local.isEmpty()) local = path; - if (local.contains(".FlashDevelop")) { special = QDir(local).dirName(); @@ -174,10 +169,7 @@ QString BridgeHandler::getLocalPath(QString path) QString BridgeHandler::getRemotePath(QString path) { - if (isSpecial) - { - return remotePath; - } + if (isSpecial) return remotePath; else { int len = localPath.length(); @@ -196,16 +188,13 @@ void BridgeHandler::localChanged(QString path) QDir dir(path); dir.setNameFilters(filter); QStringList files(dir.entryList()); - if (files.length() == 0) - return; // no file matches filter - + if (files.length() == 0) return; // no file matches filter foreach(QString name, files) { copyPatched(path + name, localPath + "/" + name); } path = localPath; } - path = getRemotePath(path); if (path.length() > 0) { @@ -220,7 +209,6 @@ void BridgeHandler::copyPatched(QString filePath, QString destPath) if (!file.open(QIODevice::ReadOnly)) return; QString src = QString::fromUtf8(file.readAll().data()); file.close(); - // replace local paths by remote paths QSettings settings; settings.beginGroup("localRemoteMap"); @@ -230,7 +218,6 @@ void BridgeHandler::copyPatched(QString filePath, QString destPath) QString local(settings.value(key).toString()); src = src.replace(local, remote); } - QFile dest(destPath); if (!dest.open(QIODevice::WriteOnly)) return; dest.write(src.toUtf8()); diff --git a/External/Tools/Bridge/bridgethread.h b/External/Tools/Bridge/bridgethread.h index cd063c88e0..507c7a7f1e 100644 --- a/External/Tools/Bridge/bridgethread.h +++ b/External/Tools/Bridge/bridgethread.h @@ -11,7 +11,6 @@ class BridgeHandler : public QObject { Q_OBJECT - QString remotePath; QStringList filter; bool isSpecial; @@ -19,7 +18,6 @@ class BridgeHandler : public QObject QString localPath; QString watchedPath; FileSystemWatcherEx *fsw; - void watchPath(QString param); QString getSpecialPath(); QString getRemotePath(QString path); @@ -30,7 +28,6 @@ class BridgeHandler : public QObject ~BridgeHandler(); QString watched; int useCount; - QString getLocalPath(QString path); signals: @@ -43,11 +40,9 @@ private slots: void localChanged(QString localPath); }; - class BridgeThread : public QObject { Q_OBJECT - int socketDescriptor; QTcpSocket *client; QTimer timer; @@ -58,6 +53,7 @@ class BridgeThread : public QObject BridgeThread(int descriptor, QObject *parent); ~BridgeThread(); BridgeHandler *handler; + static bool pathNotified; signals: void disconnected(); diff --git a/External/Tools/Bridge/filesystemwatcherex.cpp b/External/Tools/Bridge/filesystemwatcherex.cpp index 53630f36eb..2033b5b61a 100644 --- a/External/Tools/Bridge/filesystemwatcherex.cpp +++ b/External/Tools/Bridge/filesystemwatcherex.cpp @@ -2,8 +2,7 @@ #include #include "filesystemwatcherex.h" -FileSystemWatcherEx::FileSystemWatcherEx(QObject *parent) : - QObject(parent) +FileSystemWatcherEx::FileSystemWatcherEx(QObject *parent) : QObject(parent) { basePath = ""; watchedFile = 0; @@ -25,7 +24,6 @@ void FileSystemWatcherEx::setPath(QString path, bool includeSubdirectories) { if (path == "") return; QDir dir(path); - if (dir.exists()) { qDebug() << "Watching:" << path; @@ -43,7 +41,6 @@ void FileSystemWatcherEx::setFile(QString path) { if (path == "") return; QFileInfo file(path); - if (file.exists()) { qDebug() << "Watching:" << path; @@ -57,17 +54,16 @@ void FileSystemWatcherEx::setFile(QString path) } // Explore folders in depth and return concaneted list of folder paths + QStringList FileSystemWatcherEx::subFoldersList(QString path) { QDir dir(path); dir.setFilter(QDir::Dirs); - QStringList dirList; dirList << dir.absolutePath(); - QFileInfoList list = dir.entryInfoList(); - - for (int i = 0; i < list.size(); ++i) { + for (int i = 0; i < list.size(); ++i) + { QFileInfo fileInfo = list.at(i); QString name = fileInfo.fileName(); if (name[0] == '.' || name[0] == '_') continue; @@ -78,10 +74,8 @@ QStringList FileSystemWatcherEx::subFoldersList(QString path) void FileSystemWatcherEx::fileChanged(QString path) { - if (!watchedFile->file.startsWith(path)) - return; + if (!watchedFile->file.startsWith(path)) return; qDebug() << "Changed:" << path; - QFileInfo info(watchedFile->file); if (info.exists()) { @@ -104,7 +98,6 @@ void FileSystemWatcherEx::fileChanged(QString path) void FileSystemWatcherEx::directoryChanged(QString path) { qDebug() << "Changed:" << path; - QDir dir(path); if (dir.exists()) // content changed { @@ -112,7 +105,9 @@ void FileSystemWatcherEx::directoryChanged(QString path) { QStringList dirs = fsw->directories(); foreach(QString sub, subFoldersList(path)) + { if (!dirs.contains(sub)) fsw->addPath(sub); + } } emit fileSystemChanged(path); } diff --git a/External/Tools/Bridge/filesystemwatcherex.h b/External/Tools/Bridge/filesystemwatcherex.h index dd72f462d3..5b48c31c65 100644 --- a/External/Tools/Bridge/filesystemwatcherex.h +++ b/External/Tools/Bridge/filesystemwatcherex.h @@ -6,26 +6,24 @@ #include #include -class WatchedFile { +class WatchedFile +{ public: - WatchedFile(QFileInfo info) { + WatchedFile(QFileInfo info) + { file = info.absoluteFilePath(); exists = info.exists(); if (exists) lastModified = info.lastModified(); } - QString file; QDateTime lastModified; bool exists; }; - class FileSystemWatcherEx : public QObject { Q_OBJECT - QStringList subFoldersList(QString folder); - QFileSystemWatcher *fsw; QString basePath; bool includeSubs; diff --git a/External/Tools/Bridge/images/FDIcon.icns b/External/Tools/Bridge/images/FDIcon.icns deleted file mode 100644 index fa53c4b49f..0000000000 Binary files a/External/Tools/Bridge/images/FDIcon.icns and /dev/null differ diff --git a/External/Tools/Bridge/images/FDIcon.png b/External/Tools/Bridge/images/FDIcon.png deleted file mode 100644 index 985e48ba0e..0000000000 Binary files a/External/Tools/Bridge/images/FDIcon.png and /dev/null differ diff --git a/External/Tools/Bridge/images/trayicon.png b/External/Tools/Bridge/images/trayicon.png deleted file mode 100644 index 10b0cf1fce..0000000000 Binary files a/External/Tools/Bridge/images/trayicon.png and /dev/null differ diff --git a/External/Tools/Bridge/main.cpp b/External/Tools/Bridge/main.cpp index 556c4ac3c4..14c214f5f1 100644 --- a/External/Tools/Bridge/main.cpp +++ b/External/Tools/Bridge/main.cpp @@ -1,16 +1,14 @@ -#include +#include #include "mainwindow.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); - - QCoreApplication::setApplicationName("Bridge"); - QCoreApplication::setOrganizationDomain("flashdevelop.org"); - QCoreApplication::setOrganizationName("FlashDevelop"); - + QCoreApplication::setApplicationName("FlashDevelop Bridge"); + QCoreApplication::setOrganizationDomain("www.flashdevelop.org"); + QCoreApplication::setOrganizationName("FlashDevelop.org"); + QCoreApplication::setApplicationVersion("2.0.0"); MainWindow w; //w.show(); - return a.exec(); } diff --git a/External/Tools/Bridge/mainwindow.cpp b/External/Tools/Bridge/mainwindow.cpp index e076a83001..e7669afc54 100644 --- a/External/Tools/Bridge/mainwindow.cpp +++ b/External/Tools/Bridge/mainwindow.cpp @@ -1,29 +1,24 @@ #include #include #include +#include #include #include "simplelog.h" #include "mainwindow.h" #include "ui_mainwindow.h" -MainWindow::MainWindow(QWidget *parent) : - QMainWindow(parent), - ui(new Ui::MainWindow) +MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { QString logPath = QDir::homePath() + "/.fdbridge_log"; - logfile.open(logPath.toAscii().data()); - qInstallMsgHandler(SimpleLogHandler); - + logfile.open(logPath.toUtf8().data()); + qInstallMessageHandler(SimpleLogHandler); ui->setupUi(this); - setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint); showOnStart = false; - initTray(); initStatusBar(); initMapping(); initServer(); - if (showOnStart) show(); } @@ -33,23 +28,19 @@ MainWindow::~MainWindow() delete ui; } - /* TRAY ICON */ void MainWindow::initTray() { sti = new QSystemTrayIcon(this); - QIcon img(":/images/trayicon.png"); + QIcon img(":/Images/TrayIcon.png"); sti->setIcon(img); sti->setVisible(true); - QMenu *stiMenu = new QMenu(this); sti->setContextMenu(stiMenu); - QAction *item = new QAction("Configure", this); stiMenu->addAction(item); connect(item, SIGNAL(triggered()), this, SLOT(showWindow())); - item = new QAction("Exit", this); stiMenu->addAction(item); connect(item, SIGNAL(triggered()), this, SLOT(quit())); @@ -73,7 +64,6 @@ void MainWindow::closeEvent(QCloseEvent *event) event->ignore(); } - /* HELPER SERVER */ void MainWindow::initServer() @@ -82,20 +72,17 @@ void MainWindow::initServer() settings.beginGroup("server"); if (!settings.contains("host")) settings.setValue("host", "127.0.0.1"); if (!settings.contains("port")) settings.setValue("port", 8009); - server = new BridgeServer(); if (server->isListening()) { connect(server, SIGNAL(bridgeStatus(int,int)), this, SLOT(bridgeStatus(int,int))); - statusLabel->setText( QString("Listening to port %1").arg(settings.value("port").toString()) ); - + statusLabel->setText(QString("Listening to port %1").arg(settings.value("port").toString()) ); QString msg = QString("Is now listening to port %1").arg(settings.value("port").toString()); sti->showMessage("FlashDevelop Bridge", msg/*, QSystemTrayIcon::NoIcon*/); } - else statusLabel->setText( QString("Failed to listen to port %1").arg(settings.value("port").toInt()) ); + else statusLabel->setText(QString("Failed to listen to port %1").arg(settings.value("port").toInt()) ); } - /* STATUS BAR */ void MainWindow::initStatusBar() @@ -113,7 +100,6 @@ void MainWindow::bridgeStatus(int threads, int watchers) statusLabel->setText(msg); } - /* LOCAL REMOTE MAPPING EDITION */ void MainWindow::initMapping() @@ -125,15 +111,13 @@ void MainWindow::initMapping() if (map.length() == 0) { showOnStart = true; - settings.setValue("Z", QDir::homePath() + "/Dev"); + settings.setValue("Y", QDir::homePath()); settings.endGroup(); settings.beginGroup("localRemoteMap"); map = settings.allKeys(); } - ui->listMap->setRowCount(map.length()); ui->listMap->setColumnWidth(0, 100); - int line = 0; foreach(QString key, map) { @@ -143,10 +127,8 @@ void MainWindow::initMapping() ui->listMap->setItem(line, 1, item); line++; } - ui->btRemove->setEnabled(false); lockSettings = false; - updateSettings(); // validate entries } @@ -193,7 +175,7 @@ void MainWindow::on_listMap_itemSelectionChanged() ui->btRemove->setEnabled(active); } -void MainWindow::on_listMap_cellChanged(int row, int column) +void MainWindow::on_listMap_cellChanged(int, int) { updateSettings(); } @@ -203,14 +185,11 @@ void MainWindow::updateSettings() if (lockSettings) return; QSettings settings; settings.beginGroup("localRemoteMap"); - // clear foreach(QString key, settings.allKeys()) settings.remove(key); - // populate from valid lines in grid QColor error(QColor::fromRgb(0xff, 0xcc, 0x66)); QColor valid(ui->listMap->palette().base().color()); - int lines = ui->listMap->rowCount(); QRegExp reRemote("([H-Z]):\\\\"); for (int i = 0; i < lines; ++i) @@ -234,7 +213,6 @@ void MainWindow::updateSettings() remoteValid = true; } } - item = ui->listMap->item(i, 1); QString local(item->text()); bool localValid = false; @@ -253,9 +231,6 @@ void MainWindow::updateSettings() localValid = true; } } - - if (remoteValid && localValid) - settings.setValue(remote, local); + if (remoteValid && localValid) settings.setValue(remote, local); } } - diff --git a/External/Tools/Bridge/mainwindow.h b/External/Tools/Bridge/mainwindow.h index 7fa9d43c84..4854d17564 100644 --- a/External/Tools/Bridge/mainwindow.h +++ b/External/Tools/Bridge/mainwindow.h @@ -4,10 +4,12 @@ #include #include #include +#include #include "bridgeserver.h" #include "filesystemwatcherex.h" -namespace Ui { +namespace Ui +{ class MainWindow; } @@ -37,10 +39,8 @@ private slots: BridgeServer *server; bool lockSettings; bool showOnStart; - QLabel *statusLabel; QStatusBar *statusBar; - void initTray(); void initStatusBar(); void initMapping(); diff --git a/External/Tools/Bridge/mainwindow.ui b/External/Tools/Bridge/mainwindow.ui index 33c2210558..ac20810abb 100644 --- a/External/Tools/Bridge/mainwindow.ui +++ b/External/Tools/Bridge/mainwindow.ui @@ -6,8 +6,8 @@ 0 0 - 400 - 179 + 450 + 220 @@ -23,7 +23,10 @@ - Paths mapping + <html><head/><body><p>Path mapping (<a href="http://www.flashdevelop.org/wikidocs/index.php?title=Bridge" target="_blank"><span style=" text-decoration: underline; color:#0000ff;">info</span></a>)</p></body></html> + + + true diff --git a/External/Tools/Bridge/res.qrc b/External/Tools/Bridge/res.qrc index 986cdb2b5b..1589879d44 100644 --- a/External/Tools/Bridge/res.qrc +++ b/External/Tools/Bridge/res.qrc @@ -1,5 +1,5 @@ - images/trayicon.png + Images/TrayIcon.png diff --git a/External/Tools/Bridge/simplelog.h b/External/Tools/Bridge/simplelog.h index f1b7300fbc..c294afee11 100644 --- a/External/Tools/Bridge/simplelog.h +++ b/External/Tools/Bridge/simplelog.h @@ -8,20 +8,21 @@ using namespace std; ofstream logfile; -void SimpleLogHandler(QtMsgType type, const char *msg) +void SimpleLogHandler(QtMsgType type, const QMessageLogContext&, const QString& msg) { - switch (type) { + switch (type) + { case QtDebugMsg: - logfile << QTime::currentTime().toString().toAscii().data() << " : " << msg << "\n"; + logfile << QTime::currentTime().toString().toLatin1().data() << " : " << msg.toLatin1().data() << "\n"; break; case QtCriticalMsg: - logfile << QTime::currentTime().toString().toAscii().data() << " Critical: " << msg << "\n"; + logfile << QTime::currentTime().toString().toLatin1().data() << " Critical: " << msg.toLatin1().data() << "\n"; break; case QtWarningMsg: - logfile << QTime::currentTime().toString().toAscii().data() << " Warning: " << msg << "\n"; + logfile << QTime::currentTime().toString().toLatin1().data() << " Warning: " << msg.toLatin1().data() << "\n"; break; case QtFatalMsg: - logfile << QTime::currentTime().toString().toAscii().data() << " Fatal: " << msg << "\n"; + logfile << QTime::currentTime().toString().toLatin1().data() << " Fatal: " << msg.toLatin1().data() << "\n"; abort(); } logfile.flush(); diff --git a/External/Tools/DiffUI/DiffUI.csproj b/External/Tools/DiffUI/DiffUI.csproj index 73e265805d..da8711b60e 100644 --- a/External/Tools/DiffUI/DiffUI.csproj +++ b/External/Tools/DiffUI/DiffUI.csproj @@ -1,9 +1,7 @@ - + Debug AnyCPU - 8.0.50727 - 2.0 {8E5308B1-B4E8-4AF2-B892-D22432973D2D} WinExe Properties @@ -11,10 +9,14 @@ diffui - 3.5 - v3.5 + net48 + true + false + false + false + false false @@ -64,12 +66,5 @@ - - + \ No newline at end of file diff --git a/External/Tools/DiffUI/DifferenceEngine/CharData.cs b/External/Tools/DiffUI/DifferenceEngine/CharData.cs index 50998351c8..a158c9ac5e 100644 --- a/External/Tools/DiffUI/DifferenceEngine/CharData.cs +++ b/External/Tools/DiffUI/DifferenceEngine/CharData.cs @@ -3,26 +3,26 @@ namespace DifferenceEngine { - public class DiffList_CharData : IDiffList - { - private char[] _charList; + public class DiffList_CharData : IDiffList + { + private char[] _charList; - public DiffList_CharData(string charData) - { - _charList = charData.ToCharArray(); - } - #region IDiffList Members + public DiffList_CharData(string charData) + { + _charList = charData.ToCharArray(); + } + #region IDiffList Members - public int Count() - { - return _charList.Length; - } + public int Count() + { + return _charList.Length; + } - public IComparable GetByIndex(int index) - { - return _charList[index]; - } + public IComparable GetByIndex(int index) + { + return _charList[index]; + } - #endregion - } + #endregion + } } \ No newline at end of file diff --git a/External/Tools/DiffUI/DifferenceEngine/Engine.cs b/External/Tools/DiffUI/DifferenceEngine/Engine.cs index 3ab4d83e48..3169837ae7 100644 --- a/External/Tools/DiffUI/DifferenceEngine/Engine.cs +++ b/External/Tools/DiffUI/DifferenceEngine/Engine.cs @@ -3,304 +3,304 @@ namespace DifferenceEngine { - public enum DiffEngineLevel - { - FastImperfect, - Medium, - SlowPerfect - } + public enum DiffEngineLevel + { + FastImperfect, + Medium, + SlowPerfect + } - public class DiffEngine - { - private IDiffList _source; - private IDiffList _dest; - private ArrayList _matchList; + public class DiffEngine + { + private IDiffList _source; + private IDiffList _dest; + private ArrayList _matchList; - private DiffEngineLevel _level; + private DiffEngineLevel _level; - private DiffStateList _stateList; + private DiffStateList _stateList; - public DiffEngine() - { - _source = null; - _dest = null; - _matchList = null; - _stateList = null; - _level = DiffEngineLevel.FastImperfect; - } + public DiffEngine() + { + _source = null; + _dest = null; + _matchList = null; + _stateList = null; + _level = DiffEngineLevel.FastImperfect; + } - private int GetSourceMatchLength(int destIndex, int sourceIndex, int maxLength) - { - int matchCount; - for (matchCount = 0; matchCount < maxLength; matchCount++) - { - if ( _dest.GetByIndex(destIndex + matchCount).CompareTo(_source.GetByIndex(sourceIndex + matchCount)) != 0 ) - { - break; - } - } - return matchCount; - } + private int GetSourceMatchLength(int destIndex, int sourceIndex, int maxLength) + { + int matchCount; + for (matchCount = 0; matchCount < maxLength; matchCount++) + { + if ( _dest.GetByIndex(destIndex + matchCount).CompareTo(_source.GetByIndex(sourceIndex + matchCount)) != 0 ) + { + break; + } + } + return matchCount; + } - private void GetLongestSourceMatch(DiffState curItem, int destIndex,int destEnd, int sourceStart,int sourceEnd) - { - - int maxDestLength = (destEnd - destIndex) + 1; - int curLength = 0; - int curBestLength = 0; - int curBestIndex = -1; - int maxLength = 0; - for (int sourceIndex = sourceStart; sourceIndex <= sourceEnd; sourceIndex++) - { - maxLength = Math.Min(maxDestLength,(sourceEnd - sourceIndex) + 1); - if (maxLength <= curBestLength) - { - //No chance to find a longer one any more - break; - } - curLength = GetSourceMatchLength(destIndex,sourceIndex,maxLength); - if (curLength > curBestLength) - { - //This is the best match so far - curBestIndex = sourceIndex; - curBestLength = curLength; - } - //jump over the match - sourceIndex += curBestLength; - } - //DiffState cur = _stateList.GetByIndex(destIndex); - if (curBestIndex == -1) - { - curItem.SetNoMatch(); - } - else - { - curItem.SetMatch(curBestIndex, curBestLength); - } - - } + private void GetLongestSourceMatch(DiffState curItem, int destIndex,int destEnd, int sourceStart,int sourceEnd) + { + + int maxDestLength = (destEnd - destIndex) + 1; + int curLength = 0; + int curBestLength = 0; + int curBestIndex = -1; + int maxLength = 0; + for (int sourceIndex = sourceStart; sourceIndex <= sourceEnd; sourceIndex++) + { + maxLength = Math.Min(maxDestLength,(sourceEnd - sourceIndex) + 1); + if (maxLength <= curBestLength) + { + //No chance to find a longer one any more + break; + } + curLength = GetSourceMatchLength(destIndex,sourceIndex,maxLength); + if (curLength > curBestLength) + { + //This is the best match so far + curBestIndex = sourceIndex; + curBestLength = curLength; + } + //jump over the match + sourceIndex += curBestLength; + } + //DiffState cur = _stateList.GetByIndex(destIndex); + if (curBestIndex == -1) + { + curItem.SetNoMatch(); + } + else + { + curItem.SetMatch(curBestIndex, curBestLength); + } + + } - private void ProcessRange(int destStart, int destEnd, int sourceStart, int sourceEnd) - { - int curBestIndex = -1; - int curBestLength = -1; - int maxPossibleDestLength = 0; - DiffState curItem = null; - DiffState bestItem = null; - for (int destIndex = destStart; destIndex <= destEnd; destIndex++) - { - maxPossibleDestLength = (destEnd - destIndex) + 1; - if (maxPossibleDestLength <= curBestLength) - { - //we won't find a longer one even if we looked - break; - } - curItem = _stateList.GetByIndex(destIndex); - - if (!curItem.HasValidLength(sourceStart, sourceEnd, maxPossibleDestLength)) - { - //recalc new best length since it isn't valid or has never been done. - GetLongestSourceMatch(curItem, destIndex, destEnd, sourceStart, sourceEnd); - } - if (curItem.Status == DiffStatus.Matched) - { - switch (_level) - { - case DiffEngineLevel.FastImperfect: - if (curItem.Length > curBestLength) - { - //this is longest match so far - curBestIndex = destIndex; - curBestLength = curItem.Length; - bestItem = curItem; - } - //Jump over the match - destIndex += curItem.Length - 1; - break; - case DiffEngineLevel.Medium: - if (curItem.Length > curBestLength) - { - //this is longest match so far - curBestIndex = destIndex; - curBestLength = curItem.Length; - bestItem = curItem; - //Jump over the match - destIndex += curItem.Length - 1; - } - break; - default: - if (curItem.Length > curBestLength) - { - //this is longest match so far - curBestIndex = destIndex; - curBestLength = curItem.Length; - bestItem = curItem; - } - break; - } - } - } - if (curBestIndex < 0) - { - //we are done - there are no matches in this span - } - else - { - - int sourceIndex = bestItem.StartIndex; - _matchList.Add(DiffResultSpan.CreateNoChange(curBestIndex,sourceIndex,curBestLength)); - if (destStart < curBestIndex) - { - //Still have more lower destination data - if (sourceStart < sourceIndex) - { - //Still have more lower source data - // Recursive call to process lower indexes - ProcessRange(destStart, curBestIndex -1,sourceStart, sourceIndex -1); - } - } - int upperDestStart = curBestIndex + curBestLength; - int upperSourceStart = sourceIndex + curBestLength; - if (destEnd > upperDestStart) - { - //we still have more upper dest data - if (sourceEnd > upperSourceStart) - { - //set still have more upper source data - // Recursive call to process upper indexes - ProcessRange(upperDestStart,destEnd,upperSourceStart,sourceEnd); - } - } - } - } + private void ProcessRange(int destStart, int destEnd, int sourceStart, int sourceEnd) + { + int curBestIndex = -1; + int curBestLength = -1; + int maxPossibleDestLength = 0; + DiffState curItem = null; + DiffState bestItem = null; + for (int destIndex = destStart; destIndex <= destEnd; destIndex++) + { + maxPossibleDestLength = (destEnd - destIndex) + 1; + if (maxPossibleDestLength <= curBestLength) + { + //we won't find a longer one even if we looked + break; + } + curItem = _stateList.GetByIndex(destIndex); + + if (!curItem.HasValidLength(sourceStart, sourceEnd, maxPossibleDestLength)) + { + //recalc new best length since it isn't valid or has never been done. + GetLongestSourceMatch(curItem, destIndex, destEnd, sourceStart, sourceEnd); + } + if (curItem.Status == DiffStatus.Matched) + { + switch (_level) + { + case DiffEngineLevel.FastImperfect: + if (curItem.Length > curBestLength) + { + //this is longest match so far + curBestIndex = destIndex; + curBestLength = curItem.Length; + bestItem = curItem; + } + //Jump over the match + destIndex += curItem.Length - 1; + break; + case DiffEngineLevel.Medium: + if (curItem.Length > curBestLength) + { + //this is longest match so far + curBestIndex = destIndex; + curBestLength = curItem.Length; + bestItem = curItem; + //Jump over the match + destIndex += curItem.Length - 1; + } + break; + default: + if (curItem.Length > curBestLength) + { + //this is longest match so far + curBestIndex = destIndex; + curBestLength = curItem.Length; + bestItem = curItem; + } + break; + } + } + } + if (curBestIndex < 0) + { + //we are done - there are no matches in this span + } + else + { + + int sourceIndex = bestItem.StartIndex; + _matchList.Add(DiffResultSpan.CreateNoChange(curBestIndex,sourceIndex,curBestLength)); + if (destStart < curBestIndex) + { + //Still have more lower destination data + if (sourceStart < sourceIndex) + { + //Still have more lower source data + // Recursive call to process lower indexes + ProcessRange(destStart, curBestIndex -1,sourceStart, sourceIndex -1); + } + } + int upperDestStart = curBestIndex + curBestLength; + int upperSourceStart = sourceIndex + curBestLength; + if (destEnd > upperDestStart) + { + //we still have more upper dest data + if (sourceEnd > upperSourceStart) + { + //set still have more upper source data + // Recursive call to process upper indexes + ProcessRange(upperDestStart,destEnd,upperSourceStart,sourceEnd); + } + } + } + } - public double ProcessDiff(IDiffList source, IDiffList destination,DiffEngineLevel level) - { - _level = level; - return ProcessDiff(source,destination); - } + public double ProcessDiff(IDiffList source, IDiffList destination,DiffEngineLevel level) + { + _level = level; + return ProcessDiff(source,destination); + } - public double ProcessDiff(IDiffList source, IDiffList destination) - { - DateTime dt = DateTime.Now; - _source = source; - _dest = destination; - _matchList = new ArrayList(); - - int dcount = _dest.Count(); - int scount = _source.Count(); - - - if ((dcount > 0)&&(scount > 0)) - { - _stateList = new DiffStateList(dcount); - ProcessRange(0,dcount - 1,0, scount - 1); - } + public double ProcessDiff(IDiffList source, IDiffList destination) + { + DateTime dt = DateTime.Now; + _source = source; + _dest = destination; + _matchList = new ArrayList(); + + int dcount = _dest.Count(); + int scount = _source.Count(); + + + if ((dcount > 0)&&(scount > 0)) + { + _stateList = new DiffStateList(dcount); + ProcessRange(0,dcount - 1,0, scount - 1); + } - TimeSpan ts = DateTime.Now - dt; - return ts.TotalSeconds; - } + TimeSpan ts = DateTime.Now - dt; + return ts.TotalSeconds; + } - private bool AddChanges( - ArrayList report, - int curDest, - int nextDest, - int curSource, - int nextSource) - { - bool retval = false; - int diffDest = nextDest - curDest; - int diffSource = nextSource - curSource; - int minDiff = 0; - if (diffDest > 0) - { - if (diffSource > 0) - { - minDiff = Math.Min(diffDest,diffSource); - report.Add(DiffResultSpan.CreateReplace(curDest,curSource,minDiff)); - if (diffDest > diffSource) - { - curDest+=minDiff; - report.Add(DiffResultSpan.CreateAddDestination(curDest,diffDest - diffSource)); - } - else - { - if (diffSource > diffDest) - { - curSource+= minDiff; - report.Add(DiffResultSpan.CreateDeleteSource(curSource,diffSource - diffDest)); - } - } - } - else - { - report.Add(DiffResultSpan.CreateAddDestination(curDest,diffDest)); - } - retval = true; - } - else - { - if (diffSource > 0) - { - report.Add(DiffResultSpan.CreateDeleteSource(curSource,diffSource)); - retval = true; - } - } - return retval; - } + private bool AddChanges( + ArrayList report, + int curDest, + int nextDest, + int curSource, + int nextSource) + { + bool retval = false; + int diffDest = nextDest - curDest; + int diffSource = nextSource - curSource; + int minDiff = 0; + if (diffDest > 0) + { + if (diffSource > 0) + { + minDiff = Math.Min(diffDest,diffSource); + report.Add(DiffResultSpan.CreateReplace(curDest,curSource,minDiff)); + if (diffDest > diffSource) + { + curDest+=minDiff; + report.Add(DiffResultSpan.CreateAddDestination(curDest,diffDest - diffSource)); + } + else + { + if (diffSource > diffDest) + { + curSource+= minDiff; + report.Add(DiffResultSpan.CreateDeleteSource(curSource,diffSource - diffDest)); + } + } + } + else + { + report.Add(DiffResultSpan.CreateAddDestination(curDest,diffDest)); + } + retval = true; + } + else + { + if (diffSource > 0) + { + report.Add(DiffResultSpan.CreateDeleteSource(curSource,diffSource)); + retval = true; + } + } + return retval; + } - public ArrayList DiffReport() - { - ArrayList retval = new ArrayList(); - int dcount = _dest.Count(); - int scount = _source.Count(); - - //Deal with the special case of empty files - if (dcount == 0) - { - if (scount > 0) - { - retval.Add(DiffResultSpan.CreateDeleteSource(0,scount)); - } - return retval; - } - else - { - if (scount == 0) - { - retval.Add(DiffResultSpan.CreateAddDestination(0,dcount)); - return retval; - } - } + public ArrayList DiffReport() + { + ArrayList retval = new ArrayList(); + int dcount = _dest.Count(); + int scount = _source.Count(); + + //Deal with the special case of empty files + if (dcount == 0) + { + if (scount > 0) + { + retval.Add(DiffResultSpan.CreateDeleteSource(0,scount)); + } + return retval; + } + else + { + if (scount == 0) + { + retval.Add(DiffResultSpan.CreateAddDestination(0,dcount)); + return retval; + } + } - _matchList.Sort(); - int curDest = 0; - int curSource = 0; - DiffResultSpan last = null; + _matchList.Sort(); + int curDest = 0; + int curSource = 0; + DiffResultSpan last = null; - //Process each match record - foreach (DiffResultSpan drs in _matchList) - { - if ((!AddChanges(retval,curDest,drs.DestIndex,curSource,drs.SourceIndex))&& - (last != null)) - { - last.AddLength(drs.Length); - } - else - { - retval.Add(drs); - } - curDest = drs.DestIndex + drs.Length; - curSource = drs.SourceIndex + drs.Length; - last = drs; - } - - //Process any tail end data - AddChanges(retval,curDest,dcount,curSource,scount); + //Process each match record + foreach (DiffResultSpan drs in _matchList) + { + if ((!AddChanges(retval,curDest,drs.DestIndex,curSource,drs.SourceIndex))&& + (last != null)) + { + last.AddLength(drs.Length); + } + else + { + retval.Add(drs); + } + curDest = drs.DestIndex + drs.Length; + curSource = drs.SourceIndex + drs.Length; + last = drs; + } + + //Process any tail end data + AddChanges(retval,curDest,dcount,curSource,scount); - return retval; - } - } + return retval; + } + } } diff --git a/External/Tools/DiffUI/DifferenceEngine/Structures.cs b/External/Tools/DiffUI/DifferenceEngine/Structures.cs index 89b23ba5bd..91881bb2c9 100644 --- a/External/Tools/DiffUI/DifferenceEngine/Structures.cs +++ b/External/Tools/DiffUI/DifferenceEngine/Structures.cs @@ -5,228 +5,228 @@ namespace DifferenceEngine { - public interface IDiffList - { - int Count(); - IComparable GetByIndex(int index); - } - - internal enum DiffStatus - { - Matched = 1, - NoMatch = -1, - Unknown = -2 - - } - - internal class DiffState - { - private const int BAD_INDEX = -1; - private int _startIndex; - private int _length; - - public int StartIndex {get{return _startIndex;}} - public int EndIndex {get{return ((_startIndex + _length) - 1);}} - public int Length - { - get - { - int len; - if (_length > 0) - { - len = _length; - } - else - { - if (_length == 0) - { - len = 1; - } - else - { - len = 0; - } - } - return len; - } - } - public DiffStatus Status - { - get - { - DiffStatus stat; - if (_length > 0) - { - stat = DiffStatus.Matched; - } - else - { - switch (_length) - { - case -1: - stat = DiffStatus.NoMatch; - break; - default: - System.Diagnostics.Debug.Assert(_length == -2,"Invalid status: _length < -2"); - stat = DiffStatus.Unknown; - break; - } - } - return stat; - } - } - - public DiffState() - { - SetToUnkown(); - } - - protected void SetToUnkown() - { - _startIndex = BAD_INDEX; - _length = (int)DiffStatus.Unknown; - } - - public void SetMatch(int start, int length) - { - System.Diagnostics.Debug.Assert(length > 0,"Length must be greater than zero"); - System.Diagnostics.Debug.Assert(start >= 0,"Start must be greater than or equal to zero"); - _startIndex = start; - _length = length; - } - - public void SetNoMatch() - { - _startIndex = BAD_INDEX; - _length = (int)DiffStatus.NoMatch; - } - - - public bool HasValidLength(int newStart, int newEnd, int maxPossibleDestLength) - { - if (_length > 0) //have unlocked match - { - if ((maxPossibleDestLength < _length)|| - ((_startIndex < newStart)||(EndIndex > newEnd))) - { - SetToUnkown(); - } - } - return (_length != (int)DiffStatus.Unknown); - } - } - - internal class DiffStateList - { + public interface IDiffList + { + int Count(); + IComparable GetByIndex(int index); + } + + internal enum DiffStatus + { + Matched = 1, + NoMatch = -1, + Unknown = -2 + + } + + internal class DiffState + { + private const int BAD_INDEX = -1; + private int _startIndex; + private int _length; + + public int StartIndex {get{return _startIndex;}} + public int EndIndex {get{return ((_startIndex + _length) - 1);}} + public int Length + { + get + { + int len; + if (_length > 0) + { + len = _length; + } + else + { + if (_length == 0) + { + len = 1; + } + else + { + len = 0; + } + } + return len; + } + } + public DiffStatus Status + { + get + { + DiffStatus stat; + if (_length > 0) + { + stat = DiffStatus.Matched; + } + else + { + switch (_length) + { + case -1: + stat = DiffStatus.NoMatch; + break; + default: + System.Diagnostics.Debug.Assert(_length == -2,"Invalid status: _length < -2"); + stat = DiffStatus.Unknown; + break; + } + } + return stat; + } + } + + public DiffState() + { + SetToUnkown(); + } + + protected void SetToUnkown() + { + _startIndex = BAD_INDEX; + _length = (int)DiffStatus.Unknown; + } + + public void SetMatch(int start, int length) + { + System.Diagnostics.Debug.Assert(length > 0,"Length must be greater than zero"); + System.Diagnostics.Debug.Assert(start >= 0,"Start must be greater than or equal to zero"); + _startIndex = start; + _length = length; + } + + public void SetNoMatch() + { + _startIndex = BAD_INDEX; + _length = (int)DiffStatus.NoMatch; + } + + + public bool HasValidLength(int newStart, int newEnd, int maxPossibleDestLength) + { + if (_length > 0) //have unlocked match + { + if ((maxPossibleDestLength < _length)|| + ((_startIndex < newStart)||(EndIndex > newEnd))) + { + SetToUnkown(); + } + } + return (_length != (int)DiffStatus.Unknown); + } + } + + internal class DiffStateList + { #if USE_HASH_TABLE - private Hashtable _table; + private Hashtable _table; #else - private DiffState[] _array; + private DiffState[] _array; #endif - public DiffStateList(int destCount) - { + public DiffStateList(int destCount) + { #if USE_HASH_TABLE - _table = new Hashtable(Math.Max(9,destCount/10)); + _table = new Hashtable(Math.Max(9,destCount/10)); #else - _array = new DiffState[destCount]; + _array = new DiffState[destCount]; #endif - } + } - public DiffState GetByIndex(int index) - { + public DiffState GetByIndex(int index) + { #if USE_HASH_TABLE - DiffState retval = (DiffState)_table[index]; - if (retval == null) - { - retval = new DiffState(); - _table.Add(index,retval); - } + DiffState retval = (DiffState)_table[index]; + if (retval == null) + { + retval = new DiffState(); + _table.Add(index,retval); + } #else - DiffState retval = _array[index]; - if (retval == null) - { - retval = new DiffState(); - _array[index] = retval; - } + DiffState retval = _array[index]; + if (retval == null) + { + retval = new DiffState(); + _array[index] = retval; + } #endif - return retval; - } - } - - - public enum DiffResultSpanStatus - { - NoChange, - Replace, - DeleteSource, - AddDestination - } - - public class DiffResultSpan : IComparable - { - private const int BAD_INDEX = -1; - private int _destIndex; - private int _sourceIndex; - private int _length; - private DiffResultSpanStatus _status; - - public int DestIndex {get{return _destIndex;}} - public int SourceIndex {get{return _sourceIndex;}} - public int Length {get{return _length;}} - public DiffResultSpanStatus Status {get{return _status;}} - - protected DiffResultSpan( - DiffResultSpanStatus status, - int destIndex, - int sourceIndex, - int length) - { - _status = status; - _destIndex = destIndex; - _sourceIndex = sourceIndex; - _length = length; - } - - public static DiffResultSpan CreateNoChange(int destIndex, int sourceIndex, int length) - { - return new DiffResultSpan(DiffResultSpanStatus.NoChange,destIndex,sourceIndex,length); - } - - public static DiffResultSpan CreateReplace(int destIndex, int sourceIndex, int length) - { - return new DiffResultSpan(DiffResultSpanStatus.Replace,destIndex,sourceIndex,length); - } - - public static DiffResultSpan CreateDeleteSource(int sourceIndex, int length) - { - return new DiffResultSpan(DiffResultSpanStatus.DeleteSource,BAD_INDEX,sourceIndex,length); - } - - public static DiffResultSpan CreateAddDestination(int destIndex, int length) - { - return new DiffResultSpan(DiffResultSpanStatus.AddDestination,destIndex,BAD_INDEX,length); - } - - public void AddLength(int i) - { - _length += i; - } - - public override string ToString() - { - return string.Format("{0} (Dest: {1},Source: {2}) {3}", - _status.ToString(), - _destIndex.ToString(), - _sourceIndex.ToString(), - _length.ToString()); - } - #region IComparable Members - - public int CompareTo(object obj) - { - return _destIndex.CompareTo(((DiffResultSpan)obj)._destIndex); - } - - #endregion - } + return retval; + } + } + + + public enum DiffResultSpanStatus + { + NoChange, + Replace, + DeleteSource, + AddDestination + } + + public class DiffResultSpan : IComparable + { + private const int BAD_INDEX = -1; + private int _destIndex; + private int _sourceIndex; + private int _length; + private DiffResultSpanStatus _status; + + public int DestIndex {get{return _destIndex;}} + public int SourceIndex {get{return _sourceIndex;}} + public int Length {get{return _length;}} + public DiffResultSpanStatus Status {get{return _status;}} + + protected DiffResultSpan( + DiffResultSpanStatus status, + int destIndex, + int sourceIndex, + int length) + { + _status = status; + _destIndex = destIndex; + _sourceIndex = sourceIndex; + _length = length; + } + + public static DiffResultSpan CreateNoChange(int destIndex, int sourceIndex, int length) + { + return new DiffResultSpan(DiffResultSpanStatus.NoChange,destIndex,sourceIndex,length); + } + + public static DiffResultSpan CreateReplace(int destIndex, int sourceIndex, int length) + { + return new DiffResultSpan(DiffResultSpanStatus.Replace,destIndex,sourceIndex,length); + } + + public static DiffResultSpan CreateDeleteSource(int sourceIndex, int length) + { + return new DiffResultSpan(DiffResultSpanStatus.DeleteSource,BAD_INDEX,sourceIndex,length); + } + + public static DiffResultSpan CreateAddDestination(int destIndex, int length) + { + return new DiffResultSpan(DiffResultSpanStatus.AddDestination,destIndex,BAD_INDEX,length); + } + + public void AddLength(int i) + { + _length += i; + } + + public override string ToString() + { + return string.Format("{0} (Dest: {1},Source: {2}) {3}", + _status.ToString(), + _destIndex.ToString(), + _sourceIndex.ToString(), + _length.ToString()); + } + #region IComparable Members + + public int CompareTo(object obj) + { + return _destIndex.CompareTo(((DiffResultSpan)obj)._destIndex); + } + + #endregion + } } \ No newline at end of file diff --git a/External/Tools/DiffUI/DifferenceEngine/TextFile.cs b/External/Tools/DiffUI/DifferenceEngine/TextFile.cs index d6518e1571..8ea34d23a9 100644 --- a/External/Tools/DiffUI/DifferenceEngine/TextFile.cs +++ b/External/Tools/DiffUI/DifferenceEngine/TextFile.cs @@ -4,66 +4,66 @@ namespace DifferenceEngine { - public class TextLine : IComparable - { - public string Line; - public int _hash; + public class TextLine : IComparable + { + public string Line; + public int _hash; - public TextLine(string str) - { - Line = str.Replace("\t"," "); - _hash = str.GetHashCode(); - } + public TextLine(string str) + { + Line = str.Replace("\t"," "); + _hash = str.GetHashCode(); + } - #region IComparable Members + #region IComparable Members - public int CompareTo(object obj) - { - return _hash.CompareTo(((TextLine)obj)._hash); - } + public int CompareTo(object obj) + { + return _hash.CompareTo(((TextLine)obj)._hash); + } - #endregion + #endregion - } + } - public class TextFile : IDiffList - { - //private const int MaxLineLength = 1024; - private ArrayList _lines; + public class TextFile : IDiffList + { + //private const int MaxLineLength = 1024; + private ArrayList _lines; - public TextFile(string fileName) - { - _lines = new ArrayList(); - using (StreamReader sr = new StreamReader(fileName)) - { - String line; - // Read and display lines from the file until the end of - // the file is reached. - while ((line = sr.ReadLine()) != null) - { - //if (line.Length > MaxLineLength) - //{ - //throw new InvalidOperationException(string.Format("File contains a line greater than {0} characters.", MaxLineLength.ToString())); - //} - _lines.Add(new TextLine(line)); - } - } - } + public TextFile(string fileName) + { + _lines = new ArrayList(); + using (StreamReader sr = new StreamReader(fileName)) + { + String line; + // Read and display lines from the file until the end of + // the file is reached. + while ((line = sr.ReadLine()) != null) + { + //if (line.Length > MaxLineLength) + //{ + //throw new InvalidOperationException(string.Format("File contains a line greater than {0} characters.", MaxLineLength.ToString())); + //} + _lines.Add(new TextLine(line)); + } + } + } - #region IDiffList Members + #region IDiffList Members - public int Count() - { - return _lines.Count; - } + public int Count() + { + return _lines.Count; + } - public IComparable GetByIndex(int index) - { - return (TextLine)_lines[index]; - } + public IComparable GetByIndex(int index) + { + return (TextLine)_lines[index]; + } - #endregion - - } + #endregion + + } } \ No newline at end of file diff --git a/External/Tools/DiffUI/MainForm.cs b/External/Tools/DiffUI/MainForm.cs index 6cc242db8b..e91cc418c1 100644 --- a/External/Tools/DiffUI/MainForm.cs +++ b/External/Tools/DiffUI/MainForm.cs @@ -21,9 +21,9 @@ public class MainForm : Form private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.ListView sourceListView; private System.Windows.Forms.ListView destinationListView; - private System.Windows.Forms.ColumnHeader sourceLineHeader; - private System.Windows.Forms.ColumnHeader sourceTextHeader; - private System.Windows.Forms.ColumnHeader destinationLineHeader; + private System.Windows.Forms.ColumnHeader sourceLineHeader; + private System.Windows.Forms.ColumnHeader sourceTextHeader; + private System.Windows.Forms.ColumnHeader destinationLineHeader; private System.Windows.Forms.ColumnHeader destinationTextHeader; private System.Windows.Forms.SplitContainer viewSplitContainer; private System.ComponentModel.BackgroundWorker backgroundWorker; @@ -41,14 +41,14 @@ public MainForm(String[] args) this.InitializeComponent(); } - #region Windows Form Designer Generated Code + #region Windows Form Designer Generated Code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { this.sourceListView = new System.Windows.Forms.ListView(); this.sourceLineHeader = new System.Windows.Forms.ColumnHeader(); this.sourceTextHeader = new System.Windows.Forms.ColumnHeader(); @@ -293,9 +293,9 @@ private void InitializeComponent() this.controlPanel.ResumeLayout(false); this.ResumeLayout(false); - } + } - #endregion + #endregion #region Methods And Event Handlers @@ -375,27 +375,27 @@ private void ListViewDragDrop(Object sender, DragEventArgs e) /// Changes the selected index of the other list view. ///
    private void SourceSelectedIndexChanged(Object sender, System.EventArgs e) - { - if (this.sourceListView.SelectedItems.Count > 0) - { + { + if (this.sourceListView.SelectedItems.Count > 0) + { ListViewItem lvi = this.destinationListView.Items[this.sourceListView.SelectedItems[0].Index]; lvi.Selected = true; - lvi.EnsureVisible(); - } - } + lvi.EnsureVisible(); + } + } /// /// Changes the selected index of the other list view. /// private void DestinationSelectedIndexChanged(Object sender, System.EventArgs e) - { + { if (this.destinationListView.SelectedItems.Count > 0) - { + { ListViewItem lvi = this.sourceListView.Items[this.destinationListView.SelectedItems[0].Index]; - lvi.Selected = true; - lvi.EnsureVisible(); - } - } + lvi.Selected = true; + lvi.EnsureVisible(); + } + } /// /// Selects the source file. diff --git a/External/Tools/FDBuild/AssemblyInfo.cs b/External/Tools/FDBuild/AssemblyInfo.cs index 99fa108c1f..705199e136 100644 --- a/External/Tools/FDBuild/AssemblyInfo.cs +++ b/External/Tools/FDBuild/AssemblyInfo.cs @@ -1,6 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information @@ -8,18 +6,18 @@ [assembly: AssemblyTitle("FDBuild")] [assembly: AssemblyDescription("Command-Line compiler for FlashDevelop project files.")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("FlashDevelop.org")] +[assembly: AssemblyCompany(PluginCore.DistroConfig.DISTRIBUTION_COMPANY)] [assembly: AssemblyProduct("FDBuild")] -[assembly: AssemblyCopyright("FlashDevelop 2005-2010")] +[assembly: AssemblyCopyright(PluginCore.DistroConfig.DISTRIBUTION_COPYRIGHT)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // This is text that goes after " [options]" in help output. -[assembly: Mono.UsageComplement("<.fdp project file>")] +[assembly: Mono.UsageComplement("<.fd project file>")] // Attributes visible in " -V" [assembly: Mono.About("")] -[assembly: Mono.Author("FlashDevelop.org")] +[assembly: Mono.Author(PluginCore.DistroConfig.DISTRIBUTION_COMPANY)] // Version information for an assembly consists of the following four values: // diff --git a/External/Tools/FDBuild/Building/AS2/AS2ProjectBuilder.cs b/External/Tools/FDBuild/Building/AS2/AS2ProjectBuilder.cs index 7067b64c55..aa7b9e4c0f 100644 --- a/External/Tools/FDBuild/Building/AS2/AS2ProjectBuilder.cs +++ b/External/Tools/FDBuild/Building/AS2/AS2ProjectBuilder.cs @@ -1,126 +1,128 @@ using System; using System.IO; -using System.Text; -using System.Diagnostics; using ProjectManager.Projects; using ProjectManager.Projects.AS2; using FDBuild.Building; +using PluginCore.Helpers; namespace ProjectManager.Building.AS2 { - public class AS2ProjectBuilder : ProjectBuilder - { - AS2Project project; - - #region Path Helpers - string MtascPath - { - get - { + public class AS2ProjectBuilder : ProjectBuilder + { + readonly AS2Project project; + + #region Path Helpers + string MtascPath + { + get + { // path given in arguments if (CompilerPath != null) { if (File.Exists(CompilerPath)) return CompilerPath; - if (File.Exists(Path.Combine(CompilerPath, "mtasc.exe"))) + if (PlatformHelper.IsRunningOnWindows() && File.Exists(Path.Combine(CompilerPath, "mtasc.exe"))) return Path.Combine(CompilerPath, "mtasc.exe"); + if (!PlatformHelper.IsRunningOnWindows() && File.Exists(Path.Combine(CompilerPath, "mtasc"))) + return Path.Combine(CompilerPath, "mtasc"); } - // assume that mtasc.exe is probably in a directory alongside fdbuild + // assume that mtasc.exe is probably in a directory alongside fdbuild string upDirectory = Path.GetDirectoryName(FDBuildDirectory); - string mtascDir = Path.Combine(upDirectory, "mtasc"); - string mtascPath = Path.Combine(mtascDir, "mtasc.exe"); - - if (File.Exists(mtascPath)) - return mtascPath; - else - return "mtasc.exe"; // hope you have it in your environment path! - } - } - #endregion + string mtascDir = Path.Combine(upDirectory, "mtasc"); + if (PlatformHelper.IsRunningOnWindows() && File.Exists(Path.Combine(mtascDir, "mtasc.exe"))) + return Path.Combine(mtascDir, "mtasc.exe"); + if (!PlatformHelper.IsRunningOnWindows() && File.Exists(Path.Combine(mtascDir, "mtasc"))) + return Path.Combine(mtascDir, "mtasc"); + + // hope you have it in your environment path! + return "mtasc"; + } + } + #endregion public AS2ProjectBuilder(AS2Project project, string compilerPath) : base(project, compilerPath) - { - this.project = project; - } + { + this.project = project; + } - protected override void DoBuild(string[] extraClasspaths, bool noTrace) - { - Environment.CurrentDirectory = project.Directory; + protected override void DoBuild(string[] extraClasspaths, bool noTrace) + { + Environment.CurrentDirectory = project.Directory; string outputDir = Path.GetDirectoryName(project.OutputPathAbsolute); if (!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir); SwfmillLibraryBuilder libraryBuilder = new SwfmillLibraryBuilder(); - // before doing anything else, make sure any resources marked as "keep updated" - // are properly kept up to date if possible + // before doing anything else, make sure any resources marked as "keep updated" + // are properly kept up to date if possible libraryBuilder.KeepUpdated(project); // if we have any resources, build our library file and run swfmill on it libraryBuilder.BuildLibrarySwf(project, project.CompilerOptions.Verbose); - // do we have anything to compile? - if (project.CompileTargets.Count > 0 || - project.CompilerOptions.IncludePackages.Length > 0) - { - MtascArgumentBuilder mtasc = new MtascArgumentBuilder(project); - mtasc.AddCompileTargets(); - mtasc.AddOutput(); - mtasc.AddClassPaths(extraClasspaths); - mtasc.AddOptions(noTrace); - - if (project.UsesInjection) - { - mtasc.AddInput(); - } - else - { + // do we have anything to compile? + if (project.CompileTargets.Count > 0 || + project.CompilerOptions.IncludePackages.Length > 0) + { + MtascArgumentBuilder mtasc = new MtascArgumentBuilder(project); + mtasc.AddCompileTargets(); + mtasc.AddOutput(); + mtasc.AddClassPaths(extraClasspaths); + mtasc.AddOptions(noTrace); + + if (project.UsesInjection) + { + mtasc.AddInput(); + } + else + { mtasc.AddFrame(libraryBuilder.Frame); - if (project.LibraryAssets.Count == 0) - mtasc.AddHeader(); // mtasc will have to generate its own output SWF - else - mtasc.AddKeep(); // keep everything you added with swfmill - } - - string mtascArgs = mtasc.ToString(); - - if (project.CompilerOptions.Verbose) - Console.WriteLine("mtasc " + mtascArgs); - - if (!ProcessRunner.Run(MtascPath, mtascArgs, false, false)) - throw new BuildException("Build halted with errors (mtasc)."); - } - } - - private void KeepUpdated() - { - foreach (LibraryAsset asset in project.LibraryAssets) - if (asset.UpdatePath != null) - { - string assetName = Path.GetFileName(asset.Path); - string assetPath = project.GetAbsolutePath(asset.Path); - string updatePath = project.GetAbsolutePath(asset.UpdatePath); - if (File.Exists(updatePath)) - { - // check size/modified - FileInfo source = new FileInfo(updatePath); - FileInfo dest = new FileInfo(assetPath); - - if (source.LastWriteTime != dest.LastWriteTime || - source.Length != dest.Length) - { - Console.WriteLine("Updating asset '" + assetName + "'"); - File.Copy(updatePath,assetPath,true); - } - } - else - { - Console.Error.WriteLine("Warning: asset '"+assetName+"' could " - + " not be updated, as the source file could does not exist."); - } - } - } - } + if (project.LibraryAssets.Count == 0) + mtasc.AddHeader(); // mtasc will have to generate its own output SWF + else + mtasc.AddKeep(); // keep everything you added with swfmill + } + + string mtascArgs = mtasc.ToString(); + + if (project.CompilerOptions.Verbose) + Console.WriteLine("mtasc " + mtascArgs); + + if (!ProcessRunner.Run(MtascPath, mtascArgs, false, false)) + throw new BuildException("Build halted with errors (mtasc)."); + } + } + + private void KeepUpdated() + { + foreach (LibraryAsset asset in project.LibraryAssets) + if (asset.UpdatePath != null) + { + string assetName = Path.GetFileName(asset.Path); + string assetPath = project.GetAbsolutePath(asset.Path); + string updatePath = project.GetAbsolutePath(asset.UpdatePath); + if (File.Exists(updatePath)) + { + // check size/modified + FileInfo source = new FileInfo(updatePath); + FileInfo dest = new FileInfo(assetPath); + + if (source.LastWriteTime != dest.LastWriteTime || + source.Length != dest.Length) + { + Console.WriteLine("Updating asset '" + assetName + "'"); + File.Copy(updatePath,assetPath,true); + } + } + else + { + Console.Error.WriteLine("Warning: asset '"+assetName+"' could " + + " not be updated, as the source file could does not exist."); + } + } + } + } } diff --git a/External/Tools/FDBuild/Building/AS2/MtascArgumentBuilder.cs b/External/Tools/FDBuild/Building/AS2/MtascArgumentBuilder.cs index 68ba9a16ae..00e1bdd0b2 100644 --- a/External/Tools/FDBuild/Building/AS2/MtascArgumentBuilder.cs +++ b/External/Tools/FDBuild/Building/AS2/MtascArgumentBuilder.cs @@ -1,169 +1,159 @@ using System; using System.IO; -using System.Text; -using System.Collections; +using System.Linq; using ProjectManager.Projects.AS2; namespace ProjectManager.Building.AS2 { - class MtascArgumentBuilder : ArgumentBuilder - { - AS2Project project; + class MtascArgumentBuilder : ArgumentBuilder + { + readonly AS2Project project; public MtascArgumentBuilder(AS2Project project) - { - this.project = project; - } - - public void AddClassPaths(params string[] extraClassPaths) - { - // build classpaths - ArrayList classPaths = new ArrayList(project.AbsoluteClasspaths); - - foreach (string extraClassPath in extraClassPaths) - classPaths.Add(extraClassPath); - - foreach (string classPath in classPaths) - if (Directory.Exists(classPath)) Add("-cp", "\"" + classPath + "\""); // surround with quotes - } - - public void AddHeader() - { - string htmlColor = project.MovieOptions.Background.Substring(1); - - if (htmlColor.Length > 0) - htmlColor = ":" + htmlColor; - - Add("-header", string.Format("{0}:{1}:{2}{3}", - project.MovieOptions.Width, - project.MovieOptions.Height, - project.MovieOptions.Fps, - htmlColor)); - } - - public void AddCompileTargets() - { - // add project files marked as "always compile" - foreach (string target in project.CompileTargets) - { - // TODO: this is a crappy workaround for the general problem of - // project "cruft" accumulating. This will be removed once - // I add support in the treeview for displaying "missing" project items - if (File.Exists(target)) - Add("\"" + target + "\""); - } - } - - public void AddInput() - { + { + this.project = project; + } + + public void AddClassPaths(params string[] extraClassPaths) + { + // build classpaths + var classPaths = project.AbsoluteClasspaths.ToList(); + classPaths.AddRange(extraClassPaths); + foreach (string classPath in classPaths) + if (Directory.Exists(classPath)) Add("-cp", "\"" + classPath + "\""); // surround with quotes + } + + public void AddHeader() + { + string htmlColor = project.MovieOptions.Background.Substring(1); + + if (htmlColor.Length > 0) + htmlColor = ":" + htmlColor; + + Add("-header", + $"{project.MovieOptions.Width}:{project.MovieOptions.Height}:{project.MovieOptions.Fps}{htmlColor}"); + } + + public void AddCompileTargets() + { + // add project files marked as "always compile" + foreach (string target in project.CompileTargets) + { + // TODO: this is a crappy workaround for the general problem of + // project "cruft" accumulating. This will be removed once + // I add support in the treeview for displaying "missing" project items + if (File.Exists(target)) + Add("\"" + target + "\""); + } + } + + public void AddInput() + { string path = project.FixDebugReleasePath(project.GetAbsolutePath(project.InputPath)); Add("-swf", "\"" + path + "\""); - } + } - public void AddOutput() - { + public void AddOutput() + { string path = project.FixDebugReleasePath(project.OutputPathAbsolute); if (project.UsesInjection) - Add("-out", "\"" + path + "\""); - else + Add("-out", "\"" + path + "\""); + else Add("-swf", "\"" + path + "\""); - } - - public void AddFrame(int frame) - { - Add("-frame",frame.ToString()); - } - - public void AddKeep() - { - // always keep existing source - if you add .swf files to the library, expected - // behavior is to add *everything* in them. - Add("-keep"); - } - - public void AddOptions(bool noTrace) - { + } + + public void AddFrame(int frame) => Add("-frame",frame.ToString()); + + public void AddKeep() + { + // always keep existing source - if you add .swf files to the library, expected + // behavior is to add *everything* in them. + Add("-keep"); + } + + public void AddOptions(bool noTrace) + { Add("-version", Math.Max(Math.Min(project.MovieOptions.MajorVersion, 8), 6).ToString()); - - if (project.CompilerOptions.UseMX) - Add("-mx"); - - if (project.CompilerOptions.Infer) - Add("-infer"); + + if (project.CompilerOptions.UseMX) + Add("-mx"); + + if (project.CompilerOptions.Infer) + Add("-infer"); - if (project.CompilerOptions.Strict) - Add("-strict"); + if (project.CompilerOptions.Strict) + Add("-strict"); - if (project.CompilerOptions.UseMain) - Add("-main"); + if (project.CompilerOptions.UseMain) + Add("-main"); - if (project.CompilerOptions.Verbose) - Add("-v"); + if (project.CompilerOptions.Verbose) + Add("-v"); - if (project.CompilerOptions.WarnUnusedImports) - Add("-wimp"); + if (project.CompilerOptions.WarnUnusedImports) + Add("-wimp"); - if (project.CompilerOptions.ExcludeFile.Length > 0) - Add("-exclude","\""+project.CompilerOptions.ExcludeFile+"\""); + if (project.CompilerOptions.ExcludeFile.Length > 0) + Add("-exclude","\""+project.CompilerOptions.ExcludeFile+"\""); - if (project.CompilerOptions.GroupClasses) - Add("-group"); + if (project.CompilerOptions.GroupClasses) + Add("-group"); - if (project.UsesInjection) - { - Add("-frame",project.CompilerOptions.Frame.ToString()); + if (project.UsesInjection) + { + Add("-frame",project.CompilerOptions.Frame.ToString()); - if (project.CompilerOptions.Keep) - Add("-keep"); - } + if (project.CompilerOptions.Keep) + Add("-keep"); + } - // add project directories marked as "always compile" - foreach (string target in project.CompileTargets) - if (Directory.Exists(target)) - { + // add project directories marked as "always compile" + foreach (string target in project.CompileTargets) + if (Directory.Exists(target)) + { string cp = project.Classpaths.GetClosestParent(target); - if (cp == null) + if (cp is null) throw new Exception("Could not determine the closest classpath off which to compile the directory '" + target + "'."); string relTarget = (cp == ".") ? target : target.Substring(cp.Length + 1); Add("-pack","\"" + relTarget + "\""); - } - - foreach (string pack in project.CompilerOptions.IncludePackages) - if (pack.Trim().Length > 0) Add("-pack", pack); - - if (noTrace) - { - Add("-trace no"); - return; - } - - switch (project.CompilerOptions.TraceMode) - { - case TraceMode.Disable: - Add("-trace no"); - break; - case TraceMode.FlashViewer: - Add("-trace org.flashdevelop.utils.FlashViewer.trace"); - Add("org/flashdevelop/utils/FlashViewer.as"); - break; + } + + foreach (string pack in project.CompilerOptions.IncludePackages) + if (pack.Trim().Length > 0) Add("-pack", pack); + + if (noTrace) + { + Add("-trace no"); + return; + } + + switch (project.CompilerOptions.TraceMode) + { + case TraceMode.Disable: + Add("-trace no"); + break; + case TraceMode.FlashViewer: + Add("-trace org.flashdevelop.utils.FlashViewer.trace"); + Add("org/flashdevelop/utils/FlashViewer.as"); + break; case TraceMode.FlashViewerExtended: Add("-trace org.flashdevelop.utils.FlashViewer.mtrace"); Add("org/flashdevelop/utils/FlashViewer.as"); break; - case TraceMode.FlashConnect: - Add("-trace org.flashdevelop.utils.FlashConnect.trace"); - Add("org/flashdevelop/utils/FlashConnect.as"); - break; - case TraceMode.FlashConnectExtended: - Add("-trace org.flashdevelop.utils.FlashConnect.mtrace"); - Add("org/flashdevelop/utils/FlashConnect.as"); - break; - case TraceMode.CustomFunction: - Add("-trace", project.CompilerOptions.TraceFunction); - break; - } - } - } + case TraceMode.FlashConnect: + Add("-trace org.flashdevelop.utils.FlashConnect.trace"); + Add("org/flashdevelop/utils/FlashConnect.as"); + break; + case TraceMode.FlashConnectExtended: + Add("-trace org.flashdevelop.utils.FlashConnect.mtrace"); + Add("org/flashdevelop/utils/FlashConnect.as"); + break; + case TraceMode.CustomFunction: + Add("-trace", project.CompilerOptions.TraceFunction); + break; + } + } + } } diff --git a/External/Tools/FDBuild/Building/AS3/AS3ProjectBuilder.cs b/External/Tools/FDBuild/Building/AS3/AS3ProjectBuilder.cs index b0d02ef47b..865ae79278 100644 --- a/External/Tools/FDBuild/Building/AS3/AS3ProjectBuilder.cs +++ b/External/Tools/FDBuild/Building/AS3/AS3ProjectBuilder.cs @@ -1,12 +1,9 @@ using System; using System.Collections.Generic; -using System.Runtime.Remoting.Channels.Ipc; -using System.Text; using ProjectManager.Projects.AS3; using ProjectManager.Helpers; using System.IO; using FDBuild.Building.AS3; -using System.Collections; using PluginCore.Helpers; using ProjectManager.Projects; using System.Text.RegularExpressions; @@ -16,31 +13,31 @@ namespace ProjectManager.Building.AS3 { public class AS3ProjectBuilder : ProjectBuilder { - AS3Project project; - FlexCompilerShell fcsh; + readonly AS3Project project; + readonly FlexCompilerShell fcsh; string VMARGS = "-Xmx384m -Xmx1024m -Dsun.io.useCanonCaches=false -Duser.language=en"; string sdkPath; string mxmlcPath; string asc2Path; string fcshPath; string ascshPath; - bool asc2Mode; + readonly bool asc2Mode; Dictionary jvmConfig; public AS3ProjectBuilder(AS3Project project, string compilerPath, string ipcName) : base(project, compilerPath) { this.project = project; - + DetectFlexSdk(compilerPath); bool mxmlcExists = File.Exists(mxmlcPath); bool fcshExists = File.Exists(fcshPath); bool ascshExists = File.Exists(ascshPath); bool asc2Exixts = File.Exists(asc2Path); - asc2Mode = ascshExists || (asc2Exixts && !fcshExists); + asc2Mode = !fcshExists && (ascshExists || asc2Exixts); - bool hostedInFD = (fcshExists || ascshExists) && ipcName != null && ipcName != ""; + bool hostedInFD = (fcshExists || ascshExists) && !string.IsNullOrEmpty(ipcName); if (hostedInFD) { @@ -51,7 +48,7 @@ public AS3ProjectBuilder(AS3Project project, string compilerPath, string ipcName if (project.OutputType == OutputType.Application || project.OutputType == OutputType.Library) { if (fcsh != null && !fcshExists && !ascshExists) throw new Exception("Could not locate lib\\fcsh.jar or lib\\ascsh.jar in Flex SDK."); - if (fcsh == null && !mxmlcExists && !asc2Mode) + if (fcsh is null && !mxmlcExists && !asc2Mode) throw new Exception("Could not locate lib\\mxmlc.jar or lib\\mxmlc-cli.jar in Flex SDK."); } } @@ -62,36 +59,61 @@ private void DetectFlexSdk(string flexsdkPath) { flexsdkPath = ResolveFlexSdk(flexsdkPath); if (Path.GetFileName(flexsdkPath) == "bin") - flexsdkPath = Path.GetDirectoryName(flexsdkPath); + flexsdkPath = Path.GetDirectoryName(flexsdkPath); sdkPath = flexsdkPath; - mxmlcPath = Path.Combine(Path.Combine(flexsdkPath, "lib"), "mxmlc.jar"); - fcshPath = Path.Combine(Path.Combine(flexsdkPath, "lib"), "fcsh.jar"); - asc2Path = Path.Combine(Path.Combine(flexsdkPath, "lib"), "mxmlc-cli.jar"); - if (!File.Exists(asc2Path)) ascshPath = null; + string libPath = Path.Combine(flexsdkPath, "lib"); + mxmlcPath = Path.Combine(libPath, "mxmlc.jar"); + fcshPath = Path.Combine(libPath, "fcsh.jar"); + asc2Path = Path.Combine(libPath, "mxmlc-cli.jar"); + if (File.Exists(mxmlcPath) || File.Exists(fcshPath) || !File.Exists(asc2Path)) + { + // priority to FCSH + ascshPath = null; + } else { - ascshPath = Path.Combine(Path.Combine(flexsdkPath, "lib"), "ascsh.jar"); - if (!File.Exists(ascshPath)) + ascshPath = Path.Combine(libPath, "ascsh.jar"); + string toolsDir = Path.GetDirectoryName(FDBuildDirectory); + string lib = Path.Combine(toolsDir, "flexlibs/lib/ascsh.jar"); + if (ShouldCopyASCSH(lib, ascshPath)) { // try copying the missing JAR in the SDK - string toolsDir = Path.GetDirectoryName(FDBuildDirectory); - string lib = Path.Combine(toolsDir, "flexlibs/lib/ascsh.jar"); try { File.Copy(lib, ascshPath); Console.WriteLine("Copied 'ascsch.jar' in the AIR SDK for incremental ASC2 compilation."); } - catch + catch { ascshPath = null; } } } - jvmConfig = PluginCore.Helpers.JvmConfigHelper.ReadConfig(flexsdkPath); - if (jvmConfig.ContainsKey("java.args") && jvmConfig["java.args"].Trim().Length > 0) - VMARGS = jvmConfig["java.args"]; + jvmConfig = JvmConfigHelper.ReadConfig(flexsdkPath); + if (jvmConfig.TryGetValue("java.args", out var args) && args.Trim().Length > 0) + VMARGS = args; + } + + private bool ShouldCopyASCSH(string lib, string ascsh) + { + if (File.Exists(ascsh + ".disabled")) return false; + if (!File.Exists(ascsh)) return true; + // should the JAR be upgraded? + FileInfo infoFrom = new FileInfo(lib); + FileInfo infoTo = new FileInfo(ascsh); + if (infoFrom.LastWriteTime > infoTo.LastWriteTime) + { + try + { + Console.WriteLine("Found 'ascsh.jar' but it looks obsolete."); + File.Delete(ascsh); + return true; + } + catch { } + } + return false; } private string ResolveFlexSdk(string flexsdkPath) @@ -108,18 +130,13 @@ private string ResolveFlexSdk(string flexsdkPath) // when path is not provided in program arguments. string toolsDir = Path.GetDirectoryName(FDBuildDirectory); string firstRunDir = Path.GetDirectoryName(toolsDir); - string dataDir = Path.Combine(firstRunDir, "Data"); - string pmDir = Path.Combine(dataDir, "ProjectManager"); - string fdbuildHints = Path.Combine(pmDir, "FDBuildHints.txt"); + string fdbuildHints = Path.Combine(firstRunDir, "Data", "ProjectManager", "FDBuildHints.txt"); if (File.Exists(fdbuildHints)) { - using (StreamReader reader = File.OpenText(fdbuildHints)) - { - flexsdkPath = reader.ReadLine(); - } - if (!Directory.Exists(flexsdkPath)) - Console.WriteLine("Compiler path configured in FDBuildHints.txt doesn't exist:\n" + flexsdkPath); + using var reader = File.OpenText(fdbuildHints); + flexsdkPath = reader.ReadLine(); + if (!Directory.Exists(flexsdkPath)) Console.WriteLine("Compiler path configured in FDBuildHints.txt doesn't exist:\n" + flexsdkPath); else { Console.WriteLine("Using compiler defined in FDBuildHints.txt"); @@ -128,7 +145,7 @@ private string ResolveFlexSdk(string flexsdkPath) } string envPath = Environment.ExpandEnvironmentVariables("%FLEX_HOME%"); - if (!envPath.StartsWith("%")) + if (!envPath.StartsWith("%", StringComparison.Ordinal)) { if (!Directory.Exists(envPath)) Console.WriteLine("Environment path %FLEX_HOME% doesn't exist:\n" + envPath); @@ -150,7 +167,7 @@ protected override void DoBuild(string[] extraClasspaths, bool noTrace) Environment.CurrentDirectory = project.Directory; try { - string objDir = "obj"; + const string objDir = "obj"; if (!Directory.Exists(objDir)) Directory.CreateDirectory(objDir); tempFile = GetTempProjectFile(project); @@ -175,9 +192,7 @@ protected override void DoBuild(string[] extraClasspaths, bool noTrace) bool configChanged = !File.Exists(backupConfig) || !File.Exists(configFile) || !FileComparer.IsEqual(configFileTmp, configFile); //copy temp file to config if there is a change - if (configChanged){ - File.Copy(configFileTmp, configFile, true); - } + if (configChanged) File.Copy(configFileTmp, configFile, true); //remove temp File.Delete(configFileTmp); @@ -197,7 +212,7 @@ protected override void DoBuild(string[] extraClasspaths, bool noTrace) } else Console.WriteLine("mxmlc " + mxmlcArgs); - CompileWithMxmlc(project.Directory, mxmlcArgs, configChanged); + CompileWithMxmlc(project.Directory, mxmlcArgs); // if we get here, the build was successful string output = project.FixDebugReleasePath(project.OutputPathAbsolute); @@ -205,7 +220,10 @@ protected override void DoBuild(string[] extraClasspaths, bool noTrace) if (!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir); File.Copy(tempFile, output, true); } - finally { if (tempFile != null && File.Exists(tempFile)) File.Delete(tempFile); } + finally + { + if (File.Exists(tempFile)) File.Delete(tempFile); + } } private string AddBaseConfig(string args) @@ -219,35 +237,30 @@ private string AddBaseConfig(string args) return args; } - static public double ParseVersion(string version) + public static double ParseVersion(string version) { string[] p = version.Split('.'); if (p.Length == 0) return 0; - double major = 0; - double.TryParse(p[0], out major); + double.TryParse(p[0], out var major); if (p.Length == 1) return major; - double minor = 0; - double.TryParse(p[1], out minor); + double.TryParse(p[1], out var minor); return major + (minor < 10 ? minor / 10 : minor / 100); } - public void CompileWithMxmlc(string workingdir, string arguments, bool configChanged) + public void CompileWithMxmlc(string workingdir, string arguments) { if (fcsh != null) { - string output; - string[] errors; - string[] warnings; - string jar = ascshPath != null ? ascshPath : fcshPath; + string jar = ascshPath ?? fcshPath; string jvmarg = VMARGS + " -Dapplication.home=\"" + sdkPath - + "\" -Dflexlib=\"" + Path.Combine(sdkPath, "frameworks") + //+ "\" -Dflexlib=\"" + Path.Combine(sdkPath, "frameworks") + "\" -jar \"" + jar + "\""; - fcsh.Compile(workingdir, configChanged, arguments, out output, out errors, out warnings, jvmarg, JvmConfigHelper.GetJavaEXE(jvmConfig, sdkPath)); + fcsh.Compile(workingdir, arguments, out var output, out var errors, out var warnings, jvmarg, JvmConfigHelper.GetJavaEXE(jvmConfig, sdkPath)); string[] lines = output.Split('\n'); foreach (string line in lines) { - if (!line.StartsWith("Recompile:") && !line.StartsWith("Reason:")) + if (!line.StartsWith("Recompile:", StringComparison.Ordinal) && !line.StartsWith("Reason:", StringComparison.Ordinal)) Console.Write(line); } foreach (string warning in warnings) @@ -273,7 +286,7 @@ public void CompileWithMxmlc(string workingdir, string arguments, bool configCha // between builds. This is necessary because the arguments to the FlexCompilerShell // (if you're using it) have to be identical between builds to enable incremental compiling. //private string GetTempProjectFile(AS3Project project) - private string GetTempProjectFile(AS3Project project) + internal static string GetTempProjectFile(AS3Project project) { // this serves two purposes - randomize the filename, so two identically-named // projects don't get the same temp build target, and also provide an extra diff --git a/External/Tools/FDBuild/Building/AS3/FlexConfigWriter.cs b/External/Tools/FDBuild/Building/AS3/FlexConfigWriter.cs index 8eb3612ec3..c15b602ffb 100644 --- a/External/Tools/FDBuild/Building/AS3/FlexConfigWriter.cs +++ b/External/Tools/FDBuild/Building/AS3/FlexConfigWriter.cs @@ -1,11 +1,10 @@ using System; -using System.Collections.Generic; using System.Text; using System.Xml; using ProjectManager.Projects.AS3; using System.IO; -using System.Collections; -using ProjectManager.Projects; +using System.Linq; + namespace FDBuild.Building.AS3 { @@ -17,7 +16,7 @@ class FlexConfigWriter : XmlTextWriter public FlexConfigWriter(string libraryPath): base(libraryPath, new UTF8Encoding(false)) { - base.Formatting = Formatting.Indented; + Formatting = Formatting.Indented; } public void WriteConfig(AS3Project project, double sdkVersion, string[] extraClasspaths, bool debugMode, bool asc2Mode) @@ -48,6 +47,7 @@ private void InternalWriteConfig(string[] extraClasspaths, bool debugMode) AddCompilerOptions(options, debugMode); AddClassPaths(extraClasspaths); AddLibraries(); + AddNamespaces(options); WriteEndElement(); AddRSLs(); AddCompileTargets(); @@ -60,8 +60,8 @@ private void AddCompilerConstants(MxmlcOptions options, bool debugMode) WriteDefine("CONFIG::debug", debugMode ? "true" : "false"); WriteDefine("CONFIG::release", debugMode ? "false" : "true"); WriteDefine("CONFIG::timeStamp", "'" + DateTime.Now.ToString("d") + "'"); - var isMobile = project.MovieOptions.Platform == AS3MovieOptions.AIR_MOBILE_PLATFORM; - var isDesktop = project.MovieOptions.Platform == AS3MovieOptions.AIR_PLATFORM; + var isMobile = project.MovieOptions.Platform == "AIR Mobile"; + var isDesktop = project.MovieOptions.Platform == "AIR"; WriteDefine("CONFIG::air", isMobile || isDesktop ? "true" : "false"); WriteDefine("CONFIG::mobile", isMobile ? "true" : "false"); WriteDefine("CONFIG::desktop", isDesktop ? "true" : "false"); @@ -131,16 +131,17 @@ private void AddTargetPlayer(MxmlcOptions options) { int majorVersion = project.MovieOptions.MajorVersion; int minorVersion = project.MovieOptions.MinorVersion; - if (project.MovieOptions.Platform == AS3MovieOptions.AIR_PLATFORM - || project.MovieOptions.Platform == AS3MovieOptions.AIR_MOBILE_PLATFORM) - PluginCore.PlatformData.GuessFlashPlayerForAIR(ref majorVersion, ref minorVersion); - string version; if (options.MinorVersion.Length > 0) version = majorVersion + "." + options.MinorVersion; else version = majorVersion + "." + minorVersion; + string platform = project.MovieOptions.Platform; + if (platform != PluginCore.PlatformData.FLASHPLAYER_PLATFORM + && project.MovieOptions.HasPlatformSupport && project.MovieOptions.PlatformSupport.IsFlashPlatform) + version = PluginCore.PlatformData.ResolveFlashPlayerVersion(project.Language, platform, version); + WriteElementString("target-player", version); } @@ -194,6 +195,31 @@ private void AddLibraries() } } + private void AddNamespaces(MxmlcOptions options) + { + if (options.Namespaces is null || options.Namespaces.Length == 0) return; + + WriteStartElement("namespaces"); + + foreach (var ns in options.Namespaces) + { + string path = ns.Manifest.Trim(); + string uri = ns.Uri.Trim(); + if (path.Length == 0 || uri.Length == 0) continue; + path = project.GetAbsolutePath(path); + if (!File.Exists(path)) continue; + + WriteStartElement("namespace"); + + WriteElementString("uri", uri); + WriteElementString("manifest", path); + + WriteEndElement(); + } + + WriteEndElement(); + } + private void AddRSLs() { MxmlcOptions options = project.CompilerOptions; @@ -238,8 +264,7 @@ public void AddClassPaths(string[] extraClasspaths) WriteAttributeString("append", "true"); // build classpaths - ArrayList classPaths = new ArrayList(project.AbsoluteClasspaths); - + var classPaths = project.AbsoluteClasspaths.ToList(); foreach (string extraClassPath in extraClasspaths) if (Directory.Exists(extraClassPath)) classPaths.Add(extraClassPath); diff --git a/External/Tools/FDBuild/Building/AS3/FlexJSProjectBuilder.cs b/External/Tools/FDBuild/Building/AS3/FlexJSProjectBuilder.cs new file mode 100644 index 0000000000..b79a6363a5 --- /dev/null +++ b/External/Tools/FDBuild/Building/AS3/FlexJSProjectBuilder.cs @@ -0,0 +1,104 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using PluginCore.Helpers; +using ProjectManager.Building; +using ProjectManager.Building.AS3; +using ProjectManager.Projects.AS3; + +namespace FDBuild.Building.AS3 +{ + class FlexJSProjectBuilder : ProjectBuilder + { + readonly AS3Project project; + readonly string mxmlcPath; + readonly Dictionary jvmConfig; + readonly string jvmArgs; + + public FlexJSProjectBuilder(AS3Project project, string compilerPath) : base(project, compilerPath) + { + this.project = project; + mxmlcPath = Path.Combine(compilerPath, "js", "lib", "mxmlc.jar"); + if (!File.Exists(mxmlcPath)) throw new Exception("Could not locate js\\lib\\mxmlc.jar in FlexJS SDK."); + jvmConfig = JvmConfigHelper.ReadConfig(compilerPath); + if (jvmConfig.TryGetValue("java.args", out var args) && args.Trim().Length > 0) jvmArgs = args; + } + + protected override void DoBuild(string[] extraClassPaths, bool noTrace) + { + string tempFile = null; + Environment.CurrentDirectory = project.Directory; + try + { + const string objDir = "obj"; + if (!Directory.Exists(objDir)) Directory.CreateDirectory(objDir); + tempFile = AS3ProjectBuilder.GetTempProjectFile(project); + + //create new config file + double sdkVersion = AS3ProjectBuilder.ParseVersion(Program.BuildOptions.CompilerVersion ?? "4.0"); + + // create compiler configuration file + var projectName = project.Name.Replace(" ", ""); + var backupConfig = Path.Combine(objDir, projectName + "Config.old"); + var configFileTmp = Path.Combine(objDir, projectName + "Config.tmp"); + var configFile = Path.Combine(objDir, projectName + "Config.xml"); + + // backup the old Config.xml to Config.old so we can reference it + if (File.Exists(configFile)) File.Copy(configFile, backupConfig, true); + + //write "new" config to tmp + var config = new FlexConfigWriter(project.GetAbsolutePath(configFileTmp)); + config.WriteConfig(project, sdkVersion, extraClassPaths, !noTrace, false); + + //compare tmp to current + var configChanged = !File.Exists(backupConfig) || !File.Exists(configFile) || + !FileComparer.IsEqual(configFileTmp, configFile); + + //copy temp file to config if there is a change + if (configChanged) + { + File.Copy(configFileTmp, configFile, true); + } + + //remove temp + File.Delete(configFileTmp); + + var mxmlc = new MxmlcArgumentBuilder(project, sdkVersion, false); + mxmlc.AddConfig(configFile); + mxmlc.AddOptions(noTrace, false); + mxmlc.AddOutput(tempFile); + var mxmlcArgs = mxmlc.ToString(); + Console.WriteLine("mxmlc " + mxmlcArgs); + CompileWithMxmlc(mxmlcArgs); + + // if we get here, the build was successful + var output = project.FixDebugReleasePath(project.OutputPathAbsolute); + var outputDir = Path.GetDirectoryName(output); + if (!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir); + File.Copy(tempFile, output, true); + } + finally + { + if (File.Exists(tempFile)) File.Delete(tempFile); + } + } + + void CompileWithMxmlc(string mxmlcArgs) + { + var javaExe = JvmConfigHelper.GetJavaEXE(jvmConfig, CompilerPath); + Console.WriteLine("Running java as: " + javaExe); + var frameworks = Path.Combine(CompilerPath, "frameworks"); + var args = $"-Dflexcompiler=\"{CompilerPath}\" -Dflexlib=\"{frameworks}\" {jvmArgs} -jar \"{mxmlcPath}\""; + args += " -js-output-type=FLEXJS"; + args += " -sdk-js-lib=\"" + Path.Combine(frameworks, "js", "FlexJS", "generated-sources") + "\" "; + var index = mxmlcArgs.LastIndexOf("-o "); + if (index != -1) mxmlcArgs = mxmlcArgs.Remove(index); + args += mxmlcArgs; + args += " -targets=SWF"; + args += " " + project.CompileTargets.First(); + args += " -output=" + project.OutputPath; + if (!ProcessRunner.Run(javaExe, args, false, false)) throw new BuildException("Build halted with errors (mxmlc)."); + } + } +} diff --git a/External/Tools/FDBuild/Building/AS3/MxmlcArgumentBuilder.cs b/External/Tools/FDBuild/Building/AS3/MxmlcArgumentBuilder.cs index 66542d23aa..b557176129 100644 --- a/External/Tools/FDBuild/Building/AS3/MxmlcArgumentBuilder.cs +++ b/External/Tools/FDBuild/Building/AS3/MxmlcArgumentBuilder.cs @@ -1,22 +1,20 @@ using System; -using System.Collections; -using System.IO; -using System.Text; using ProjectManager.Projects.AS3; -using System.Runtime.InteropServices; namespace ProjectManager.Building.AS3 { class MxmlcArgumentBuilder : ArgumentBuilder { - AS3Project project; - bool flex45; - bool asc2; + readonly AS3Project project; + readonly bool flex45; + readonly bool flex410; + readonly bool asc2; public MxmlcArgumentBuilder(AS3Project project, double sdkVersion, bool asc2Mode) { this.project = project; flex45 = sdkVersion >= 4.5; + flex410 = Math.Truncate(sdkVersion) >= 4 && (sdkVersion % 1) * 100 > 9; asc2 = asc2Mode; } @@ -41,7 +39,7 @@ public void AddOptions(bool releaseMode, bool incremental) MxmlcOptions options = project.CompilerOptions; - if (asc2 && options.AdvancedTelemetry) + if ((asc2 || flex410) && options.AdvancedTelemetry) { AddEq("-advanced-telemetry", true); if (!string.IsNullOrEmpty(options.AdvancedTelemetryPassword)) @@ -56,28 +54,25 @@ public void AddOptions(bool releaseMode, bool incremental) bool hasVersion = false; if (options.Additional != null) { - string all = String.Join(" ", options.Additional); - if (all.IndexOf("configname") > 0) hasConfig = true; - if (all.IndexOf("swf-version") > 0) hasVersion = true; + string all = string.Join(" ", options.Additional); + if (all.IndexOf("configname", StringComparison.Ordinal) > 0) hasConfig = true; + if (all.IndexOf("swf-version", StringComparison.Ordinal) > 0) hasVersion = true; } - bool isAIR = false; if (!hasConfig) { if (project.MovieOptions.Platform == "AIR") { - isAIR = true; AddEq("+configname", "air"); } else if (project.MovieOptions.Platform == "AIR Mobile") { - isAIR = true; AddEq("+configname", "airmobile"); } } if ((asc2 || flex45) && !hasVersion) { string version = project.MovieOptions.Version; - if (isAIR) version = PluginCore.PlatformData.GuessFlashPlayerForAIR(version); - string swfVersion = (project.MovieOptions as AS3MovieOptions).GetSWFVersion(version); + string platform = project.MovieOptions.Platform; + string swfVersion = PluginCore.PlatformData.ResolveSwfVersion(project.Language, platform, version); if (swfVersion != null) AddEq("-swf-version", swfVersion); } @@ -85,14 +80,8 @@ public void AddOptions(bool releaseMode, bool incremental) Add(options.Additional, releaseMode); } - void AddEq(string argument, string value) - { - Add(argument + "=" + value); - } + void AddEq(string argument, string value) => Add(argument + "=" + value); - void AddEq(string argument, bool value) - { - AddEq(argument, value ? "true" : "false"); - } + void AddEq(string argument, bool value) => AddEq(argument, value ? "true" : "false"); } } diff --git a/External/Tools/FDBuild/Building/ArgumentBuilder.cs b/External/Tools/FDBuild/Building/ArgumentBuilder.cs index 4cf2883468..bc9a6d9bda 100644 --- a/External/Tools/FDBuild/Building/ArgumentBuilder.cs +++ b/External/Tools/FDBuild/Building/ArgumentBuilder.cs @@ -1,55 +1,47 @@ using System; -using System.Collections; -using System.Text; -using ProjectManager.Projects; +using System.Collections.Generic; namespace ProjectManager.Building { - class ArgumentBuilder - { - ArrayList args; + class ArgumentBuilder + { + readonly List args; - public ArgumentBuilder() - { - args = new ArrayList(); + public ArgumentBuilder() + { + args = new List(); } public void Add(string[] arguments, bool releaseMode) { - foreach (string argument in arguments) - if (argument != null && argument.Length > 0) + foreach (var argument in arguments) + if (!string.IsNullOrEmpty(argument)) { - string line = argument.Trim(); - if (line.Length == 0) - continue; + var line = argument.Trim(); + if (line.Length == 0) continue; // conditional arguments - if (line.StartsWith("DEBUG:")) + if (line.StartsWith("DEBUG:", StringComparison.Ordinal)) { if (releaseMode) continue; - else line = line.Substring("DEBUG:".Length).Trim(); + line = line.Substring("DEBUG:".Length).Trim(); } - if (line.StartsWith("RELEASE:")) + if (line.StartsWith("RELEASE:", StringComparison.Ordinal)) { if (!releaseMode) continue; - else line = line.Substring("RELEASE:".Length).Trim(); + line = line.Substring("RELEASE:".Length).Trim(); } args.Add(line); } } - public void Add(string argument, params string[] values) - { - args.Add(argument); - foreach (string value in values) - if (value != null && value.Length > 0) args.Add(value); - } + public void Add(string argument, params string[] values) + { + args.Add(argument); + foreach (var value in values) + if (!string.IsNullOrEmpty(value)) args.Add(value); + } - public override string ToString() - { - string[] argArray = args.ToArray(typeof(string)) as string[]; - string line = string.Join(" ", argArray); - return line; - } - } -} + public override string ToString() => string.Join(" ", args); + } +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Building/BuildEventRunner.cs b/External/Tools/FDBuild/Building/BuildEventRunner.cs index e6d1b92044..66194fb103 100644 --- a/External/Tools/FDBuild/Building/BuildEventRunner.cs +++ b/External/Tools/FDBuild/Building/BuildEventRunner.cs @@ -1,39 +1,37 @@ using System; -using System.IO; -using System.Collections; using ProjectManager.Projects; namespace ProjectManager.Building { - /// - /// Processed pre and post-build steps, filling in project variables - /// - public class BuildEventRunner - { - Project project; - BuildEventVars vars; + /// + /// Processed pre and post-build steps, filling in project variables + /// + public class BuildEventRunner + { + readonly Project project; + readonly BuildEventVars vars; - public BuildEventRunner(Project project, string compilerPath) - { - this.project = project; + public BuildEventRunner(Project project, string compilerPath) + { + this.project = project; project.CurrentSDK = compilerPath; - this.vars = new BuildEventVars(project); - } + vars = new BuildEventVars(project); + } //parse line into command/argument pair - private string[] tokenize(string line) + private string[] Tokenize(string line) { - string[] result = new String[2]; + string[] result = new string[2]; - if (line.StartsWith("\"")) + if (line.StartsWith("\"", StringComparison.Ordinal)) { - int endQuote = line.IndexOf("\"", 1); + int endQuote = line.IndexOf('\"', 1); result[0] = (endQuote > -1) ? line.Substring(1, endQuote - 1) : line; result[1] = (endQuote > -1) ? line.Substring(endQuote + 1).TrimStart() : ""; } else { - int space = line.IndexOf(" "); + int space = line.IndexOf(' '); result[0] = (space > -1) ? line.Substring(0, space) : line; result[1] = (space > -1) ? line.Substring(space + 1) : ""; } @@ -44,9 +42,7 @@ private string[] tokenize(string line) public void Run(string buildEvents, bool noTrace) { string[] events = buildEvents.Split('\n'); - if (events.Length == 0) - return; - + if (events.Length == 0) return; BuildEventInfo[] infos = vars.GetVars(); foreach (string buildEvent in events) { @@ -54,19 +50,19 @@ public void Run(string buildEvents, bool noTrace) string line = buildEvent.Trim(); - if (line.Length <= 0) + if (line.Length == 0) continue; // nothing to do // conditional execution - if (line.StartsWith("DEBUG:")) + if (line.StartsWith("DEBUG:", StringComparison.Ordinal)) { if (noTrace) continue; - else line = line.Substring("DEBUG:".Length).Trim(); + line = line.Substring("DEBUG:".Length).Trim(); } - if (line.StartsWith("RELEASE:")) + if (line.StartsWith("RELEASE:", StringComparison.Ordinal)) { if (!noTrace) continue; - else line = line.Substring("RELEASE:".Length).Trim(); + line = line.Substring("RELEASE:".Length).Trim(); } // expand variables foreach (BuildEventInfo info in infos) @@ -75,7 +71,7 @@ public void Run(string buildEvents, bool noTrace) line = project.FixDebugReleasePath(line); Console.WriteLine("cmd: " + line); - string[] tokens = tokenize(line); + string[] tokens = Tokenize(line); string command = tokens[0]; string args = tokens[1]; @@ -87,13 +83,12 @@ public void Run(string buildEvents, bool noTrace) break; case "RunMxmlc": - string[] mxmlctokens = tokenize(args); + string[] mxmlctokens = Tokenize(args); FDBuild.Program.BuildMXMLC(mxmlctokens[0], mxmlctokens[1]); break; - case "RunCompc": - string[] compctokens = tokenize(args); - FDBuild.Program.BuildCOMPC(compctokens[0], compctokens[1]); + case "RunCompc": + FDBuild.Program.BuildCOMPC(); break; default: @@ -103,5 +98,5 @@ public void Run(string buildEvents, bool noTrace) } } } - } + } } diff --git a/External/Tools/FDBuild/Building/BuildException.cs b/External/Tools/FDBuild/Building/BuildException.cs index 3fe8120866..ab3b80abda 100644 --- a/External/Tools/FDBuild/Building/BuildException.cs +++ b/External/Tools/FDBuild/Building/BuildException.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace ProjectManager.Building { diff --git a/External/Tools/FDBuild/Building/FileComparer.cs b/External/Tools/FDBuild/Building/FileComparer.cs index 6e977f5c0c..cd84217a3b 100644 --- a/External/Tools/FDBuild/Building/FileComparer.cs +++ b/External/Tools/FDBuild/Building/FileComparer.cs @@ -1,65 +1,61 @@ -using System; using System.IO; -using System.Text; namespace ProjectManager.Building { - // from: http://support.microsoft.com/default.aspx?scid=kb;EN-US;320348 - class FileComparer - { - // This method accepts two strings the represent two files to - // compare. A return value of 0 indicates that the contents of the files - // are the same. A return value of any other value indicates that the - // files are not the same. - public static bool IsEqual(string file1, string file2) - { - int file1byte; - int file2byte; - FileStream fs1; - FileStream fs2; - - // Determine if the same file was referenced two times. - if (file1 == file2) - { - // Return true to indicate that the files are the same. - return true; - } - - // Open the two files. - fs1 = new FileStream(file1, FileMode.Open); - fs2 = new FileStream(file2, FileMode.Open); - - // Check the file sizes. If they are not the same, the files - // are not the same. - if (fs1.Length != fs2.Length) - { - // Close the file - fs1.Close(); - fs2.Close(); - - // Return false to indicate files are different - return false; - } - - // Read and compare a byte from each file until either a - // non-matching set of bytes is found or until the end of - // file1 is reached. - do - { - // Read one byte from each file. - file1byte = fs1.ReadByte(); - file2byte = fs2.ReadByte(); - } - while ((file1byte == file2byte) && (file1byte != -1)); - - // Close the files. - fs1.Close(); - fs2.Close(); - - // Return the success of the comparison. "file1byte" is - // equal to "file2byte" at this point only if the files are - // the same. - return ((file1byte - file2byte) == 0); - } - } -} + // from: http://support.microsoft.com/default.aspx?scid=kb;EN-US;320348 + class FileComparer + { + // This method accepts two strings the represent two files to + // compare. A return value of 0 indicates that the contents of the files + // are the same. A return value of any other value indicates that the + // files are not the same. + public static bool IsEqual(string file1, string file2) + { + + // Determine if the same file was referenced two times. + if (file1 == file2) + { + // Return true to indicate that the files are the same. + return true; + } + + // Open the two files. + var fs1 = new FileStream(file1, FileMode.Open); + var fs2 = new FileStream(file2, FileMode.Open); + + // Check the file sizes. If they are not the same, the files + // are not the same. + if (fs1.Length != fs2.Length) + { + // Close the file + fs1.Close(); + fs2.Close(); + + // Return false to indicate files are different + return false; + } + + int file1byte; + int file2byte; + // Read and compare a byte from each file until either a + // non-matching set of bytes is found or until the end of + // file1 is reached. + do + { + // Read one byte from each file. + file1byte = fs1.ReadByte(); + file2byte = fs2.ReadByte(); + } + while (file1byte == file2byte && file1byte != -1); + + // Close the files. + fs1.Close(); + fs2.Close(); + + // Return the success of the comparison. "file1byte" is + // equal to "file2byte" at this point only if the files are + // the same. + return file1byte - file2byte == 0; + } + } +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Building/Generic/GenericProjectBuilder.cs b/External/Tools/FDBuild/Building/Generic/GenericProjectBuilder.cs index a7536de4b7..28f8743874 100644 --- a/External/Tools/FDBuild/Building/Generic/GenericProjectBuilder.cs +++ b/External/Tools/FDBuild/Building/Generic/GenericProjectBuilder.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using FDBuild.Building; -using ProjectManager.Projects.Generic; +using ProjectManager.Projects.Generic; namespace ProjectManager.Building.Generic { diff --git a/External/Tools/FDBuild/Building/Haxe/HaxeProjectBuilder.cs b/External/Tools/FDBuild/Building/Haxe/HaxeProjectBuilder.cs index d8733c672c..b37ce7872e 100644 --- a/External/Tools/FDBuild/Building/Haxe/HaxeProjectBuilder.cs +++ b/External/Tools/FDBuild/Building/Haxe/HaxeProjectBuilder.cs @@ -1,8 +1,5 @@ using System; using System.IO; -using System.Collections.Generic; -using System.Text; -using ProjectManager.Helpers; using ProjectManager.Projects.Haxe; using FDBuild.Building; @@ -10,9 +7,9 @@ namespace ProjectManager.Building.Haxe { public class HaxeProjectBuilder : ProjectBuilder { - HaxeProject project; + readonly HaxeProject project; - string haxePath; + readonly string haxePath; public HaxeProjectBuilder(HaxeProject project, string compilerPath) : base(project, compilerPath) @@ -34,23 +31,12 @@ protected override void DoBuild(string[] extraClasspaths, bool noTrace) if (!Directory.Exists(outputDir)) Directory.CreateDirectory(outputDir); string serverPort = Environment.ExpandEnvironmentVariables("%HAXE_SERVER_PORT%"); - string connect = (!serverPort.StartsWith("%") && serverPort != "0") + string connect = (!serverPort.StartsWith("%", StringComparison.Ordinal) && serverPort != "0") ? "--connect " + serverPort : ""; - if (project.IsNmeOutput && !string.IsNullOrEmpty(project.TargetBuild)) - { - haxePath = haxePath.Replace("haxe.exe", "haxelib.exe"); - string config = project.TargetBuild; - string haxeNmeArgs = String.Join(" ", BuildNmeCommand(extraClasspaths, output, config, noTrace, null));// +" " + connect; - Console.WriteLine("haxelib " + haxeNmeArgs); - if (!ProcessRunner.Run(haxePath, haxeNmeArgs, false, false)) - throw new BuildException("Build halted with errors (haxelib.exe)."); - return; - } - // always use relative path for CPP (because it prepends ./) - if (project.IsCppOutput) - output = project.FixDebugReleasePath(project.OutputPath); + //if (project.IsCppOutput) + // output = project.FixDebugReleasePath(project.OutputPath); if (project.IsFlashOutput) { @@ -63,8 +49,8 @@ protected override void DoBuild(string[] extraClasspaths, bool noTrace) // if we have any resources, build our library file and run swfmill on it libraryBuilder.BuildLibrarySwf(project, false); } - - string haxeArgs = connect + " " + String.Join(" ", project.BuildHXML(extraClasspaths, output, noTrace)); + output = output.TrimEnd('\\', '/'); + string haxeArgs = connect + " " + string.Join(" ", project.BuildHXML(extraClasspaths, output, noTrace)); Console.WriteLine("haxe " + haxeArgs); @@ -72,12 +58,12 @@ protected override void DoBuild(string[] extraClasspaths, bool noTrace) throw new BuildException("Build halted with errors (haxe.exe)."); } - private string[] BuildNmeCommand(string[] extraClasspaths, string output, string target, bool noTrace, string extraArgs) + /*private string[] BuildNmeCommand(string[] extraClasspaths, string output, string target, bool noTrace, string extraArgs) { List pr = new List(); string builder = HaxeProject.GetBuilder(output); - if (builder == null) builder = "openfl"; + if (builder is null) builder = "openfl"; pr.Add("run " + builder + " build"); pr.Add(Quote(output)); @@ -90,13 +76,6 @@ private string[] BuildNmeCommand(string[] extraClasspaths, string output, string if (extraArgs != null) pr.Add(extraArgs); return pr.ToArray(); - } - - string Quote(string s) - { - if (s.IndexOf(" ") >= 0) - return "\"" + s + "\""; - return s; - } + }*/ } } diff --git a/External/Tools/FDBuild/Building/ProcessRunner.cs b/External/Tools/FDBuild/Building/ProcessRunner.cs index 92721aa82d..5332928193 100644 --- a/External/Tools/FDBuild/Building/ProcessRunner.cs +++ b/External/Tools/FDBuild/Building/ProcessRunner.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.IO; using System.Diagnostics; using System.Threading; @@ -8,77 +7,79 @@ namespace ProjectManager.Building { - public class ProcessRunner - { - public static bool Run(string fileName, string arguments, bool ignoreExitCode, bool mergeErrors) - { - //if (!File.Exists(fileName)) - // throw new FileNotFoundException("The program '"+fileName+"' was not found.",fileName); + public class ProcessRunner + { + public static bool Run(string fileName, string arguments, bool ignoreExitCode, bool mergeErrors) + { + // CrossOver native call + bool isNative = fileName == "FDEXE.sh" || Path.GetExtension(fileName) == ".command"; - Process process = new Process(); + Process process = new Process(); process.StartInfo.UseShellExecute = false; - process.StartInfo.RedirectStandardOutput = true; - process.StartInfo.RedirectStandardError = true; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.RedirectStandardError = true; process.StartInfo.StandardOutputEncoding = Encoding.Default; process.StartInfo.StandardErrorEncoding = Encoding.Default; process.StartInfo.CreateNoWindow = true; - process.StartInfo.FileName = Environment.ExpandEnvironmentVariables(fileName); - process.StartInfo.Arguments = Environment.ExpandEnvironmentVariables(arguments); - process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; - process.Start(); + process.StartInfo.FileName = Environment.ExpandEnvironmentVariables(fileName); + process.StartInfo.Arguments = Environment.ExpandEnvironmentVariables(arguments); + process.StartInfo.WorkingDirectory = Environment.CurrentDirectory; + process.Start(); + + // capture output in a separate thread + LineFilter stdoutFilter = new LineFilter(process.StandardOutput, Console.Out, false); + LineFilter stderrFilter = new LineFilter(process.StandardError, Console.Error, mergeErrors); - // capture output in a separate thread - LineFilter stdoutFilter = new LineFilter(process.StandardOutput, Console.Out, false); - LineFilter stderrFilter = new LineFilter(process.StandardError, Console.Error, mergeErrors); + Thread outThread = new Thread(stdoutFilter.Filter); + Thread errThread = new Thread(stderrFilter.Filter); - Thread outThread = new Thread(new ThreadStart(stdoutFilter.Filter)); - Thread errThread = new Thread(new ThreadStart(stderrFilter.Filter)); + outThread.Start(); + errThread.Start(); - outThread.Start(); - errThread.Start(); + // Call is redirected, process is lost, will finish when done. + if (isNative) return stderrFilter.Lines == 0; - process.WaitForExit(); + process.WaitForExit(); + outThread.Join(1000); + errThread.Join(1000); + + return (ignoreExitCode) ? stderrFilter.Lines == 0 : process.ExitCode == 0; + } + } - outThread.Join(1000); - errThread.Join(1000); - - return (ignoreExitCode) ? stderrFilter.Lines == 0 : process.ExitCode == 0; - } - } + class LineFilter + { + static readonly Regex reSplitError = new Regex(@"\.[a-z]+:[0-9]+$"); + readonly TextReader reader; + readonly TextWriter writer; + readonly bool mergeErrors; + string unsplit; + public int Lines; - class LineFilter - { - static Regex reSplitError = new Regex(@"\.[a-z]+:[0-9]+$"); - TextReader reader; - TextWriter writer; - bool mergeErrors; - string unsplit = null; - public int Lines; - - public LineFilter(TextReader reader, TextWriter writer, bool mergeErrors) - { - this.reader = reader; - this.writer = writer; + public LineFilter(TextReader reader, TextWriter writer, bool mergeErrors) + { + this.reader = reader; + this.writer = writer; this.mergeErrors = mergeErrors; - } + } - public void Filter() - { - while (true) - { - string line = reader.ReadLine(); - if (line == null) break; + public void Filter() + { + while (true) + { + string line = reader.ReadLine(); + if (line is null) break; if (mergeErrors) { if (unsplit != null) { line = unsplit + ":" + line; unsplit = null; } else if (reSplitError.IsMatch(line)) { unsplit = line; continue; } } - writer.WriteLine(line); - writer.Flush(); - - if (line.Length > 0) Lines++; - } - } - } + writer.WriteLine(line); + writer.Flush(); + + if (line.Length > 0) Lines++; + } + } + } } \ No newline at end of file diff --git a/External/Tools/FDBuild/Building/ProjectBuilder.cs b/External/Tools/FDBuild/Building/ProjectBuilder.cs index c0f4e4a8d2..1129acc12a 100644 --- a/External/Tools/FDBuild/Building/ProjectBuilder.cs +++ b/External/Tools/FDBuild/Building/ProjectBuilder.cs @@ -1,8 +1,6 @@ using System; using System.IO; -using System.Collections.Generic; -using System.Text; -using System.Reflection; +using FDBuild.Building.AS3; using ProjectManager.Projects; using ProjectManager.Projects.AS2; using ProjectManager.Projects.AS3; @@ -17,52 +15,37 @@ namespace ProjectManager.Building { public abstract class ProjectBuilder { - Project project; - string compilerPath; + readonly Project project; - public string CompilerPath - { - get { return compilerPath; } - set { compilerPath = value; } - } + public string CompilerPath { get; set; } public ProjectBuilder(Project project, string compilerPath) { this.project = project; - this.compilerPath = compilerPath; + CompilerPath = compilerPath; } public static ProjectBuilder Create(Project project, string ipcName, string compilerPath) { - if (project is AS2Project) - return new AS2ProjectBuilder(project as AS2Project, compilerPath); - else if (project is AS3Project) - return new AS3ProjectBuilder(project as AS3Project, compilerPath, ipcName); - else if (project is HaxeProject) - return new HaxeProjectBuilder(project as HaxeProject, compilerPath); - else if (project is GenericProject) - return new GenericProjectBuilder(project as GenericProject, compilerPath); - else - throw new Exception("FDBuild doesn't know how to build " + project.GetType().Name); - } - - protected string FDBuildDirectory - { - get + return project switch { - string url = Assembly.GetEntryAssembly().GetName().CodeBase; - Uri uri = new Uri(url); - return Path.GetDirectoryName(uri.LocalPath); - } + AS2Project as2Project => new AS2ProjectBuilder(as2Project, compilerPath), + AS3Project as3Project when Directory.Exists(Path.Combine(compilerPath, "js")) => + new FlexJSProjectBuilder(as3Project, compilerPath), + AS3Project as3Project => new AS3ProjectBuilder(as3Project, compilerPath, ipcName), + HaxeProject haxeProject => new HaxeProjectBuilder(haxeProject, compilerPath), + GenericProject genericProject => new GenericProjectBuilder(genericProject, compilerPath), + _ => throw new Exception("FDBuild doesn't know how to build " + project.GetType().Name) + }; } + protected string FDBuildDirectory => ProjectPaths.ApplicationDirectory; + public void Build(string[] extraClasspaths, bool debugMode, bool noPreBuild, bool noPostBuild) { Console.WriteLine("Building " + project.Name); - - BuildEventRunner runner = new BuildEventRunner(project, compilerPath); - bool attempedPostBuildEvent = false; - + var runner = new BuildEventRunner(project, CompilerPath); + var attempedPostBuildEvent = false; try { if (!noPreBuild && project.PreBuildEvent.Length > 0) @@ -90,15 +73,11 @@ public void Build(string[] extraClasspaths, bool debugMode, bool noPreBuild, boo runner.Run(project.PostBuildEvent, debugMode); } } - Console.WriteLine("Build succeeded"); } - public void BuildCommand(string[] extraClasspaths, bool noTrace) - { - DoBuild(extraClasspaths, noTrace); - } + public void BuildCommand(string[] extraClasspaths, bool noTrace) => DoBuild(extraClasspaths, noTrace); protected abstract void DoBuild(string[] extraClasspaths, bool noTrace); } -} +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Building/SwfmillLibraryBuilder.cs b/External/Tools/FDBuild/Building/SwfmillLibraryBuilder.cs index 1c2c5c51c1..70e2253f08 100644 --- a/External/Tools/FDBuild/Building/SwfmillLibraryBuilder.cs +++ b/External/Tools/FDBuild/Building/SwfmillLibraryBuilder.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using ProjectManager.Projects; using ProjectManager.Building; using System.IO; @@ -9,7 +7,7 @@ namespace FDBuild.Building { class SwfmillLibraryBuilder { - static public string ExecutablePath; + public static string ExecutablePath; public int Frame; @@ -64,8 +62,7 @@ public void BuildLibrarySwf(Project project, bool verbose) string backupLibraryPath = Path.Combine("obj", projectName + "Library.old"); string relLibraryPath = Path.Combine("obj", projectName + "Library.xml"); string backupSwfPath = Path.Combine("obj", projectName + "Resources.old"); - string arguments = string.Format("simple \"{0}\" \"{1}\"", - relLibraryPath, swfPath); + string arguments = $"simple \"{relLibraryPath}\" \"{swfPath}\""; SwfmillLibraryWriter swfmill = new SwfmillLibraryWriter(relLibraryPath); swfmill.WriteProject(project); diff --git a/External/Tools/FDBuild/Building/SwfmillLibraryWriter.cs b/External/Tools/FDBuild/Building/SwfmillLibraryWriter.cs index b28c0a0f7f..14693302e6 100644 --- a/External/Tools/FDBuild/Building/SwfmillLibraryWriter.cs +++ b/External/Tools/FDBuild/Building/SwfmillLibraryWriter.cs @@ -1,5 +1,4 @@ using System; -using System.Collections; using System.IO; using System.Text; using System.Xml; @@ -8,47 +7,47 @@ namespace ProjectManager.Building { // builds a Library.xml file from a .fdp Project - public class SwfmillLibraryWriter : XmlTextWriter - { + public class SwfmillLibraryWriter : XmlTextWriter + { Project project; - public SwfmillLibraryWriter(string libraryPath) : base(libraryPath, Encoding.UTF8) - { - base.Formatting = Formatting.Indented; - } + public SwfmillLibraryWriter(string libraryPath) : base(libraryPath, Encoding.UTF8) + { + Formatting = Formatting.Indented; + } - public void WriteProject(Project project) - { - this.project = project; + public void WriteProject(Project project) + { + this.project = project; - try { InternalWriteProject(); } - finally { Close(); } - } + try { InternalWriteProject(); } + finally { Close(); } + } - // this function should be compacted at some point, it's got too many branches - private void InternalWriteProject() - { - WriteStartDocument(); - WriteComment("This file was generated by a tool (FDBuild)."); - WriteComment("Any modifications you make may be lost."); - WriteStartElement("movie"); + // this function should be compacted at some point, it's got too many branches + void InternalWriteProject() + { + WriteStartDocument(); + WriteComment("This file was generated by a tool (FDBuild)."); + WriteComment("Any modifications you make may be lost."); + WriteStartElement("movie"); int maxFlashVersion = (project.Language == "haxe") ? 10 : 9; int flashVersion = Math.Max(6, Math.Min(maxFlashVersion, project.MovieOptions.MajorVersion)); WriteAttributeString("version", flashVersion.ToString()); - WriteAttributeString("width", project.MovieOptions.Width.ToString()); - WriteAttributeString("height", project.MovieOptions.Height.ToString()); - WriteAttributeString("framerate", project.MovieOptions.Fps.ToString()); - WriteStartElement("background"); - WriteAttributeString("color", project.MovieOptions.Background); - WriteEndElement(); - WriteStartElement("frame"); - WriteStartElement("library"); + WriteAttributeString("width", project.MovieOptions.Width.ToString()); + WriteAttributeString("height", project.MovieOptions.Height.ToString()); + WriteAttributeString("framerate", project.MovieOptions.Fps.ToString()); + WriteStartElement("background"); + WriteAttributeString("color", project.MovieOptions.Background); + WriteEndElement(); + WriteStartElement("frame"); + WriteStartElement("library"); WriteStartElement("clip"); WriteAttributeString("id", GetSafeId("__sharepoint__")); WriteEndElement(); - WritePreloaders(); + WritePreloaders(); if (!NeedsMoreFrames) WriteNormalAssets(); else @@ -57,70 +56,54 @@ private void InternalWriteProject() WriteAttributeString("id", GetSafeId("__importtag__")); WriteEndElement(); } - WriteEndElement(); + WriteEndElement(); WriteSharedClips(); - WriteEndElement(); + WriteEndElement(); - if (NeedsMoreFrames) - { - WriteStartElement("frame"); + if (NeedsMoreFrames) + { + WriteStartElement("frame"); WriteSharedImports(); - WriteEndElement(); + WriteEndElement(); - // generate two extra frames (code will be injected into frame 3) - WriteStartElement("frame"); - WriteElementString("stop",""); - WriteStartElement("library"); - WriteNormalAssets(); - WriteEndElement(); - WriteEndElement(); + // generate two extra frames (code will be injected into frame 3) + WriteStartElement("frame"); + WriteElementString("stop",""); + WriteStartElement("library"); + WriteNormalAssets(); + WriteEndElement(); + WriteEndElement(); } - WriteEndElement(); - WriteEndDocument(); - Flush(); - } - - #region Library Building - - /*private void WritePlaceOnStage() - { - foreach (LibraryAsset asset in project.LibraryAssets) - if (asset.IsAS && asset.PlaceOnStage && File.Exists(asset.Path)) - { - string id = asset.ID; + WriteEndElement(); + WriteEndDocument(); + Flush(); + } - WriteStartElement("place"); - WriteAttributeString("id",id); - WriteAttributeString("name","_"+id); - //WriteAttributeString("x","0"); - //WriteAttributeString("y","0"); - WriteEndElement(); - } - }*/ + #region Library Building - private void WritePreloaders() - { - foreach (LibraryAsset asset in project.LibraryAssets) - { - // TODO: this is a crappy workaround for the general problem of - // project "cruft" accumulating. This will be removed once - // I add support in the treeview for displaying "missing" project items - - if (!File.Exists(asset.Path)) - continue; - - if (asset.IsSwf && asset.SwfMode == SwfAssetMode.Preloader) - AddSwf(asset); - } - } + void WritePreloaders() + { + foreach (LibraryAsset asset in project.LibraryAssets) + { + // TODO: this is a crappy workaround for the general problem of + // project "cruft" accumulating. This will be removed once + // I add support in the treeview for displaying "missing" project items + + if (!File.Exists(asset.Path)) + continue; + + if (asset.IsSwf && asset.SwfMode == SwfAssetMode.Preloader) + AddSwf(asset); + } + } - private void WriteSharedClips() - { - int depth = 0; + void WriteSharedClips() + { + int depth = 0; - // place empty clips to the stage to signal to any preloaders what - // libraries need to be loaded - foreach (LibraryAsset asset in project.LibraryAssets) + // place empty clips to the stage to signal to any preloaders what + // libraries need to be loaded + foreach (LibraryAsset asset in project.LibraryAssets) if (asset.IsSwf && asset.SwfMode == SwfAssetMode.Shared) { WriteStartElement("place"); @@ -129,68 +112,68 @@ private void WriteSharedClips() WriteAttributeString("depth", (depth++).ToString()); WriteEndElement(); } - } + } - private void WriteSharedImports() - { - // import shared libraries - foreach (LibraryAsset asset in project.LibraryAssets) - if (asset.IsSwf && asset.SwfMode == SwfAssetMode.Shared) - { - WriteStartElement("import"); - WriteAttributeString("url", asset.Path); - if (asset.Sharepoint != null) - WriteAttributeString("symbol", asset.Sharepoint); - else - WriteAttributeString("file", asset.Path); - WriteEndElement(); - } - } + void WriteSharedImports() + { + // import shared libraries + foreach (LibraryAsset asset in project.LibraryAssets) + if (asset.IsSwf && asset.SwfMode == SwfAssetMode.Shared) + { + WriteStartElement("import"); + WriteAttributeString("url", asset.Path); + if (asset.Sharepoint != null) + WriteAttributeString("symbol", asset.Sharepoint); + else + WriteAttributeString("file", asset.Path); + WriteEndElement(); + } + } - private void WriteNormalAssets() - { - foreach (LibraryAsset asset in project.LibraryAssets) - { - if (!File.Exists(asset.Path)) - continue; - - if (!asset.IsSwf || asset.SwfMode == SwfAssetMode.Library) - AddAsset(asset); - } - } + void WriteNormalAssets() + { + foreach (LibraryAsset asset in project.LibraryAssets) + { + if (!File.Exists(asset.Path)) + continue; + + if (!asset.IsSwf || asset.SwfMode == SwfAssetMode.Library) + AddAsset(asset); + } + } - // returns true if you have any shared libraries or preloaders - public bool NeedsMoreFrames - { - get - { - foreach (LibraryAsset asset in project.LibraryAssets) - if (File.Exists(asset.Path) && asset.IsSwf && - asset.SwfMode != SwfAssetMode.Library) - return true; - return false; - } + // returns true if you have any shared libraries or preloaders + public bool NeedsMoreFrames + { + get + { + foreach (LibraryAsset asset in project.LibraryAssets) + if (File.Exists(asset.Path) && asset.IsSwf && + asset.SwfMode != SwfAssetMode.Library) + return true; + return false; + } } - private string GetSafeId(string id) + string GetSafeId(string id) { - return (project.Language == "haxe") ? Char.ToUpper(id[2]) + id.Substring(3) : id; + return (project.Language == "haxe") ? char.ToUpper(id[2]) + id.Substring(3) : id; } - #endregion + #endregion - #region Adding Assets + #region Adding Assets - private void AddAsset(LibraryAsset asset) - { + void AddAsset(LibraryAsset asset) + { if (asset.IsImage) AddImage(asset); else if (asset.IsFont) AddFont(asset); else if (asset.IsSwf) AddSwf(asset); else if (asset.IsSound) AddSound(asset); - } + } - private void AddImage(LibraryAsset asset) - { + void AddImage(LibraryAsset asset) + { if (asset.BitmapLinkage) { WriteStartElement("bitmap"); @@ -201,12 +184,12 @@ private void AddImage(LibraryAsset asset) } WriteAttributeString("id", asset.ID); WriteAttributeString("name", asset.ID); - WriteAttributeString("import", asset.Path); - AddStampAttributes(asset.Path); - WriteEndElement(); + WriteAttributeString("import", asset.Path); + AddStampAttributes(asset.Path); + WriteEndElement(); } - private void AddSound(LibraryAsset asset) + void AddSound(LibraryAsset asset) { // WriteStartElement("sound"); @@ -217,43 +200,43 @@ private void AddSound(LibraryAsset asset) WriteEndElement(); } - private void AddFont(LibraryAsset asset) - { - WriteStartElement("font"); + void AddFont(LibraryAsset asset) + { + WriteStartElement("font"); WriteAttributeString("id", asset.ID); WriteAttributeString("name", asset.ID); - WriteAttributeString("import", asset.Path); + WriteAttributeString("import", asset.Path); - if (asset.FontGlyphs != null) - WriteAttributeString("glyphs",asset.FontGlyphs); - else - WriteAttributeString("glyphs", "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ `~!@#$%^&*()-_=+[]{}\\|;:'\",./<>?"); - - AddStampAttributes(asset.Path); - WriteEndElement(); - } + if (asset.FontGlyphs != null) + WriteAttributeString("glyphs",asset.FontGlyphs); + else + WriteAttributeString("glyphs", "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ `~!@#$%^&*()-_=+[]{}\\|;:'\",./<>?"); + + AddStampAttributes(asset.Path); + WriteEndElement(); + } - private void AddSwf(LibraryAsset asset) - { - WriteStartElement("clip"); + void AddSwf(LibraryAsset asset) + { + WriteStartElement("clip"); if (asset.SwfMode == SwfAssetMode.Library) { WriteAttributeString("id", asset.ID); WriteAttributeString("name", asset.ID); } - WriteAttributeString("import", asset.Path); - AddStampAttributes(asset.Path); - WriteEndElement(); - } + WriteAttributeString("import", asset.Path); + AddStampAttributes(asset.Path); + WriteEndElement(); + } - private void AddStampAttributes(string path) - { - FileInfo file = new FileInfo(path); - WriteAttributeString("size", file.Length.ToString()); - WriteAttributeString("modified", file.LastWriteTimeUtc.ToString()); - } + void AddStampAttributes(string path) + { + FileInfo file = new FileInfo(path); + WriteAttributeString("size", file.Length.ToString()); + WriteAttributeString("modified", file.LastWriteTimeUtc.ToString()); + } - #endregion - } + #endregion + } } diff --git a/External/Tools/FDBuild/FDBuild.csproj b/External/Tools/FDBuild/FDBuild.csproj index 5c707f80ab..cea8f690be 100644 --- a/External/Tools/FDBuild/FDBuild.csproj +++ b/External/Tools/FDBuild/FDBuild.csproj @@ -1,69 +1,109 @@  - + Debug AnyCPU - 9.0.21022 - 2.0 {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09} - Exe + WinExe FDBuild fdbuild - - - 3.5 - - - v2.0 + net48 + true + false + false + false + publish\ + true + Disk + true + false + false + win-x64;win-x86; + false + x64;AnyCPU;x86 true full false ..\..\..\FlashDevelop\Bin\Debug\Tools\fdbuild\ - DEBUG;TRACE + DEBUG;TRACE;FDBUILD prompt 4 + 9 + win-x64 pdbonly true ..\..\..\FlashDevelop\Bin\Debug\Tools\fdbuild\ - TRACE + TRACE;FDBUILD prompt 4 + 9 + win-x64 true ..\..\..\FlashDevelop\Bin\Debug\Tools\fdbuild\ - DEBUG;TRACE + TRACE;DEBUG;FDBUILD full x86 prompt + 9 + win-x86 ..\..\..\FlashDevelop\Bin\Debug\Tools\fdbuild\ - TRACE + TRACE;FDBUILD true none x86 prompt false + 9 + win-x86 + + + true + ..\..\..\FlashDevelop\Bin\Debug\Tools\fdbuild\ + TRACE;DEBUG;FDBUILD + full + x64 + 9 + prompt + true + win-x64 + + + ..\..\..\FlashDevelop\Bin\Debug\Tools\fdbuild\ + TRACE;FDBUILD + true + x64 + false + 9 + prompt + true + win-x64 - - + + DistroConfig.cs + Building\AS3\ConfigHelper.cs + + Building\FileInspector.cs + Building\AS3\JvmConfigHelper.cs @@ -100,21 +140,18 @@ Projects\AS3\AS3ProjectWriter.cs - - Projects\AS3\FlexProjectReader.cs - Projects\AS3\MxmlcOptions.cs + + Projects\AS3\MxmlNamespace.cs + Projects\BuildEventVars.cs Projects\CompilerOptions.cs - - Projects\FileInspector.cs - Projects\Generic\GenericMovieOptions.cs @@ -172,10 +209,14 @@ Projects\ProjectWriter.cs + + Helpers\PlatformHelper.cs + + @@ -203,12 +244,5 @@ - - + \ No newline at end of file diff --git a/External/Tools/FDBuild/FDBuild.sln b/External/Tools/FDBuild/FDBuild.sln index 5dd03b44bf..909e6352f9 100644 --- a/External/Tools/FDBuild/FDBuild.sln +++ b/External/Tools/FDBuild/FDBuild.sln @@ -1,6 +1,8 @@  -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual C# Express 2010 +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29021.104 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FDBuild", "FDBuild.csproj", "{FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}" ProjectSection(ProjectDependencies) = postProject {78101C01-E186-4954-B1DD-DEBB7905FAD8} = {78101C01-E186-4954-B1DD-DEBB7905FAD8} diff --git a/External/Tools/FDBuild/FDBuildOptions.cs b/External/Tools/FDBuild/FDBuildOptions.cs index b092c62cec..848528dc2a 100644 --- a/External/Tools/FDBuild/FDBuildOptions.cs +++ b/External/Tools/FDBuild/FDBuildOptions.cs @@ -1,35 +1,31 @@ -using System; -using System.Collections; +using System.Collections.Generic; using Mono.GetOptions; using System.IO; namespace FDBuild { - public class FDBuildOptions : Options - { - ArrayList extraClasspaths; + public class FDBuildOptions : Options + { + readonly List extraClasspaths; string language; - public string ProjectFile; + public string ProjectFile; - public FDBuildOptions(string[] args) - { - NoTrace = false; - ProjectFile = ""; - extraClasspaths = new ArrayList(); - ProcessArgs(args); - } + public FDBuildOptions(string[] args) + { + NoTrace = false; + ProjectFile = ""; + extraClasspaths = new List(); + ProcessArgs(args); + } - [ArgumentProcessor] - public void SetProject(string file) - { - ProjectFile = file; - } + [ArgumentProcessor] + public void SetProject(string file) => ProjectFile = file; - [Option(99, "Add extra classpath", "cp")] - public string ExtraClasspath - { - set { if (!extraClasspaths.Contains(value)) extraClasspaths.Add(value); } - } + [Option(99, "Add extra classpath", "cp")] + public string ExtraClasspath + { + set { if (!extraClasspaths.Contains(value)) extraClasspaths.Add(value); } + } [Option("Set library base directory", "library")] public string LibraryDir; @@ -56,27 +52,24 @@ public string ExtraClasspath public bool NoPostBuild = false; [Option("Pause the console after building", "pause")] - public bool PauseAtEnd = false; + public bool PauseAtEnd = false; [Option("Connect to FlashDevelop's remoting services using the specified IPC name (optional)", "ipc")] public string IpcName = null; public string Language { - set { - if (LibraryDir == null) return; - if (language != null) - extraClasspaths.Remove(Path.Combine(LibraryDir, Path.Combine(language, "classes"))); + set + { + if (LibraryDir is null) return; + if (language != null) extraClasspaths.Remove(Path.Combine(LibraryDir, language, "classes")); language = value; + var library = Path.Combine(LibraryDir, language, "classes"); // add the library classpath for the language - string library = Path.Combine(LibraryDir, Path.Combine(language, "classes")); if (Directory.Exists(library) && language != "HAXE") extraClasspaths.Add(library); } } - public string[] ExtraClasspaths - { - get { return extraClasspaths.ToArray(typeof(string)) as string[]; } - } - } -} + public string[] ExtraClasspaths => extraClasspaths.ToArray(); + } +} \ No newline at end of file diff --git a/External/Tools/FDBuild/FakeClasses.cs b/External/Tools/FDBuild/FakeClasses.cs index 164b67d09e..ce45dbaf22 100644 --- a/External/Tools/FDBuild/FakeClasses.cs +++ b/External/Tools/FDBuild/FakeClasses.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Collections; using System.IO; @@ -31,11 +29,11 @@ public class PropertiesDialog { } } namespace ProjectManager.Controls.AS2 { - public class AS2PropertiesDialog : ProjectManager.Controls.PropertiesDialog { } + public class AS2PropertiesDialog : PropertiesDialog { } } namespace ProjectManager.Controls.AS3 { - public class AS3PropertiesDialog : ProjectManager.Controls.PropertiesDialog { } + public class AS3PropertiesDialog : PropertiesDialog { } } namespace ProjectManager.Helpers @@ -45,16 +43,16 @@ namespace ProjectManager.Helpers /// class ProjectCreator { - private static Hashtable projectTypes = new Hashtable(); - private static bool projectTypesSet = false; + private static readonly Hashtable projectTypes = new Hashtable(); + private static bool projectTypesSet; private static void SetInitialProjectHash() { - projectTypes["project.fdp"] = typeof(ProjectManager.Projects.AS2.AS2Project); - projectTypes["project.as2proj"] = typeof(ProjectManager.Projects.AS2.AS2Project); - projectTypes["project.as3proj"] = typeof(ProjectManager.Projects.AS3.AS3Project); - projectTypes["project.hxproj"] = typeof(ProjectManager.Projects.Haxe.HaxeProject); - projectTypes["project.fdproj"] = typeof(ProjectManager.Projects.Generic.GenericProject); + projectTypes["project.fdp"] = typeof(Projects.AS2.AS2Project); + projectTypes["project.as2proj"] = typeof(Projects.AS2.AS2Project); + projectTypes["project.as3proj"] = typeof(Projects.AS3.AS3Project); + projectTypes["project.hxproj"] = typeof(Projects.Haxe.HaxeProject); + projectTypes["project.fdproj"] = typeof(Projects.Generic.GenericProject); projectTypesSet = true; } @@ -72,9 +70,18 @@ public static Type GetProjectType(string key) return null; } - public static string KeyForProjectPath(string path) + public static string KeyForProjectPath(string path) => "project" + Path.GetExtension(path).ToLower(); + } +} + +namespace ProjectManager.Projects.AS3 +{ + internal class FlexProjectReader : ProjectReader + { + public FlexProjectReader(string filename) + : base(filename, new AS3Project(filename)) { - return "project" + Path.GetExtension(path).ToLower(); } } -} \ No newline at end of file + +} diff --git a/External/Tools/FDBuild/Mono/AboutAttribute.cs b/External/Tools/FDBuild/Mono/AboutAttribute.cs index 609cbdaeb1..d7c96981dd 100644 --- a/External/Tools/FDBuild/Mono/AboutAttribute.cs +++ b/External/Tools/FDBuild/Mono/AboutAttribute.cs @@ -8,17 +8,12 @@ public class AboutAttribute : Attribute // Methods public AboutAttribute(string details) { - this.Details = details; + Details = details; } - public override string ToString() - { - return this.Details; - } - - + public override string ToString() => Details; + // Fields public string Details; } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/AuthorAttribute.cs b/External/Tools/FDBuild/Mono/AuthorAttribute.cs index aa195f7996..a947a773ea 100644 --- a/External/Tools/FDBuild/Mono/AuthorAttribute.cs +++ b/External/Tools/FDBuild/Mono/AuthorAttribute.cs @@ -8,29 +8,27 @@ public class AuthorAttribute : Attribute // Methods public AuthorAttribute(string name) { - this.Name = name; - this.SubProject = null; + Name = name; + SubProject = null; } public AuthorAttribute(string name, string subProject) { - this.Name = name; - this.SubProject = subProject; + Name = name; + SubProject = subProject; } public override string ToString() { - if (this.SubProject == null) + if (SubProject is null) { - return this.Name; + return Name; } - return (this.Name + " (" + this.SubProject + ")"); + return (Name + " (" + SubProject + ")"); } - - + // Fields public string Name; public string SubProject; } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/GetOptions/ArgumentProcessorAttribute.cs b/External/Tools/FDBuild/Mono/GetOptions/ArgumentProcessorAttribute.cs index 49b8dda6ba..9d9ca0468a 100644 --- a/External/Tools/FDBuild/Mono/GetOptions/ArgumentProcessorAttribute.cs +++ b/External/Tools/FDBuild/Mono/GetOptions/ArgumentProcessorAttribute.cs @@ -5,11 +5,5 @@ namespace Mono.GetOptions [AttributeUsage(AttributeTargets.Method)] public class ArgumentProcessorAttribute : Attribute { - // Methods - public ArgumentProcessorAttribute() - { - } - } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/GetOptions/OptionAttribute.cs b/External/Tools/FDBuild/Mono/GetOptions/OptionAttribute.cs index 4e6d944dc8..19cdf5965e 100644 --- a/External/Tools/FDBuild/Mono/GetOptions/OptionAttribute.cs +++ b/External/Tools/FDBuild/Mono/GetOptions/OptionAttribute.cs @@ -8,71 +8,71 @@ public class OptionAttribute : Attribute // Methods public OptionAttribute(string shortDescription) { - this.SetValues(shortDescription, ' ', string.Empty, string.Empty, 1); + SetValues(shortDescription, ' ', string.Empty, string.Empty, 1); } public OptionAttribute(int maxOccurs, string shortDescription) { - this.SetValues(shortDescription, ' ', string.Empty, string.Empty, maxOccurs); + SetValues(shortDescription, ' ', string.Empty, string.Empty, maxOccurs); } public OptionAttribute(string shortDescription, char shortForm) { - this.SetValues(shortDescription, shortForm, string.Empty, string.Empty, 1); + SetValues(shortDescription, shortForm, string.Empty, string.Empty, 1); } public OptionAttribute(string shortDescription, string longForm) { - this.SetValues(shortDescription, ' ', longForm, string.Empty, 1); + SetValues(shortDescription, ' ', longForm, string.Empty, 1); } public OptionAttribute(int maxOccurs, string shortDescription, char shortForm) { - this.SetValues(shortDescription, shortForm, string.Empty, string.Empty, maxOccurs); + SetValues(shortDescription, shortForm, string.Empty, string.Empty, maxOccurs); } public OptionAttribute(int maxOccurs, string shortDescription, string longForm) { - this.SetValues(shortDescription, ' ', longForm, string.Empty, maxOccurs); + SetValues(shortDescription, ' ', longForm, string.Empty, maxOccurs); } public OptionAttribute(string shortDescription, char shortForm, string longForm) { - this.SetValues(shortDescription, shortForm, longForm, string.Empty, 1); + SetValues(shortDescription, shortForm, longForm, string.Empty, 1); } public OptionAttribute(string shortDescription, string longForm, string alternateForm) { - this.SetValues(shortDescription, ' ', longForm, alternateForm, 1); + SetValues(shortDescription, ' ', longForm, alternateForm, 1); } public OptionAttribute(int maxOccurs, string shortDescription, char shortForm, string longForm) { - this.SetValues(shortDescription, shortForm, longForm, string.Empty, maxOccurs); + SetValues(shortDescription, shortForm, longForm, string.Empty, maxOccurs); } public OptionAttribute(int maxOccurs, string shortDescription, string longForm, string alternateForm) { - this.SetValues(shortDescription, ' ', longForm, alternateForm, maxOccurs); + SetValues(shortDescription, ' ', longForm, alternateForm, maxOccurs); } public OptionAttribute(string shortDescription, char shortForm, string longForm, string alternateForm) { - this.SetValues(shortDescription, shortForm, longForm, alternateForm, 1); + SetValues(shortDescription, shortForm, longForm, alternateForm, 1); } public OptionAttribute(int maxOccurs, string shortDescription, char shortForm, string longForm, string alternateForm) { - this.SetValues(shortDescription, shortForm, longForm, alternateForm, maxOccurs); + SetValues(shortDescription, shortForm, longForm, alternateForm, maxOccurs); } private void SetValues(string shortDescription, char shortForm, string longForm, string alternateForm, int maxOccurs) { - this.ShortDescription = shortDescription; - this.ShortForm = shortForm; - this.LongForm = longForm; - this.MaxOccurs = maxOccurs; - this.AlternateForm = alternateForm; + ShortDescription = shortDescription; + ShortForm = shortForm; + LongForm = longForm; + MaxOccurs = maxOccurs; + AlternateForm = alternateForm; } diff --git a/External/Tools/FDBuild/Mono/GetOptions/OptionDetails.cs b/External/Tools/FDBuild/Mono/GetOptions/OptionDetails.cs index 43ea7947bf..c6468a91be 100644 --- a/External/Tools/FDBuild/Mono/GetOptions/OptionDetails.cs +++ b/External/Tools/FDBuild/Mono/GetOptions/OptionDetails.cs @@ -6,134 +6,125 @@ namespace Mono.GetOptions internal class OptionDetails : IComparable { - // Methods - static OptionDetails() + public OptionDetails(MemberInfo memberInfo, OptionAttribute option, Options optionBundle) { - OptionDetails.Verbose = false; - } - - public OptionDetails(System.Reflection.MemberInfo memberInfo, OptionAttribute option, Options optionBundle) - { - this.paramName = null; - this.optionHelp = null; - this.ShortForm = ("" + option.ShortForm).Trim(); - if (option.LongForm == null) + paramName = null; + optionHelp = null; + ShortForm = ("" + option.ShortForm).Trim(); + if (option.LongForm is null) { - this.LongForm = string.Empty; + LongForm = string.Empty; } else { - this.LongForm = (option.LongForm != string.Empty) ? option.LongForm : memberInfo.Name; + LongForm = option.LongForm.Length != 0 ? option.LongForm : memberInfo.Name; } - this.AlternateForm = option.AlternateForm; - this.ShortDescription = this.ExtractParamName(option.ShortDescription); - this.Occurs = 0; - this.OptionBundle = optionBundle; - this.BooleanOption = false; - this.MemberInfo = memberInfo; - this.NeedsParameter = false; - this.Values = null; - this.MaxOccurs = 1; - this.VBCStyleBoolean = option.VBCStyleBoolean; - this.SecondLevelHelp = option.SecondLevelHelp; - this.ParameterType = OptionDetails.TypeOfMember(memberInfo); - if (this.ParameterType != null) + AlternateForm = option.AlternateForm; + ShortDescription = ExtractParamName(option.ShortDescription); + Occurs = 0; + OptionBundle = optionBundle; + BooleanOption = false; + MemberInfo = memberInfo; + NeedsParameter = false; + Values = null; + MaxOccurs = 1; + VBCStyleBoolean = option.VBCStyleBoolean; + SecondLevelHelp = option.SecondLevelHelp; + ParameterType = TypeOfMember(memberInfo); + if (ParameterType != null) { - if (this.ParameterType.FullName != "System.Boolean") + if (ParameterType.FullName != "System.Boolean") { - if (this.LongForm.IndexOf(':') >= 0) + if (LongForm.IndexOf(':') >= 0) { - throw new InvalidOperationException("Options with an embedded colon (':') in their visible name must be boolean!!! [" + this.MemberInfo.ToString() + " isn't]"); + throw new InvalidOperationException("Options with an embedded colon (':') in their visible name must be boolean!!! [" + MemberInfo + " isn't]"); } - this.NeedsParameter = true; + NeedsParameter = true; if (option.MaxOccurs == 1) { return; } - if (this.ParameterType.IsArray) + if (ParameterType.IsArray) { - this.Values = new ArrayList(); - this.MaxOccurs = option.MaxOccurs; + Values = new ArrayList(); + MaxOccurs = option.MaxOccurs; return; } - if ((this.MemberInfo is MethodInfo) || (this.MemberInfo is PropertyInfo)) + if (MemberInfo is MethodInfo || MemberInfo is PropertyInfo) { - this.MaxOccurs = option.MaxOccurs; + MaxOccurs = option.MaxOccurs; return; } - object[] objArray1 = new object[] { "MaxOccurs set to non default value (", option.MaxOccurs, ") for a [", this.MemberInfo.ToString(), "] option" } ; + object[] objArray1 = { "MaxOccurs set to non default value (", option.MaxOccurs, ") for a [", MemberInfo.ToString(), "] option" } ; throw new InvalidOperationException(string.Concat(objArray1)); } - this.BooleanOption = true; + BooleanOption = true; if (option.MaxOccurs != 1) { - if ((this.MemberInfo is MethodInfo) || (this.MemberInfo is PropertyInfo)) + if (MemberInfo is MethodInfo || MemberInfo is PropertyInfo) { - this.MaxOccurs = option.MaxOccurs; + MaxOccurs = option.MaxOccurs; } else { - object[] objArray2 = new object[] { "MaxOccurs set to non default value (", option.MaxOccurs, ") for a [", this.MemberInfo.ToString(), "] option" } ; + object[] objArray2 = { "MaxOccurs set to non default value (", option.MaxOccurs, ") for a [", MemberInfo.ToString(), "] option" } ; throw new InvalidOperationException(string.Concat(objArray2)); } } } } - private void DoIt(bool setValue) + void DoIt(bool setValue) { - if (!this.NeedsParameter) + if (!NeedsParameter) { - this.Occurred(1); - if (OptionDetails.Verbose) + Occurred(1); + if (Verbose) { - Console.WriteLine("<" + this.LongForm + "> set to [true]"); + Console.WriteLine("<" + LongForm + "> set to [true]"); } - if (this.MemberInfo is FieldInfo) + if (MemberInfo is FieldInfo info) { - ((FieldInfo) this.MemberInfo).SetValue(this.OptionBundle, setValue); + info.SetValue(OptionBundle, setValue); } - else if (this.MemberInfo is PropertyInfo) + else if (MemberInfo is PropertyInfo propertyInfo) { - ((PropertyInfo) this.MemberInfo).SetValue(this.OptionBundle, setValue, null); + propertyInfo.SetValue(OptionBundle, setValue, null); } - else if (((WhatToDoNext) ((MethodInfo) this.MemberInfo).Invoke(this.OptionBundle, null)) == WhatToDoNext.AbandonProgram) + else if ((WhatToDoNext) ((MethodInfo) MemberInfo).Invoke(OptionBundle, null) == WhatToDoNext.AbandonProgram) { Environment.Exit(1); } } } - private void DoIt(string parameterValue) + void DoIt(string parameterValue) { - if (parameterValue == null) - { - parameterValue = ""; - } - char[] chArray1 = new char[] { ',' } ; + parameterValue ??= ""; + char[] chArray1 = { ',' } ; string[] textArray1 = parameterValue.Split(chArray1); - this.Occurred(textArray1.Length); + Occurred(textArray1.Length); string[] textArray2 = textArray1; - for (int num1 = 0; num1 < textArray2.Length; num1++) + foreach (var text1 in textArray2) { - string text1 = textArray2[num1]; object obj1 = null; - if (OptionDetails.Verbose) + if (Verbose) { - string[] textArray3 = new string[] { "<", this.LongForm, "> set to [", text1, "]" } ; + string[] textArray3 = { "<", LongForm, "> set to [", text1, "]" } ; Console.WriteLine(string.Concat(textArray3)); } - if ((this.Values != null) && (text1 != null)) + if (Values != null && text1 != null) { try { - obj1 = Convert.ChangeType(text1, this.ParameterType.GetElementType()); + obj1 = Convert.ChangeType(text1, ParameterType.GetElementType()); } catch (Exception) { - Console.WriteLine(string.Format("The value '{0}' is not convertible to the appropriate type '{1}' for the {2} option", text1, this.ParameterType.GetElementType().Name, this.DefaultForm)); + Console.WriteLine( + $"The value '{text1}' is not convertible to the appropriate type '{ParameterType.GetElementType().Name}' for the {DefaultForm} option"); } - this.Values.Add(obj1); + Values.Add(obj1); } else { @@ -141,119 +132,114 @@ private void DoIt(string parameterValue) { try { - obj1 = Convert.ChangeType(text1, this.ParameterType); + obj1 = Convert.ChangeType(text1, ParameterType); } catch (Exception) { - Console.WriteLine(string.Format("The value '{0}' is not convertible to the appropriate type '{1}' for the {2} option", text1, this.ParameterType.Name, this.DefaultForm)); + Console.WriteLine( + $"The value '{text1}' is not convertible to the appropriate type '{ParameterType.Name}' for the {DefaultForm} option"); goto Label_01B1; } } - if (this.MemberInfo is FieldInfo) + if (MemberInfo is FieldInfo fieldInfo) { - ((FieldInfo) this.MemberInfo).SetValue(this.OptionBundle, obj1); + fieldInfo.SetValue(OptionBundle, obj1); } - else if (this.MemberInfo is PropertyInfo) + else if (MemberInfo is PropertyInfo propertyInfo) { - ((PropertyInfo) this.MemberInfo).SetValue(this.OptionBundle, obj1, null); + propertyInfo.SetValue(OptionBundle, obj1, null); } else { - object[] objArray1 = new object[] { obj1 } ; - if (((WhatToDoNext) ((MethodInfo) this.MemberInfo).Invoke(this.OptionBundle, objArray1)) == WhatToDoNext.AbandonProgram) + object[] objArray1 = { obj1 } ; + if ((WhatToDoNext) ((MethodInfo) MemberInfo).Invoke(OptionBundle, objArray1) == WhatToDoNext.AbandonProgram) { Environment.Exit(1); } } } - Label_01B1:; + Label_01B1:; } } - private string ExtractParamName(string shortDescription) + string ExtractParamName(string shortDescription) { - int num1 = shortDescription.IndexOf("{"); + int num1 = shortDescription.IndexOf('{'); if (num1 < 0) { - this.paramName = "PARAM"; + paramName = "PARAM"; return shortDescription; } - int num2 = shortDescription.IndexOf("}"); + int num2 = shortDescription.IndexOf('}'); if (num2 < num1) { num2 = shortDescription.Length + 1; } - this.paramName = shortDescription.Substring(num1 + 1, (num2 - num1) - 1); - shortDescription = shortDescription.Substring(0, num1) + this.paramName + shortDescription.Substring(num2 + 1); + paramName = shortDescription.Substring(num1 + 1, num2 - num1 - 1); + shortDescription = shortDescription.Substring(0, num1) + paramName + shortDescription.Substring(num2 + 1); return shortDescription; } - private bool IsThisOption(string arg) + bool IsThisOption(string arg) { - if ((arg == null) || (arg == string.Empty)) - { - return false; - } - char[] chArray1 = new char[] { '-', '/' } ; + if (string.IsNullOrEmpty(arg)) return false; + char[] chArray1 = { '-', '/' } ; arg = arg.TrimStart(chArray1); - if (this.VBCStyleBoolean) + if (VBCStyleBoolean) { - char[] chArray2 = new char[] { '-', '+' } ; + char[] chArray2 = { '-', '+' } ; arg = arg.TrimEnd(chArray2); } - return (((arg == this.ShortForm) || (arg == this.LongForm)) || (arg == this.AlternateForm)); + return arg == ShortForm || arg == LongForm || arg == AlternateForm; } - private void Occurred(int howMany) + void Occurred(int howMany) { - this.Occurs += howMany; - if ((this.MaxOccurs > 0) && (this.Occurs > this.MaxOccurs)) + Occurs += howMany; + if (MaxOccurs > 0 && Occurs > MaxOccurs) { - object[] objArray1 = new object[] { "Option ", this.ShortForm, " can be used at most ", this.MaxOccurs, " times" } ; + object[] objArray1 = { "Option ", ShortForm, " can be used at most ", MaxOccurs, " times" } ; throw new IndexOutOfRangeException(string.Concat(objArray1)); } } public OptionProcessingResult ProcessArgument(string arg, string nextArg) { - if (this.IsThisOption(arg)) + if (IsThisOption(arg)) { - if (!this.NeedsParameter) + if (!NeedsParameter) { - if (this.VBCStyleBoolean && arg.EndsWith("-")) + if (VBCStyleBoolean && arg.EndsWith("-", StringComparison.Ordinal)) { - this.DoIt(false); + DoIt(false); } else { - this.DoIt(true); + DoIt(true); } return OptionProcessingResult.OptionAlone; } - this.DoIt(nextArg); + DoIt(nextArg); return OptionProcessingResult.OptionConsumedParameter; } - if (this.IsThisOption(arg + ":" + nextArg)) + if (IsThisOption(arg + ":" + nextArg)) { - this.DoIt(true); + DoIt(true); return OptionProcessingResult.OptionConsumedParameter; } return OptionProcessingResult.NotThisOption; } - int IComparable.CompareTo(object other) - { - return this.Key.CompareTo(((OptionDetails) other).Key); - } + int IComparable.CompareTo(object other) => Key.CompareTo(((OptionDetails) other).Key); public override string ToString() { - if (this.optionHelp == null) + if (optionHelp is null) { string text1; string text2; - bool flag1 = (this.LongForm != null) && (this.LongForm != string.Empty); - if (this.OptionBundle.ParsingMode == OptionsParsingMode.Windows) + bool flag1 = !string.IsNullOrEmpty(LongForm); + if (OptionBundle.ParsingMode == OptionsParsingMode.Windows) { text2 = "/"; text1 = "/"; @@ -261,145 +247,113 @@ public override string ToString() else { text2 = "-"; - text1 = this.linuxLongPrefix; + text1 = linuxLongPrefix; } - this.optionHelp = " "; - this.optionHelp = this.optionHelp + ((this.ShortForm == string.Empty) ? " " : (text2 + this.ShortForm + " ")); - this.optionHelp = this.optionHelp + (!flag1 ? "" : (text1 + this.LongForm)); - if (this.NeedsParameter) + optionHelp = " "; + optionHelp += ShortForm == string.Empty ? " " : text2 + ShortForm + " "; + optionHelp += !flag1 ? "" : text1 + LongForm; + if (NeedsParameter) { if (flag1) { - this.optionHelp = this.optionHelp + ":"; + optionHelp += ":"; } - this.optionHelp = this.optionHelp + this.ParamName; + optionHelp += ParamName; } - else if (this.BooleanOption && this.VBCStyleBoolean) + else if (BooleanOption && VBCStyleBoolean) { - this.optionHelp = this.optionHelp + "[+|-]"; + optionHelp += "[+|-]"; } - this.optionHelp = this.optionHelp + ("\t" + this.ShortDescription); - if ((this.AlternateForm != string.Empty) && (this.AlternateForm != null)) + optionHelp += "\t" + ShortDescription; + if (!string.IsNullOrEmpty(AlternateForm)) { - this.optionHelp = this.optionHelp + (" [short form: " + text2 + this.AlternateForm + "]"); + optionHelp += " [short form: " + text2 + AlternateForm + "]"; } } - return this.optionHelp; + return optionHelp; } public void TransferValues() { - if (this.Values != null) + if (Values is null) return; + if (MemberInfo is FieldInfo fieldInfo) { - if (this.MemberInfo is FieldInfo) - { - ((FieldInfo) this.MemberInfo).SetValue(this.OptionBundle, this.Values.ToArray(this.ParameterType.GetElementType())); - } - else if (this.MemberInfo is PropertyInfo) - { - ((PropertyInfo) this.MemberInfo).SetValue(this.OptionBundle, this.Values.ToArray(this.ParameterType.GetElementType()), null); - } - else + fieldInfo.SetValue(OptionBundle, Values.ToArray(ParameterType.GetElementType())); + } + else if (MemberInfo is PropertyInfo propertyInfo) + { + propertyInfo.SetValue(OptionBundle, Values.ToArray(ParameterType.GetElementType()), null); + } + else + { + object[] objArray1 = { Values.ToArray(ParameterType.GetElementType()) } ; + if ((WhatToDoNext) ((MethodInfo) MemberInfo).Invoke(OptionBundle, objArray1) == WhatToDoNext.AbandonProgram) { - object[] objArray1 = new object[] { this.Values.ToArray(this.ParameterType.GetElementType()) } ; - if (((WhatToDoNext) ((MethodInfo) this.MemberInfo).Invoke(this.OptionBundle, objArray1)) == WhatToDoNext.AbandonProgram) - { - Environment.Exit(1); - } + Environment.Exit(1); } } } - private static Type TypeOfMember(System.Reflection.MemberInfo memberInfo) + static Type TypeOfMember(MemberInfo memberInfo) { - if ((memberInfo.MemberType == MemberTypes.Field) && (memberInfo is FieldInfo)) + if (memberInfo.MemberType == MemberTypes.Field && memberInfo is FieldInfo fieldInfo) { - return ((FieldInfo) memberInfo).FieldType; + return fieldInfo.FieldType; } - if ((memberInfo.MemberType == MemberTypes.Property) && (memberInfo is PropertyInfo)) + if (memberInfo.MemberType == MemberTypes.Property && memberInfo is PropertyInfo propertyInfo) { - return ((PropertyInfo) memberInfo).PropertyType; + return propertyInfo.PropertyType; } - if ((memberInfo.MemberType == MemberTypes.Method) && (memberInfo is MethodInfo)) + if (memberInfo.MemberType == MemberTypes.Method && memberInfo is MethodInfo methodInfo) { - if (((MethodInfo) memberInfo).ReturnType.FullName != typeof(WhatToDoNext).FullName) + if (methodInfo.ReturnType.FullName != typeof(WhatToDoNext).FullName) { throw new NotSupportedException("Option method must return '" + typeof(WhatToDoNext).FullName + "'"); } - ParameterInfo[] infoArray1 = ((MethodInfo) memberInfo).GetParameters(); - if ((infoArray1 != null) && (infoArray1.Length != 0)) - { - return infoArray1[0].ParameterType; - } - return null; + var infoArray1 = methodInfo.GetParameters(); + return infoArray1.Length != 0 ? infoArray1[0].ParameterType : null; } throw new NotSupportedException("'" + memberInfo.MemberType + "' memberType is not supported"); } - // Properties public string DefaultForm { get { string text1 = "-"; - string text2 = this.linuxLongPrefix; - if (this.parsingMode == OptionsParsingMode.Windows) + string text2 = linuxLongPrefix; + if (parsingMode == OptionsParsingMode.Windows) { text1 = "/"; text2 = "/"; } - if (this.ShortForm != string.Empty) + if (ShortForm != string.Empty) { - return (text1 + this.ShortForm); + return text1 + ShortForm; } - return (text2 + this.LongForm); + return text2 + LongForm; } } - internal string Key - { - get - { - return (this.LongForm + " " + this.ShortForm); - } - } + internal string Key => LongForm + " " + ShortForm; - private string linuxLongPrefix - { - get - { - return (((this.parsingMode & OptionsParsingMode.GNU_DoubleDash) != OptionsParsingMode.GNU_DoubleDash) ? "-" : "--"); - } - } + string linuxLongPrefix => (parsingMode & OptionsParsingMode.GNU_DoubleDash) != OptionsParsingMode.GNU_DoubleDash ? "-" : "--"; - public string ParamName - { - get - { - return this.paramName; - } - } - - private OptionsParsingMode parsingMode - { - get - { - return this.OptionBundle.ParsingMode; - } - } + public string ParamName => paramName; + OptionsParsingMode parsingMode => OptionBundle.ParsingMode; // Fields public string AlternateForm; public bool BooleanOption; public string LongForm; public int MaxOccurs; - public System.Reflection.MemberInfo MemberInfo; + public MemberInfo MemberInfo; public bool NeedsParameter; public int Occurs; public Options OptionBundle; - private string optionHelp; + string optionHelp; public Type ParameterType; public string paramName; public bool SecondLevelHelp; @@ -409,5 +363,4 @@ private OptionsParsingMode parsingMode public bool VBCStyleBoolean; public static bool Verbose; } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/GetOptions/OptionList.cs b/External/Tools/FDBuild/Mono/GetOptions/OptionList.cs index 85169a7fc8..e4192b6fcd 100644 --- a/External/Tools/FDBuild/Mono/GetOptions/OptionList.cs +++ b/External/Tools/FDBuild/Mono/GetOptions/OptionList.cs @@ -1,3 +1,6 @@ +using System.Collections.Generic; +using System.Linq; + namespace Mono.GetOptions { using Mono; @@ -13,23 +16,23 @@ public class OptionList public OptionList(Options optionBundle) { this.optionBundle = null; - this.appTitle = "Add a [assembly: AssemblyTitle(\"Here goes the application name\")] to your assembly"; - this.appCopyright = "Add a [assembly: AssemblyCopyright(\"(c)200n Here goes the copyright holder name\")] to your assembly"; - this.appDescription = "Add a [assembly: AssemblyDescription(\"Here goes the short description\")] to your assembly"; - this.appAboutDetails = "Add a [assembly: Mono.About(\"Here goes the short about details\")] to your assembly"; - this.appUsageComplement = "Add a [assembly: Mono.UsageComplement(\"Here goes the usage clause complement\")] to your assembly"; - this.list = new ArrayList(); - this.arguments = new ArrayList(); - this.argumentsTail = new ArrayList(); - this.argumentProcessor = null; - this.HasSecondLevelHelp = false; - this.bannerAlreadyShown = false; - this.Initialize(optionBundle); + appTitle = "Add a [assembly: AssemblyTitle(\"Here goes the application name\")] to your assembly"; + appCopyright = "Add a [assembly: AssemblyCopyright(\"(c)200n Here goes the copyright holder name\")] to your assembly"; + appDescription = "Add a [assembly: AssemblyDescription(\"Here goes the short description\")] to your assembly"; + appAboutDetails = "Add a [assembly: Mono.About(\"Here goes the short about details\")] to your assembly"; + appUsageComplement = "Add a [assembly: Mono.UsageComplement(\"Here goes the usage clause complement\")] to your assembly"; + list = new List(); + arguments = new List(); + argumentsTail = new List(); + argumentProcessor = null; + HasSecondLevelHelp = false; + bannerAlreadyShown = false; + Initialize(optionBundle); } - private void AddArgumentProcessor(MemberInfo memberInfo) + void AddArgumentProcessor(MemberInfo memberInfo) { - if (this.argumentProcessor != null) + if (argumentProcessor != null) { throw new NotSupportedException("More than one argument processor method found"); } @@ -42,45 +45,44 @@ private void AddArgumentProcessor(MemberInfo memberInfo) throw new NotSupportedException("Argument processor method must return 'void'"); } ParameterInfo[] infoArray1 = ((MethodInfo) memberInfo).GetParameters(); - if (((infoArray1 == null) || (infoArray1.Length != 1)) || (infoArray1[0].ParameterType.FullName != typeof(string).FullName)) + if (((infoArray1 is null) || (infoArray1.Length != 1)) || (infoArray1[0].ParameterType.FullName != typeof(string).FullName)) { throw new NotSupportedException("Argument processor method must have a string parameter"); } - this.argumentProcessor = (MethodInfo) memberInfo; + argumentProcessor = (MethodInfo) memberInfo; } internal WhatToDoNext DoAbout() { - this.ShowAbout(); + ShowAbout(); return WhatToDoNext.AbandonProgram; } internal WhatToDoNext DoHelp() { - this.ShowHelp(false); + ShowHelp(false); return WhatToDoNext.AbandonProgram; } internal WhatToDoNext DoHelp2() { - this.ShowHelp(true); + ShowHelp(true); return WhatToDoNext.AbandonProgram; } internal WhatToDoNext DoUsage() { - this.ShowUsage(); + ShowUsage(); return WhatToDoNext.AbandonProgram; } public string[] ExpandResponseFiles(string[] args) { - ArrayList list1 = new ArrayList(); - string[] textArray1 = args; - for (int num1 = 0; num1 < textArray1.Length; num1++) + var list1 = new List(); + var textArray1 = args; + foreach (var text1 in textArray1) { - string text1 = textArray1[num1]; - if (text1.StartsWith("@")) + if (text1.StartsWith("@", StringComparison.Ordinal)) { try { @@ -88,7 +90,7 @@ public string[] ExpandResponseFiles(string[] args) StreamReader reader1 = new StreamReader(text1.Substring(1)); while ((text2 = reader1.ReadLine()) != null) { - list1.AddRange(text2.Split(new char[0])); + list1.AddRange(text2.Split()); } reader1.Close(); } @@ -107,95 +109,76 @@ public string[] ExpandResponseFiles(string[] args) list1.Add(text1); } } - return (string[]) list1.ToArray(typeof(string)); + return list1.ToArray(); } - private object[] GetAssemblyAttributes(Type type) - { - return this.entry.GetCustomAttributes(type, false); - } + object[] GetAssemblyAttributes(Type type) => entry.GetCustomAttributes(type, false); - private string[] GetAssemblyAttributeStrings(Type type) + string[] GetAssemblyAttributeStrings(Type type) { - object[] objArray1 = this.GetAssemblyAttributes(type); - if ((objArray1 == null) || (objArray1.Length == 0)) - { - return new string[0]; - } - int num1 = 0; - string[] textArray1 = new string[objArray1.Length]; - object[] objArray2 = objArray1; - for (int num2 = 0; num2 < objArray2.Length; num2++) + var objArray1 = GetAssemblyAttributes(type); + if ((objArray1 is null) || (objArray1.Length == 0)) { - object obj1 = objArray2[num2]; - textArray1[num1++] = obj1.ToString(); + return Array.Empty(); } - return textArray1; + return objArray1.Select(static it => it.ToString()).ToArray(); } - private void GetAssemblyAttributeValue(Type type, ref string var) + void GetAssemblyAttributeValue(Type type, ref string var) { - object[] objArray1 = this.GetAssemblyAttributes(type); - if ((objArray1 != null) && (objArray1.Length > 0)) + object[] objArray1 = GetAssemblyAttributes(type); + if (objArray1 != null && objArray1.Length > 0) { var = objArray1[0].ToString(); } } - private void GetAssemblyAttributeValue(Type type, string propertyName, ref string var) + void GetAssemblyAttributeValue(Type type, string propertyName, ref string var) { - object[] objArray1 = this.GetAssemblyAttributes(type); - if ((objArray1 != null) && (objArray1.Length > 0)) + object[] objArray1 = GetAssemblyAttributes(type); + if (objArray1 != null && objArray1.Length > 0) { - var = (string) type.InvokeMember(propertyName, BindingFlags.GetProperty | (BindingFlags.GetField | (BindingFlags.Public | BindingFlags.Instance)), null, objArray1[0], new object[0]); + var = (string) type.InvokeMember(propertyName, BindingFlags.GetProperty | (BindingFlags.GetField | (BindingFlags.Public | BindingFlags.Instance)), null, objArray1[0], Array.Empty()); } } - private static int IndexOfAny(string where, params char[] what) - { - return where.IndexOfAny(what); - } + static int IndexOfAny(string where, params char[] what) => where.IndexOfAny(what); - private void Initialize(Options optionBundle) + void Initialize(Options optionBundle) { - if (optionBundle == null) - { - throw new ArgumentNullException("optionBundle"); - } - this.entry = Assembly.GetEntryAssembly(); - this.appExeName = this.entry.GetName().Name; - this.appVersion = this.entry.GetName().Version.ToString(); - this.optionBundle = optionBundle; - this.parsingMode = optionBundle.ParsingMode; - this.breakSingleDashManyLettersIntoManyOptions = optionBundle.BreakSingleDashManyLettersIntoManyOptions; - this.endOptionProcessingWithDoubleDash = optionBundle.EndOptionProcessingWithDoubleDash; - this.GetAssemblyAttributeValue(typeof(AssemblyTitleAttribute), "Title", ref this.appTitle); - this.GetAssemblyAttributeValue(typeof(AssemblyCopyrightAttribute), "Copyright", ref this.appCopyright); - this.GetAssemblyAttributeValue(typeof(AssemblyDescriptionAttribute), "Description", ref this.appDescription); - this.GetAssemblyAttributeValue(typeof(AboutAttribute), ref this.appAboutDetails); - this.GetAssemblyAttributeValue(typeof(UsageComplementAttribute), ref this.appUsageComplement); - this.appAuthors = this.GetAssemblyAttributeStrings(typeof(AuthorAttribute)); - if (this.appAuthors.Length == 0) + entry = Assembly.GetEntryAssembly(); + appExeName = entry.GetName().Name; + appVersion = entry.GetName().Version.ToString(); + this.optionBundle = optionBundle ?? throw new ArgumentNullException(nameof(optionBundle)); + parsingMode = optionBundle.ParsingMode; + breakSingleDashManyLettersIntoManyOptions = optionBundle.BreakSingleDashManyLettersIntoManyOptions; + endOptionProcessingWithDoubleDash = optionBundle.EndOptionProcessingWithDoubleDash; + GetAssemblyAttributeValue(typeof(AssemblyTitleAttribute), "Title", ref appTitle); + GetAssemblyAttributeValue(typeof(AssemblyCopyrightAttribute), "Copyright", ref appCopyright); + GetAssemblyAttributeValue(typeof(AssemblyDescriptionAttribute), "Description", ref appDescription); + GetAssemblyAttributeValue(typeof(AboutAttribute), ref appAboutDetails); + GetAssemblyAttributeValue(typeof(UsageComplementAttribute), ref appUsageComplement); + appAuthors = GetAssemblyAttributeStrings(typeof(AuthorAttribute)); + if (appAuthors.Length == 0) { - this.appAuthors = new string[] { "Add one or more [assembly: Mono.GetOptions.Author(\"Here goes the author name\")] to your assembly" } ; + appAuthors = new[] { "Add one or more [assembly: Mono.GetOptions.Author(\"Here goes the author name\")] to your assembly" } ; } MemberInfo[] infoArray1 = optionBundle.GetType().GetMembers(); - for (int num1 = 0; num1 < infoArray1.Length; num1++) + foreach (var info1 in infoArray1) { - MemberInfo info1 = infoArray1[num1]; object[] objArray1 = info1.GetCustomAttributes(typeof(OptionAttribute), true); - if ((objArray1 != null) && (objArray1.Length > 0)) + if (objArray1.Length > 0) { OptionDetails details1 = new OptionDetails(info1, (OptionAttribute) objArray1[0], optionBundle); - this.list.Add(details1); - this.HasSecondLevelHelp = this.HasSecondLevelHelp || details1.SecondLevelHelp; + list.Add(details1); + HasSecondLevelHelp = HasSecondLevelHelp || details1.SecondLevelHelp; } else { objArray1 = info1.GetCustomAttributes(typeof(ArgumentProcessorAttribute), true); - if ((objArray1 != null) && (objArray1.Length > 0)) + if (objArray1.Length > 0) { - this.AddArgumentProcessor(info1); + AddArgumentProcessor(info1); } } } @@ -203,26 +186,25 @@ private void Initialize(Options optionBundle) internal bool MaybeAnOption(string arg) { - return ((((this.parsingMode & OptionsParsingMode.Windows) > ((OptionsParsingMode) 0)) && (arg[0] == '/')) || (((this.parsingMode & OptionsParsingMode.Linux) > ((OptionsParsingMode) 0)) && (arg[0] == '-'))); + return (((parsingMode & OptionsParsingMode.Windows) > 0) && (arg[0] == '/')) || (((parsingMode & OptionsParsingMode.Linux) > 0) && (arg[0] == '-')); } public string[] NormalizeArgs(string[] args) { - bool flag1 = true; - ArrayList list1 = new ArrayList(); - string[] textArray1 = this.ExpandResponseFiles(args); - for (int num2 = 0; num2 < textArray1.Length; num2++) + var flag1 = true; + var list1 = new List(); + var textArray1 = ExpandResponseFiles(args); + foreach (var text1 in textArray1) { - string text1 = textArray1[num2]; if (text1.Length > 0) { if (flag1) { - if (this.endOptionProcessingWithDoubleDash && (text1 == "--")) + if (endOptionProcessingWithDoubleDash && (text1 == "--")) { flag1 = false; } - else if (((((this.parsingMode & OptionsParsingMode.Linux) > ((OptionsParsingMode) 0)) && (text1[0] == '-')) && ((text1.Length > 1) && (text1[1] != '-'))) && this.breakSingleDashManyLettersIntoManyOptions) + else if (((parsingMode & OptionsParsingMode.Linux) > 0) && (text1[0] == '-') && ((text1.Length > 1) && (text1[1] != '-')) && breakSingleDashManyLettersIntoManyOptions) { CharEnumerator enumerator1 = text1.Substring(1).GetEnumerator(); while (true) @@ -237,12 +219,12 @@ public string[] NormalizeArgs(string[] args) } else { - if (!this.MaybeAnOption(text1)) + if (!MaybeAnOption(text1)) { goto Label_014D; } - char[] chArray1 = new char[] { ':', '=' } ; - int num1 = OptionList.IndexOfAny(text1, chArray1); + char[] chArray1 = { ':', '=' } ; + int num1 = IndexOfAny(text1, chArray1); if (num1 < 0) { list1.Add(text1); @@ -254,21 +236,21 @@ public string[] NormalizeArgs(string[] args) } else { - this.argumentsTail.Add(text1); + argumentsTail.Add(text1); } } goto Label_0155; - Label_014D: + Label_014D: list1.Add(text1); - Label_0155:; + Label_0155:; } - return (string[]) list1.ToArray(typeof(string)); + return list1.ToArray(); } public string[] ProcessArgs(string[] args) { - this.list.Sort(); - args = this.NormalizeArgs(args); + list.Sort(); + args = NormalizeArgs(args); try { int num1 = args.Length; @@ -285,11 +267,11 @@ public string[] ProcessArgs(string[] args) text1 = null; } bool flag1 = false; - if ((text2.Length <= 1) || (!text2.StartsWith("-") && !text2.StartsWith("/"))) + if ((text2.Length <= 1) || (!text2.StartsWith("-", StringComparison.Ordinal) && !text2.StartsWith("/", StringComparison.Ordinal))) { goto Label_00DA; } - IEnumerator enumerator1 = this.list.GetEnumerator(); + IEnumerator enumerator1 = list.GetEnumerator(); Label_0078: try { @@ -311,18 +293,15 @@ public string[] ProcessArgs(string[] args) finally { IDisposable disposable1 = enumerator1 as IDisposable; - if (disposable1 != null) - { - disposable1.Dispose(); - } + disposable1?.Dispose(); } Label_00DA: if (!flag1) { - this.ProcessNonOption(text2); + ProcessNonOption(text2); } } - IEnumerator enumerator2 = this.list.GetEnumerator(); + IEnumerator enumerator2 = list.GetEnumerator(); Label_0102: try { @@ -336,31 +315,25 @@ public string[] ProcessArgs(string[] args) finally { IDisposable disposable2 = enumerator2 as IDisposable; - if (disposable2 != null) - { - disposable2.Dispose(); - } + disposable2?.Dispose(); } - IEnumerator enumerator3 = this.argumentsTail.GetEnumerator(); + IEnumerator enumerator3 = argumentsTail.GetEnumerator(); Label_0151: try { if (enumerator3.MoveNext()) { string text3 = (string) enumerator3.Current; - this.ProcessNonOption(text3); + ProcessNonOption(text3); goto Label_0151; } } finally { IDisposable disposable3 = enumerator3 as IDisposable; - if (disposable3 != null) - { - disposable3.Dispose(); - } + disposable3?.Dispose(); } - return (string[]) this.arguments.ToArray(typeof(string)); + return arguments.ToArray(); } catch (Exception exception1) { @@ -370,33 +343,32 @@ public string[] ProcessArgs(string[] args) return null; } - private void ProcessNonOption(string argument) + void ProcessNonOption(string argument) { if (OptionDetails.Verbose) { Console.WriteLine("argument [" + argument + "]"); } - if (this.argumentProcessor == null) + if (argumentProcessor is null) { - this.arguments.Add(argument); + arguments.Add(argument); } else { - object[] objArray1 = new object[] { argument } ; - this.argumentProcessor.Invoke(this.optionBundle, objArray1); + object[] objArray1 = { argument } ; + argumentProcessor.Invoke(optionBundle, objArray1); } } - private void ShowAbout() + void ShowAbout() { - this.ShowTitleLines(); - Console.WriteLine(this.appAboutDetails); + ShowTitleLines(); + Console.WriteLine(appAboutDetails); StringBuilder builder1 = new StringBuilder("Authors: "); bool flag1 = true; - string[] textArray1 = this.appAuthors; - for (int num1 = 0; num1 < textArray1.Length; num1++) + string[] textArray1 = appAuthors; + foreach (var text1 in textArray1) { - string text1 = textArray1[num1]; if (flag1) { flag1 = false; @@ -412,36 +384,34 @@ private void ShowAbout() public void ShowBanner() { - if (!this.bannerAlreadyShown) + if (!bannerAlreadyShown) { - string[] textArray1 = new string[] { this.appTitle, " ", this.appVersion, " - ", this.appCopyright } ; + string[] textArray1 = { appTitle, " ", appVersion, " - ", appCopyright } ; Console.WriteLine(string.Concat(textArray1)); } - this.bannerAlreadyShown = true; + bannerAlreadyShown = true; } - private void ShowHelp(bool showSecondLevelHelp) + void ShowHelp(bool showSecondLevelHelp) { - this.ShowTitleLines(); - Console.WriteLine(this.Usage); + ShowTitleLines(); + Console.WriteLine(Usage); Console.WriteLine("Options:"); - ArrayList list1 = new ArrayList(this.list.Count); - int num1 = 0; - IEnumerator enumerator1 = this.list.GetEnumerator(); + var list1 = new List(list.Count); + var num1 = 0; + var enumerator1 = list.GetEnumerator(); Label_003B: try { if (enumerator1.MoveNext()) { - OptionDetails details1 = (OptionDetails) enumerator1.Current; + OptionDetails details1 = enumerator1.Current; if (details1.SecondLevelHelp == showSecondLevelHelp) { - char[] chArray1 = new char[] { '\n' } ; - string[] textArray1 = details1.ToString().Split(chArray1); + string[] textArray1 = details1.ToString().Split('\n'); string[] textArray3 = textArray1; - for (int num4 = 0; num4 < textArray3.Length; num4++) + foreach (var text1 in textArray3) { - string text1 = textArray3[num4]; int num2 = text1.IndexOf('\t'); if (num2 > num1) { @@ -455,11 +425,8 @@ private void ShowHelp(bool showSecondLevelHelp) } finally { - IDisposable disposable1 = enumerator1 as IDisposable; - if (disposable1 != null) - { - disposable1.Dispose(); - } + IDisposable disposable1 = enumerator1; + disposable1?.Dispose(); } num1 += 2; IEnumerator enumerator2 = list1.GetEnumerator(); @@ -471,8 +438,7 @@ private void ShowHelp(bool showSecondLevelHelp) return; } string text2 = (string) enumerator2.Current; - char[] chArray2 = new char[] { '\t' } ; - string[] textArray2 = text2.Split(chArray2); + string[] textArray2 = text2.Split('\t'); Console.Write(textArray2[0].PadRight(num1)); Console.WriteLine(textArray2[1]); if (textArray2.Length > 2) @@ -489,25 +455,22 @@ private void ShowHelp(bool showSecondLevelHelp) finally { IDisposable disposable2 = enumerator2 as IDisposable; - if (disposable2 != null) - { - disposable2.Dispose(); - } + disposable2?.Dispose(); } } - private void ShowTitleLines() + void ShowTitleLines() { - this.ShowBanner(); - Console.WriteLine(this.appDescription); + ShowBanner(); + Console.WriteLine(appDescription); Console.WriteLine(); } - private void ShowUsage() + void ShowUsage() { - Console.WriteLine(this.Usage); + Console.WriteLine(Usage); Console.Write("Short Options: "); - IEnumerator enumerator1 = this.list.GetEnumerator(); + IEnumerator enumerator1 = list.GetEnumerator(); Label_0021: try { @@ -521,59 +484,43 @@ private void ShowUsage() finally { IDisposable disposable1 = enumerator1 as IDisposable; - if (disposable1 != null) - { - disposable1.Dispose(); - } + disposable1?.Dispose(); } Console.WriteLine(); } - private void ShowUsage(string errorMessage) + void ShowUsage(string errorMessage) { - Console.WriteLine("ERROR: " + errorMessage.TrimEnd(new char[0])); - this.ShowUsage(); + Console.WriteLine("ERROR: " + errorMessage.TrimEnd()); + ShowUsage(); } // Properties - public string AboutDetails - { - get - { - return this.appAboutDetails; - } - } + public string AboutDetails => appAboutDetails; - public string Usage - { - get - { - return ("Usage: " + this.appExeName + " [options] " + this.appUsageComplement); - } - } + public string Usage => ("Usage: " + appExeName + " [options] " + appUsageComplement); // Fields - private string appAboutDetails; - private string[] appAuthors; - private string appCopyright; - private string appDescription; - private string appExeName; - private string appTitle; - private string appUsageComplement; - private string appVersion; - private MethodInfo argumentProcessor; - private ArrayList arguments; - private ArrayList argumentsTail; - private bool bannerAlreadyShown; - private bool breakSingleDashManyLettersIntoManyOptions; - private bool endOptionProcessingWithDoubleDash; - private Assembly entry; - private bool HasSecondLevelHelp; - private ArrayList list; - private Options optionBundle; - private OptionsParsingMode parsingMode; + string appAboutDetails; + string[] appAuthors; + string appCopyright; + string appDescription; + string appExeName; + string appTitle; + string appUsageComplement; + string appVersion; + MethodInfo argumentProcessor; + readonly List arguments; + readonly List argumentsTail; + bool bannerAlreadyShown; + bool breakSingleDashManyLettersIntoManyOptions; + bool endOptionProcessingWithDoubleDash; + Assembly entry; + bool HasSecondLevelHelp; + readonly List list; + Options optionBundle; + OptionsParsingMode parsingMode; } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/GetOptions/OptionProcessingResult.cs b/External/Tools/FDBuild/Mono/GetOptions/OptionProcessingResult.cs index 2c9dd8ac8f..7e43107bbc 100644 --- a/External/Tools/FDBuild/Mono/GetOptions/OptionProcessingResult.cs +++ b/External/Tools/FDBuild/Mono/GetOptions/OptionProcessingResult.cs @@ -1,12 +1,9 @@ namespace Mono.GetOptions { - using System; - - internal enum OptionProcessingResult + enum OptionProcessingResult { NotThisOption, OptionAlone, OptionConsumedParameter } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/GetOptions/Options.cs b/External/Tools/FDBuild/Mono/GetOptions/Options.cs index 2bbd10fa2f..5200ff6526 100644 --- a/External/Tools/FDBuild/Mono/GetOptions/Options.cs +++ b/External/Tools/FDBuild/Mono/GetOptions/Options.cs @@ -1,64 +1,42 @@ namespace Mono.GetOptions { - using System; - public class Options { // Methods public Options() { - this.ParsingMode = OptionsParsingMode.Both; - this.BreakSingleDashManyLettersIntoManyOptions = false; - this.EndOptionProcessingWithDoubleDash = true; + ParsingMode = OptionsParsingMode.Both; + BreakSingleDashManyLettersIntoManyOptions = false; + EndOptionProcessingWithDoubleDash = true; } [Option("Display version and licensing information", 'V', "version")] - public virtual WhatToDoNext DoAbout() - { - return this.optionParser.DoAbout(); - } + public virtual WhatToDoNext DoAbout() => optionParser.DoAbout(); [Option("Show this help list", '?', "help")] - public virtual WhatToDoNext DoHelp() - { - return this.optionParser.DoHelp(); - } + public virtual WhatToDoNext DoHelp() => optionParser.DoHelp(); [Option("Show an additional help list", "help2")] - public virtual WhatToDoNext DoHelp2() - { - return this.optionParser.DoHelp2(); - } + public virtual WhatToDoNext DoHelp2() => optionParser.DoHelp2(); [Option("Show usage syntax and exit", "usage")] - public virtual WhatToDoNext DoUsage() - { - return this.optionParser.DoUsage(); - } + public virtual WhatToDoNext DoUsage() => optionParser.DoUsage(); public void ProcessArgs(string[] args) { - this.optionParser = new OptionList(this); - this.RemainingArguments = this.optionParser.ProcessArgs(args); - } - - public void ShowBanner() - { - this.optionParser.ShowBanner(); + optionParser = new OptionList(this); + RemainingArguments = optionParser.ProcessArgs(args); } + public void ShowBanner() => optionParser.ShowBanner(); // Properties [Option("Show verbose parsing of options", "verbosegetoptions", SecondLevelHelp=true)] public bool VerboseParsingOfOptions { - set - { - OptionDetails.Verbose = value; - } + set => OptionDetails.Verbose = value; } - - + // Fields public bool BreakSingleDashManyLettersIntoManyOptions; public bool EndOptionProcessingWithDoubleDash; @@ -66,5 +44,4 @@ public bool VerboseParsingOfOptions public OptionsParsingMode ParsingMode; public string[] RemainingArguments; } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/GetOptions/OptionsParsingMode.cs b/External/Tools/FDBuild/Mono/GetOptions/OptionsParsingMode.cs index c4db33ff44..0b8bd3c16a 100644 --- a/External/Tools/FDBuild/Mono/GetOptions/OptionsParsingMode.cs +++ b/External/Tools/FDBuild/Mono/GetOptions/OptionsParsingMode.cs @@ -11,5 +11,4 @@ public enum OptionsParsingMode Linux = 1, Windows = 2 } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/GetOptions/WhatToDoNext.cs b/External/Tools/FDBuild/Mono/GetOptions/WhatToDoNext.cs index 2b697d0405..e53eba76a4 100644 --- a/External/Tools/FDBuild/Mono/GetOptions/WhatToDoNext.cs +++ b/External/Tools/FDBuild/Mono/GetOptions/WhatToDoNext.cs @@ -1,11 +1,8 @@ namespace Mono.GetOptions { - using System; - public enum WhatToDoNext { AbandonProgram, GoAhead } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Mono/UsageComplementAttribute.cs b/External/Tools/FDBuild/Mono/UsageComplementAttribute.cs index dca2d8782f..0eff668977 100644 --- a/External/Tools/FDBuild/Mono/UsageComplementAttribute.cs +++ b/External/Tools/FDBuild/Mono/UsageComplementAttribute.cs @@ -8,17 +8,13 @@ public class UsageComplementAttribute : Attribute // Methods public UsageComplementAttribute(string details) { - this.Details = details; + Details = details; } - public override string ToString() - { - return this.Details; - } + public override string ToString() => Details; // Fields public string Details; } -} - +} \ No newline at end of file diff --git a/External/Tools/FDBuild/Program.cs b/External/Tools/FDBuild/Program.cs index 4f00c67041..a8c7c9bd0e 100644 --- a/External/Tools/FDBuild/Program.cs +++ b/External/Tools/FDBuild/Program.cs @@ -1,11 +1,11 @@ using System; -using System.Reflection; using System.IO; using ProjectManager.Projects; using ProjectManager.Building; using ProjectManager.Building.AS3; using FDBuild.Building; using System.Text; +using PluginCore.Helpers; namespace FDBuild @@ -30,13 +30,13 @@ public static int Main(string[] args) Environment.CurrentDirectory = Path.GetDirectoryName(options.ProjectFile); string directory = Environment.CurrentDirectory; string toolsDir = Path.GetDirectoryName(ProjectPaths.ApplicationDirectory); + string firstRunDir = Path.GetDirectoryName(toolsDir); // try and automagically figure out flashdevelop's library path // it should be at ..\..\Library - if (options.LibraryDir == null) + if (options.LibraryDir is null) try { - string firstRunDir = Path.GetDirectoryName(toolsDir); string libraryDir = Path.Combine(firstRunDir, "Library"); if (Directory.Exists(libraryDir)) options.LibraryDir = libraryDir; @@ -44,10 +44,25 @@ public static int Main(string[] args) catch { } string swfmillPath = options.SwfmillPath ?? Path.Combine(toolsDir, "swfmill"); - if (File.Exists(Path.Combine(swfmillPath, "swfmill.exe"))) + if (PlatformHelper.IsRunningOnWindows() && File.Exists(Path.Combine(swfmillPath, "swfmill.exe"))) SwfmillLibraryBuilder.ExecutablePath = Path.Combine(swfmillPath, "swfmill.exe"); + else if (!PlatformHelper.IsRunningOnWindows() && File.Exists(Path.Combine(swfmillPath, "swfmill"))) + SwfmillLibraryBuilder.ExecutablePath = Path.Combine(swfmillPath, "swfmill"); else - SwfmillLibraryBuilder.ExecutablePath = "swfmill.exe"; // hope you have it in your environment path! + SwfmillLibraryBuilder.ExecutablePath = "swfmill"; // hope you have it in your environment path! + + // figure user settings PlatformData + string platformsFile = Path.Combine("Settings", "Platforms"); + if (File.Exists(Path.Combine(firstRunDir, ".local"))) + { + PluginCore.PlatformData.Load(Path.Combine(firstRunDir, platformsFile)); + } + else + { + string userAppDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + string fdDir = Path.Combine(userAppDir, PluginCore.DistroConfig.DISTRIBUTION_NAME); + PluginCore.PlatformData.Load(Path.Combine(fdDir, platformsFile)); + } try { @@ -116,10 +131,10 @@ public static void Build(string projectFile, FDBuildOptions options) public static void BuildProject(string projectFile) { Project project = ProjectLoader.Load(projectFile); - Program.BuildOptions.Language = project.Language.ToUpper(); + BuildOptions.Language = project.Language.ToUpper(); - ProjectBuilder builder = ProjectBuilder.Create(project, Program.BuildOptions.IpcName, Program.BuildOptions.CompilerPath); - builder.BuildCommand(Program.BuildOptions.ExtraClasspaths, Program.BuildOptions.NoTrace); + ProjectBuilder builder = ProjectBuilder.Create(project, BuildOptions.IpcName, BuildOptions.CompilerPath); + builder.BuildCommand(BuildOptions.ExtraClasspaths, BuildOptions.NoTrace); } /// @@ -127,24 +142,15 @@ public static void BuildProject(string projectFile) /// /// the working directory for fsch, to have full optimization make this the same for all calls /// the mxmlc arguments - public static void BuildMXMLC( string workingdir, string arguments ) + public static void BuildMXMLC(string workingdir, string arguments) { - //Project project = ProjectLoader.Load(projectFile); - //Program.BuildOptions.Language = project.Language.ToUpper(); - - AS3ProjectBuilder builder = new AS3ProjectBuilder(null, Program.BuildOptions.CompilerPath, Program.BuildOptions.IpcName); - builder.CompileWithMxmlc(workingdir, arguments, true); - + AS3ProjectBuilder builder = new AS3ProjectBuilder(null, BuildOptions.CompilerPath, BuildOptions.IpcName); + builder.CompileWithMxmlc(workingdir, arguments); } /// /// Build from pre/post command: compc /// - /// the working directory for fsch, to have full optimization make this the same for all calls - /// the compc arguments - public static void BuildCOMPC( string workingdir, string arguments ) - { - AS3ProjectBuilder builder = new AS3ProjectBuilder(null, Program.BuildOptions.CompilerPath, Program.BuildOptions.IpcName); - } + public static void BuildCOMPC() => new AS3ProjectBuilder(null, BuildOptions.CompilerPath, BuildOptions.IpcName); } } diff --git a/External/Tools/IGen/ASClassParser.cs b/External/Tools/IGen/ASClassParser.cs index 81a8fb6bce..451befbefb 100644 --- a/External/Tools/IGen/ASClassParser.cs +++ b/External/Tools/IGen/ASClassParser.cs @@ -11,553 +11,553 @@ namespace ASCompletion { - /// - /// Actionscript class parser - /// - public class ASClassParser - { - #region interface with application - static private IASContext context; - - static public IASContext Context - { - get { return context; } - set { context = value; } - } - #endregion - - #region regular_expressions_definitions - static public readonly RegexOptions ro_cm = - RegexOptions.Compiled | RegexOptions.Multiline; - static public readonly RegexOptions ro_cs = - RegexOptions.Compiled | RegexOptions.Singleline; + /// + /// Actionscript class parser + /// + public class ASClassParser + { + #region interface with application + static private IASContext context; + + static public IASContext Context + { + get { return context; } + set { context = value; } + } + #endregion + + #region regular_expressions_definitions + static public readonly RegexOptions ro_cm = + RegexOptions.Compiled | RegexOptions.Multiline; + static public readonly RegexOptions ro_cs = + RegexOptions.Compiled | RegexOptions.Singleline; - // uncommenting source - //static public readonly Regex re_lineAgainstBlocComments = - // new Regex("^(?[^*]*//[^\r\n]*)/\\*", ro_cm); - //new Regex("^(?[^*]*//.*)/\\*", ro_cm); - static public readonly Regex re_blocComments = - new Regex("(?[^\\/])/\\*.*?\\*/", ro_cs); - static public readonly Regex re_lineComments = - new Regex("^(?.*?)//.*$", ro_cm); - static public readonly Regex re_usefullComments = - new Regex("(?[^\\/])(?/\\*\\*.*?\\*/)", ro_cs); - static public readonly Regex re_commentIndex = - new Regex("comment(?[\\d]*)", ro_cs); - static public readonly Regex re_commentContent = - new Regex("^.*\\*(?.*)$", ro_cm); + // uncommenting source + //static public readonly Regex re_lineAgainstBlocComments = + // new Regex("^(?[^*]*//[^\r\n]*)/\\*", ro_cm); + //new Regex("^(?[^*]*//.*)/\\*", ro_cm); + static public readonly Regex re_blocComments = + new Regex("(?[^\\/])/\\*.*?\\*/", ro_cs); + static public readonly Regex re_lineComments = + new Regex("^(?.*?)//.*$", ro_cm); + static public readonly Regex re_usefullComments = + new Regex("(?[^\\/])(?/\\*\\*.*?\\*/)", ro_cs); + static public readonly Regex re_commentIndex = + new Regex("comment(?[\\d]*)", ro_cs); + static public readonly Regex re_commentContent = + new Regex("^.*\\*(?.*)$", ro_cm); - // class parsing - static public readonly Regex re_AS3package = - new Regex("[\\s]*package[\\s]+(?[\\w.]*)[\\s]*{", ro_cs); - static public readonly Regex re_import = - new Regex("^[\\s]*import[\\s]+(?[\\w.]+)", ro_cm); - static public readonly Regex re_class = - new Regex("(?[^;.]*)[\\s]?(?(class|interface))[\\s]+(?[\\w.]+)(?.*?){", ro_cs); - static public readonly Regex re_extends = - new Regex("[\\s]extends[\\s]+(?[\\w.]+)", ro_cs); - static public readonly Regex re_implements = - new Regex("[\\s]implements[\\s]", ro_cs); + // class parsing + static public readonly Regex re_AS3package = + new Regex("[\\s]*package[\\s]+(?[\\w.]*)[\\s]*{", ro_cs); + static public readonly Regex re_import = + new Regex("^[\\s]*import[\\s]+(?[\\w.]+)", ro_cm); + static public readonly Regex re_class = + new Regex("(?[^;.]*)[\\s]?(?(class|interface))[\\s]+(?[\\w.]+)(?.*?){", ro_cs); + static public readonly Regex re_extends = + new Regex("[\\s]extends[\\s]+(?[\\w.]+)", ro_cs); + static public readonly Regex re_implements = + new Regex("[\\s]implements[\\s]", ro_cs); - static public readonly Regex re_functions = - new Regex("[\\w\\s]*[\\s]function[\\s]*[^;]*", ro_cs); - //new Regex(";[\\w\\s]*[\\s]function[\\s]*[^;]*", ro_cs); - static public readonly Regex re_splitFunction = - new Regex("(?[\\w\\s]*)[\\s]function[\\s]*(?[^(]*)\\((?[^()]*)\\)(?.*)", ro_cs); - static public readonly Regex re_parametersSeparator = - new Regex("[\\s]*,[\\s]*", ro_cs); + static public readonly Regex re_functions = + new Regex("[\\w\\s]*[\\s]function[\\s]*[^;]*", ro_cs); + //new Regex(";[\\w\\s]*[\\s]function[\\s]*[^;]*", ro_cs); + static public readonly Regex re_splitFunction = + new Regex("(?[\\w\\s]*)[\\s]function[\\s]*(?[^(]*)\\((?[^()]*)\\)(?.*)", ro_cs); + static public readonly Regex re_parametersSeparator = + new Regex("[\\s]*,[\\s]*", ro_cs); - static public readonly Regex re_variable = - new Regex("[\\w\\s]*[\\s]var[\\s]+[^,;=\r\n]+", ro_cs); - //new Regex("[;{}][\\w\\s]*[\\s]var[\\s]+[^;=]+", ro_cs); - static public readonly Regex re_splitVariable = - new Regex("(?[\\w\\s]*)[\\s]var[\\s]+(?[\\w$]+)(?.*)", ro_cs); - static public readonly Regex re_variableType = - new Regex("[\\s]*:[\\s]*(?[\\w.]+)", ro_cs); - static public readonly Regex re_isGetterSetter = - new Regex("^(?[gs])et[\\s]+(?.+)$", ro_cs); - - // HACK AS3 'const' support - static public readonly Regex re_constant = - new Regex("[\\w\\s]*[\\s]const[\\s]+[^,;=\r\n]+", ro_cs); - static public readonly Regex re_splitConstant = - new Regex("(?[\\w\\s]*)[\\s]const[\\s]+(?[\\w$]+)(?.*)", ro_cs); + static public readonly Regex re_variable = + new Regex("[\\w\\s]*[\\s]var[\\s]+[^,;=\r\n]+", ro_cs); + //new Regex("[;{}][\\w\\s]*[\\s]var[\\s]+[^;=]+", ro_cs); + static public readonly Regex re_splitVariable = + new Regex("(?[\\w\\s]*)[\\s]var[\\s]+(?[\\w$]+)(?.*)", ro_cs); + static public readonly Regex re_variableType = + new Regex("[\\s]*:[\\s]*(?[\\w.]+)", ro_cs); + static public readonly Regex re_isGetterSetter = + new Regex("^(?[gs])et[\\s]+(?.+)$", ro_cs); + + // HACK AS3 'const' support + static public readonly Regex re_constant = + new Regex("[\\w\\s]*[\\s]const[\\s]+[^,;=\r\n]+", ro_cs); + static public readonly Regex re_splitConstant = + new Regex("(?[\\w\\s]*)[\\s]const[\\s]+(?[\\w$]+)(?.*)", ro_cs); - // cleaning - static private readonly Regex re_colonParams = - new Regex("[\\s]*:[\\s]*", ro_cs); + // cleaning + static private readonly Regex re_colonParams = + new Regex("[\\s]*:[\\s]*", ro_cs); - // balanced matching, see: http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx - static public readonly Regex re_balancedBraces = - new Regex("{[^{}]*(((?{)[^{}]*)+((?})[^{}]*)+)*(?(Open)(?!))}", ro_cs); - #endregion + // balanced matching, see: http://blogs.msdn.com/bclteam/archive/2005/03/15/396452.aspx + static public readonly Regex re_balancedBraces = + new Regex("{[^{}]*(((?{)[^{}]*)+((?})[^{}]*)+)*(?(Open)(?!))}", ro_cs); + #endregion - #region main_parseclass_function - /// - /// Parse a class from file - /// - /// Class object - /// Class filename - static public void ParseClass(ASClass aClass) - { - string src; - // read file content - try - { - if (!File.Exists(aClass.FileName)) return; - StreamReader sr = new StreamReader(aClass.FileName); - src = sr.ReadToEnd(); - sr.Close(); - } - catch (Exception ex) - { - context.DisplayError(ex.Message); - return; - } - // parse - ParseClass(aClass, src); - } + #region main_parseclass_function + /// + /// Parse a class from file + /// + /// Class object + /// Class filename + static public void ParseClass(ASClass aClass) + { + string src; + // read file content + try + { + if (!File.Exists(aClass.FileName)) return; + StreamReader sr = new StreamReader(aClass.FileName); + src = sr.ReadToEnd(); + sr.Close(); + } + catch (Exception ex) + { + context.DisplayError(ex.Message); + return; + } + // parse + ParseClass(aClass, src); + } - /// - /// Parse a class from source - /// - /// Class object - /// Class source - static public void ParseClass(ASClass aClass, string src) - { - // remove comments - StringCollection comments = new StringCollection(); - src = CleanClassSource(src, comments); + /// + /// Parse a class from source + /// + /// Class object + /// Class source + static public void ParseClass(ASClass aClass, string src) + { + // remove comments + StringCollection comments = new StringCollection(); + src = CleanClassSource(src, comments); - // check class definition - Match mClass = re_class.Match(src); - if (!mClass.Success) { - aClass.ClassName = null; - return; - } - - // classname - string prevCName = aClass.ClassName; - aClass.ClassName = mClass.Groups["cname"].Value; - - // HACK AS3 package support - string preClassSrc = src.Substring(0,mClass.Groups["ctype"].Index); - string AS3package = null; - Match mPackage = re_AS3package.Match(preClassSrc); - if (mPackage.Success) - { - aClass.IsAS3 = true; - AS3package = mPackage.Groups["name"].Value; - if (AS3package != null && AS3package.Length > 0) - aClass.ClassName = AS3package+"."+aClass.ClassName; - } - else aClass.IsAS3 = false; - - // check classname - int p = aClass.ClassName.LastIndexOf("."); - string constructor = (p >= 0) ? aClass.ClassName.Substring(p+1) : aClass.ClassName; - string classType = mClass.Groups["ctype"].Value; - if (src.Substring(0, mClass.Groups["cname"].Index).IndexOf(" comment0 ") >= 0) - aClass.Comments = comments[0]; + // check class definition + Match mClass = re_class.Match(src); + if (!mClass.Success) { + aClass.ClassName = null; + return; + } + + // classname + string prevCName = aClass.ClassName; + aClass.ClassName = mClass.Groups["cname"].Value; + + // HACK AS3 package support + string preClassSrc = src.Substring(0,mClass.Groups["ctype"].Index); + string AS3package = null; + Match mPackage = re_AS3package.Match(preClassSrc); + if (mPackage.Success) + { + aClass.IsAS3 = true; + AS3package = mPackage.Groups["name"].Value; + if (AS3package != null && AS3package.Length > 0) + aClass.ClassName = AS3package+"."+aClass.ClassName; + } + else aClass.IsAS3 = false; + + // check classname + int p = aClass.ClassName.LastIndexOf("."); + string constructor = (p >= 0) ? aClass.ClassName.Substring(p+1) : aClass.ClassName; + string classType = mClass.Groups["ctype"].Value; + if (src.Substring(0, mClass.Groups["cname"].Index).IndexOf(" comment0 ") >= 0) + aClass.Comments = comments[0]; - // class base path - bool validClassFile = true; - int basepos = aClass.FileName.LastIndexOf( aClass.ClassName.Replace('.', Path.DirectorySeparatorChar)+".as" ); - if (basepos < 0) - { - // this class name & file don't match, it can lead to dangerous errors - validClassFile = false; - // warm about the misspelled class name - if (!aClass.FileName.EndsWith("/"+constructor+".as") - || !aClass.FileName.ToUpper().EndsWith("\\"+aClass.ClassName.ToUpper().Replace('.','\\')+".AS")) - { - if (prevCName != aClass.ClassName) - { - string msg = String.Format("The {0} '{1}' does not match the file name:\n{2}", - classType, - aClass.ClassName, - aClass.FileName); - context.DisplayError(msg); - } - } - aClass.BasePath = System.IO.Path.GetDirectoryName(aClass.FileName)+"\\"; - } - else - { - aClass.BasePath = aClass.FileName.Substring(0, basepos); - } - - // add to classpath - context.SetTemporaryBasePath(aClass.FileName, aClass.BasePath); + // class base path + bool validClassFile = true; + int basepos = aClass.FileName.LastIndexOf( aClass.ClassName.Replace('.', Path.DirectorySeparatorChar)+".as" ); + if (basepos < 0) + { + // this class name & file don't match, it can lead to dangerous errors + validClassFile = false; + // warm about the misspelled class name + if (!aClass.FileName.EndsWith("/"+constructor+".as") + || !aClass.FileName.ToUpper().EndsWith("\\"+aClass.ClassName.ToUpper().Replace('.','\\')+".AS")) + { + if (prevCName != aClass.ClassName) + { + string msg = String.Format("The {0} '{1}' does not match the file name:\n{2}", + classType, + aClass.ClassName, + aClass.FileName); + context.DisplayError(msg); + } + } + aClass.BasePath = System.IO.Path.GetDirectoryName(aClass.FileName)+"\\"; + } + else + { + aClass.BasePath = aClass.FileName.Substring(0, basepos); + } + + // add to classpath + context.SetTemporaryBasePath(aClass.FileName, aClass.BasePath); - // class flag - aClass.Flags = FlagType.Class; - if (classType == "interface") aClass.Flags |= FlagType.Interface; - if (mClass.Groups["keys"].Value.IndexOf("intrinsic") >= 0) aClass.Flags |= FlagType.Intrinsic; - if (mClass.Groups["keys"].Value.IndexOf("dynamic") >= 0) aClass.Flags |= FlagType.Dynamic; + // class flag + aClass.Flags = FlagType.Class; + if (classType == "interface") aClass.Flags |= FlagType.Interface; + if (mClass.Groups["keys"].Value.IndexOf("intrinsic") >= 0) aClass.Flags |= FlagType.Intrinsic; + if (mClass.Groups["keys"].Value.IndexOf("dynamic") >= 0) aClass.Flags |= FlagType.Dynamic; - // import statements - ParseImports(preClassSrc, aClass); - preClassSrc = null; + // import statements + ParseImports(preClassSrc, aClass); + preClassSrc = null; - // inheritance - string herit = mClass.Groups["herit"].Value; - Match mExtends = re_extends.Match(herit); - string extends = (validClassFile && mExtends.Success) ? mExtends.Groups["cname"].ToString() : "Object"; - if ((extends != aClass.ClassName) && (aClass.ClassName != "TopLevel")) - { - aClass.Extends = null; - // resolve extended class - ASClass extendsClass = context.GetClassByName(extends, aClass); - // detect infinite extension loop - ASClass tmpClass = extendsClass; - while (tmpClass != null) - { - if (tmpClass == aClass) - { - string msg = String.Format("The {0} '{1}' extends itself.", - classType, - aClass.ClassName); - context.DisplayError(msg); - extendsClass = null; - break; - } - tmpClass = tmpClass.Extends; - } - if (extendsClass != null) aClass.Extends = extendsClass; - else aClass.Extends = new ASClass(); - } - - Match mImplements = re_implements.Match(herit); - if (mImplements.Success) - { - string implements; - if (!mExtends.Success || mImplements.Index > mExtends.Index) - implements = herit.Substring(mImplements.Index+mImplements.Length).Trim(); - else - implements = herit.Substring(mImplements.Index+mImplements.Length, mExtends.Index-mImplements.Index-mImplements.Length).Trim(); - aClass.Implements = re_parametersSeparator.Replace(implements, ", "); - } - else aClass.Implements = null; - - // clean class body - src = "; "+src.Substring(mClass.Groups["herit"].Index + mClass.Groups["herit"].Value.Length+1); - src = re_balancedBraces.Replace(src, ";"); + // inheritance + string herit = mClass.Groups["herit"].Value; + Match mExtends = re_extends.Match(herit); + string extends = (validClassFile && mExtends.Success) ? mExtends.Groups["cname"].ToString() : "Object"; + if ((extends != aClass.ClassName) && (aClass.ClassName != "TopLevel")) + { + aClass.Extends = null; + // resolve extended class + ASClass extendsClass = context.GetClassByName(extends, aClass); + // detect infinite extension loop + ASClass tmpClass = extendsClass; + while (tmpClass != null) + { + if (tmpClass == aClass) + { + string msg = String.Format("The {0} '{1}' extends itself.", + classType, + aClass.ClassName); + context.DisplayError(msg); + extendsClass = null; + break; + } + tmpClass = tmpClass.Extends; + } + if (extendsClass != null) aClass.Extends = extendsClass; + else aClass.Extends = new ASClass(); + } + + Match mImplements = re_implements.Match(herit); + if (mImplements.Success) + { + string implements; + if (!mExtends.Success || mImplements.Index > mExtends.Index) + implements = herit.Substring(mImplements.Index+mImplements.Length).Trim(); + else + implements = herit.Substring(mImplements.Index+mImplements.Length, mExtends.Index-mImplements.Index-mImplements.Length).Trim(); + aClass.Implements = re_parametersSeparator.Replace(implements, ", "); + } + else aClass.Implements = null; + + // clean class body + src = "; "+src.Substring(mClass.Groups["herit"].Index + mClass.Groups["herit"].Value.Length+1); + src = re_balancedBraces.Replace(src, ";"); - // if updating, clear - aClass.Methods.Clear(); - aClass.Properties.Clear(); - aClass.Vars.Clear(); + // if updating, clear + aClass.Methods.Clear(); + aClass.Properties.Clear(); + aClass.Vars.Clear(); - // parse functions - string keys; - bool isStatic; - MatchCollection mcFunc = re_functions.Matches(src); - Match mFunc; - Match mType; - Match mComments; - ASMember member; - foreach(Match m in mcFunc) - { - mFunc = re_splitFunction.Match(m.Value); - if (!mFunc.Success) continue; - // keywords - keys = mFunc.Groups["keys"].Value; - member = new ASMember(); - member.Flags = FlagType.Function; - if (keys.IndexOf("private") >= 0) member.Flags |= FlagType.Private; - else member.Flags |= FlagType.Public; - isStatic = (keys.IndexOf("static") >= 0); - if (isStatic) member.Flags |= FlagType.Static; - else member.Flags |= FlagType.Dynamic; - // comments - if (comments.Count > 0) - { - mComments = re_commentIndex.Match(keys); - if (mComments.Success) { - member.Comments = comments[ Convert.ToInt16(mComments.Groups["index"].Value) ]; - } - } - // method - member.Name = mFunc.Groups["fname"].Value.Trim(); - if (member.Name.Length == 0) - continue; - // parameters - member.Parameters = re_colonParams.Replace( re_parametersSeparator.Replace(mFunc.Groups["params"].Value.Trim(), ", "), ":"); - // return type - mType = re_variableType.Match(mFunc.Groups["type"].Value); - if (mType.Success) member.Type = mType.Groups["type"].Value; - else member.Type = ""; - // constructor type - if (member.Name == constructor) - { - member.Flags |= FlagType.Constructor; - member.Type = constructor; - } + // parse functions + string keys; + bool isStatic; + MatchCollection mcFunc = re_functions.Matches(src); + Match mFunc; + Match mType; + Match mComments; + ASMember member; + foreach(Match m in mcFunc) + { + mFunc = re_splitFunction.Match(m.Value); + if (!mFunc.Success) continue; + // keywords + keys = mFunc.Groups["keys"].Value; + member = new ASMember(); + member.Flags = FlagType.Function; + if (keys.IndexOf("private") >= 0) member.Flags |= FlagType.Private; + else member.Flags |= FlagType.Public; + isStatic = (keys.IndexOf("static") >= 0); + if (isStatic) member.Flags |= FlagType.Static; + else member.Flags |= FlagType.Dynamic; + // comments + if (comments.Count > 0) + { + mComments = re_commentIndex.Match(keys); + if (mComments.Success) { + member.Comments = comments[ Convert.ToInt16(mComments.Groups["index"].Value) ]; + } + } + // method + member.Name = mFunc.Groups["fname"].Value.Trim(); + if (member.Name.Length == 0) + continue; + // parameters + member.Parameters = re_colonParams.Replace( re_parametersSeparator.Replace(mFunc.Groups["params"].Value.Trim(), ", "), ":"); + // return type + mType = re_variableType.Match(mFunc.Groups["type"].Value); + if (mType.Success) member.Type = mType.Groups["type"].Value; + else member.Type = ""; + // constructor type + if (member.Name == constructor) + { + member.Flags |= FlagType.Constructor; + member.Type = constructor; + } - // getter/setter - if ((member.Name.Length > 4) && ((int)member.Name[3] < 33)) - { - Match mProp = re_isGetterSetter.Match(member.Name); - if (mProp.Success) - { - string pname = mProp.Groups["pname"].Value; - ASMember prop = aClass.Properties.Search(pname, 0); - if (prop == null) - { - prop = member; - prop.Name = pname; - prop.Flags -= FlagType.Function; - aClass.Properties.Add(prop); - } - if (mProp.Groups["type"].Value == "g") - { - prop.Flags |= FlagType.Getter; - prop.Type = member.Type; - if (!mType.Success) prop.Type = "Object"; - } - else - { - prop.Flags |= FlagType.Setter; - prop.Parameters = member.Parameters; - } - if ((member.Comments != null) && - ((prop.Comments == null) || (prop.Comments.Length < member.Comments.Length))) - prop.Comments = member.Comments; - } - // store method - else aClass.Methods.Add(member); - } - // store method - else aClass.Methods.Add(member); - } + // getter/setter + if ((member.Name.Length > 4) && ((int)member.Name[3] < 33)) + { + Match mProp = re_isGetterSetter.Match(member.Name); + if (mProp.Success) + { + string pname = mProp.Groups["pname"].Value; + ASMember prop = aClass.Properties.Search(pname, 0); + if (prop == null) + { + prop = member; + prop.Name = pname; + prop.Flags -= FlagType.Function; + aClass.Properties.Add(prop); + } + if (mProp.Groups["type"].Value == "g") + { + prop.Flags |= FlagType.Getter; + prop.Type = member.Type; + if (!mType.Success) prop.Type = "Object"; + } + else + { + prop.Flags |= FlagType.Setter; + prop.Parameters = member.Parameters; + } + if ((member.Comments != null) && + ((prop.Comments == null) || (prop.Comments.Length < member.Comments.Length))) + prop.Comments = member.Comments; + } + // store method + else aClass.Methods.Add(member); + } + // store method + else aClass.Methods.Add(member); + } - // parse variables - MatchCollection mcVars = re_variable.Matches(src); - Match mVar; - foreach(Match m in mcVars) - { - mVar = re_splitVariable.Match(m.Value); - if (!mVar.Success) continue; - // parse method definition - keys = mVar.Groups["keys"].Value; - member = new ASMember(); - member.Flags = FlagType.Variable; - // keywords - if (keys.IndexOf("private") >= 0) member.Flags |= FlagType.Private; - else member.Flags |= FlagType.Public; - isStatic = (keys.IndexOf("static") >= 0); - if (isStatic) member.Flags |= FlagType.Static; - else member.Flags |= FlagType.Dynamic; - // comments - mComments = re_commentIndex.Match(keys); - if (mComments.Success) - member.Comments = comments[ Convert.ToInt16(mComments.Groups["index"].Value) ]; - // name - member.Name = mVar.Groups["pname"].Value; - // type - mType = re_variableType.Match(mVar.Groups["type"].Value); - if (mType.Success) - member.Type = mType.Groups["type"].Value; - else member.Type = "Object"; - // store - aClass.Vars.Add(member); - } - - // HACK AS3 'const' declarations - if (AS3package != null) - { - mcVars = re_constant.Matches(src); - foreach(Match m in mcVars) - { - mVar = re_splitConstant.Match(m.Value); - if (!mVar.Success) continue; - // parse method definition - keys = mVar.Groups["keys"].Value; - member = new ASMember(); - member.Flags = FlagType.Variable; - // keywords - if (keys.IndexOf("private") >= 0) member.Flags |= FlagType.Private; - else member.Flags |= FlagType.Public; - isStatic = (keys.IndexOf("static") >= 0); - if (isStatic) member.Flags |= FlagType.Static; - else member.Flags |= FlagType.Dynamic; - // comments - mComments = re_commentIndex.Match(keys); - if (mComments.Success) - member.Comments = comments[ Convert.ToInt16(mComments.Groups["index"].Value) ]; - // name - member.Name = mVar.Groups["pname"].Value; - // type - mType = re_variableType.Match(mVar.Groups["type"].Value); - if (mType.Success) - member.Type = mType.Groups["type"].Value; - else member.Type = "Object"; - // store - aClass.Vars.Add(member); - } - } + // parse variables + MatchCollection mcVars = re_variable.Matches(src); + Match mVar; + foreach(Match m in mcVars) + { + mVar = re_splitVariable.Match(m.Value); + if (!mVar.Success) continue; + // parse method definition + keys = mVar.Groups["keys"].Value; + member = new ASMember(); + member.Flags = FlagType.Variable; + // keywords + if (keys.IndexOf("private") >= 0) member.Flags |= FlagType.Private; + else member.Flags |= FlagType.Public; + isStatic = (keys.IndexOf("static") >= 0); + if (isStatic) member.Flags |= FlagType.Static; + else member.Flags |= FlagType.Dynamic; + // comments + mComments = re_commentIndex.Match(keys); + if (mComments.Success) + member.Comments = comments[ Convert.ToInt16(mComments.Groups["index"].Value) ]; + // name + member.Name = mVar.Groups["pname"].Value; + // type + mType = re_variableType.Match(mVar.Groups["type"].Value); + if (mType.Success) + member.Type = mType.Groups["type"].Value; + else member.Type = "Object"; + // store + aClass.Vars.Add(member); + } + + // HACK AS3 'const' declarations + if (AS3package != null) + { + mcVars = re_constant.Matches(src); + foreach(Match m in mcVars) + { + mVar = re_splitConstant.Match(m.Value); + if (!mVar.Success) continue; + // parse method definition + keys = mVar.Groups["keys"].Value; + member = new ASMember(); + member.Flags = FlagType.Variable; + // keywords + if (keys.IndexOf("private") >= 0) member.Flags |= FlagType.Private; + else member.Flags |= FlagType.Public; + isStatic = (keys.IndexOf("static") >= 0); + if (isStatic) member.Flags |= FlagType.Static; + else member.Flags |= FlagType.Dynamic; + // comments + mComments = re_commentIndex.Match(keys); + if (mComments.Success) + member.Comments = comments[ Convert.ToInt16(mComments.Groups["index"].Value) ]; + // name + member.Name = mVar.Groups["pname"].Value; + // type + mType = re_variableType.Match(mVar.Groups["type"].Value); + if (mType.Success) + member.Type = mType.Groups["type"].Value; + else member.Type = "Object"; + // store + aClass.Vars.Add(member); + } + } - // is also a package? - //DebugConsole.Trace("check folder "+aClass.FileName.Substring(0, aClass.FileName.Length-3)); - if (System.IO.Directory.Exists(aClass.FileName.Substring(0, aClass.FileName.Length-3))) - { - string package = aClass.FileName.Substring(aClass.BasePath.Length); - package = package.Substring(0, package.IndexOf('.')); - ASMemberList pList = context.GetSubClasses(package); - if ((pList != null) && (pList.Count > 0)) - { - //DebugConsole.Trace("Sub classes/packages "+package+" "+pList.Count); - aClass.Flags |= FlagType.Package; - aClass.Package = pList; - // if intrinsic class, inherit flag - if ((aClass.Flags & FlagType.Intrinsic) == FlagType.Intrinsic) - foreach(ASMember import in pList) - import.Flags |= FlagType.Intrinsic; - } - } + // is also a package? + //DebugConsole.Trace("check folder "+aClass.FileName.Substring(0, aClass.FileName.Length-3)); + if (System.IO.Directory.Exists(aClass.FileName.Substring(0, aClass.FileName.Length-3))) + { + string package = aClass.FileName.Substring(aClass.BasePath.Length); + package = package.Substring(0, package.IndexOf('.')); + ASMemberList pList = context.GetSubClasses(package); + if ((pList != null) && (pList.Count > 0)) + { + //DebugConsole.Trace("Sub classes/packages "+package+" "+pList.Count); + aClass.Flags |= FlagType.Package; + aClass.Package = pList; + // if intrinsic class, inherit flag + if ((aClass.Flags & FlagType.Intrinsic) == FlagType.Intrinsic) + foreach(ASMember import in pList) + import.Flags |= FlagType.Intrinsic; + } + } - // done - } - #endregion + // done + } + #endregion - #region tools_functions - /// - /// Remove comments from the Class' source - /// - /// Original Class source - /// Class source without comments - static public string CleanClassSource(string src, StringCollection comments) - { - int len = src.Length-1; - if (len <= 0) - return src; - char[] ba = src.ToCharArray(); - int i = 0; - char c1; - char c2; - int matching = 0; - bool addText = true; - bool addComment = false; - int inString = 0; - StringBuilder sb = new StringBuilder(len); - StringBuilder comment = new StringBuilder(); - while (i < len-1) { - // next chars - c1 = ba[i++]; - // match - switch (matching) { - // look for comment block/line - case 0: - if (inString == 0) - { - // new comment - if (c1 == '/') - { - c2 = ba[i]; - if (c2 == '/') { - matching = 1; - addText = false; - i++; - continue; - } - else if (c2 == '*') { - matching = 2; - addText = false; - if (i < len-1 && ba[i+1] == '*' && ba[i+2] != '/') { - addComment = (comments != null); - i++; - } - i++; - continue; - } - } - // don't look for comments in strings - else if (c1 == '"') inString = 1; - else if (c1 == '\'') inString = 2; - } - // end of string - else if ((inString == 1) && (c1 == '"')) inString = 0; - else if ((inString == 2) && (c1 == '\'')) inString = 0; - break; - case 1: - if (c1 == 10 || c1 == 13) { - addText = true; - comment = new StringBuilder(); - matching = 0; - } - break; - case 2: - if (c1 == '*') - { - c2 = ba[i]; - if (c2 == '/') { - string temp = comment.ToString(); - // extract doc comments - if (addComment && (comment.Length > 0)) - { - sb.Append(" comment").Append(comments.Count).Append(' '); - comments.Add(temp); - } - // TODO ASClassParser: parse for TODO statements! - comment = new StringBuilder(); - addText = true; - addComment = false; - matching = 0; - i++; - continue; - } - } - break; - } - // add char - if (addText) sb.Append(c1); - else comment.Append(c1); - } - return sb.ToString(); - } + #region tools_functions + /// + /// Remove comments from the Class' source + /// + /// Original Class source + /// Class source without comments + static public string CleanClassSource(string src, StringCollection comments) + { + int len = src.Length-1; + if (len <= 0) + return src; + char[] ba = src.ToCharArray(); + int i = 0; + char c1; + char c2; + int matching = 0; + bool addText = true; + bool addComment = false; + int inString = 0; + StringBuilder sb = new StringBuilder(len); + StringBuilder comment = new StringBuilder(); + while (i < len-1) { + // next chars + c1 = ba[i++]; + // match + switch (matching) { + // look for comment block/line + case 0: + if (inString == 0) + { + // new comment + if (c1 == '/') + { + c2 = ba[i]; + if (c2 == '/') { + matching = 1; + addText = false; + i++; + continue; + } + else if (c2 == '*') { + matching = 2; + addText = false; + if (i < len-1 && ba[i+1] == '*' && ba[i+2] != '/') { + addComment = (comments != null); + i++; + } + i++; + continue; + } + } + // don't look for comments in strings + else if (c1 == '"') inString = 1; + else if (c1 == '\'') inString = 2; + } + // end of string + else if ((inString == 1) && (c1 == '"')) inString = 0; + else if ((inString == 2) && (c1 == '\'')) inString = 0; + break; + case 1: + if (c1 == 10 || c1 == 13) { + addText = true; + comment = new StringBuilder(); + matching = 0; + } + break; + case 2: + if (c1 == '*') + { + c2 = ba[i]; + if (c2 == '/') { + string temp = comment.ToString(); + // extract doc comments + if (addComment && (comment.Length > 0)) + { + sb.Append(" comment").Append(comments.Count).Append(' '); + comments.Add(temp); + } + // TODO ASClassParser: parse for TODO statements! + comment = new StringBuilder(); + addText = true; + addComment = false; + matching = 0; + i++; + continue; + } + } + break; + } + // add char + if (addText) sb.Append(c1); + else comment.Append(c1); + } + return sb.ToString(); + } - /// - /// Parse import statements in source - /// - /// Class source - /// Class object to update - static private void ParseImports(string src, ASClass aClass) - { - aClass.Imports.Clear(); + /// + /// Parse import statements in source + /// + /// Class source + /// Class object to update + static private void ParseImports(string src, ASClass aClass) + { + aClass.Imports.Clear(); src = src.Replace('\r', '\n'); // fix .NET Regex line-ends detection - MatchCollection mcImports = re_import.Matches(src); - if (mcImports.Count > 0) - { - ArrayList known = new ArrayList(); - string package; - string cname; - ASMember newImport; - foreach(Match mImport in mcImports) - { - package = mImport.Groups["package"].Value; - //DebugConsole.Trace("IMPORT '"+package+"'"); - int p = package.LastIndexOf("."); - cname = (p >= 0) ? package.Substring(p+1) : package; - // resolve wildcard - if (cname.Length == 0) - { - context.ResolveWildcards(package, aClass, known); - } - else if (!known.Contains(package)) - { - known.Add(package); - newImport = new ASMember(); - newImport.Name = cname; - newImport.Type = package; - aClass.Imports.Add(newImport); - } - } - } - //else DebugConsole.Trace("NO IMPORTS"); - } - #endregion - - } + MatchCollection mcImports = re_import.Matches(src); + if (mcImports.Count > 0) + { + ArrayList known = new ArrayList(); + string package; + string cname; + ASMember newImport; + foreach(Match mImport in mcImports) + { + package = mImport.Groups["package"].Value; + //DebugConsole.Trace("IMPORT '"+package+"'"); + int p = package.LastIndexOf("."); + cname = (p >= 0) ? package.Substring(p+1) : package; + // resolve wildcard + if (cname.Length == 0) + { + context.ResolveWildcards(package, aClass, known); + } + else if (!known.Contains(package)) + { + known.Add(package); + newImport = new ASMember(); + newImport.Name = cname; + newImport.Type = package; + aClass.Imports.Add(newImport); + } + } + } + //else DebugConsole.Trace("NO IMPORTS"); + } + #endregion + + } } diff --git a/External/Tools/IGen/ASClasses.cs b/External/Tools/IGen/ASClasses.cs index 44ab33350e..81a83dd0b2 100644 --- a/External/Tools/IGen/ASClasses.cs +++ b/External/Tools/IGen/ASClasses.cs @@ -9,512 +9,512 @@ namespace ASCompletion { - /// - /// Object representation of an Actionscript class - /// - sealed public class ASClass - { - #region actionscript class instance - public FlagType Flags; - private string fileName; - public string ClassName; - public ASMemberList Imports; - public ASMemberList Methods; - public ASMemberList Vars; - public ASMemberList Properties; - public ASMemberList Package; - public bool OutOfDate; - public bool IsAS3; - public string BasePath; - private ASClass extends; - public string Implements; - public string Comments; - - public ASClass Extends - { - get { - if (extends == null) return null; - else return ASClassParser.Context.GetCachedClass(extends); - } - set { - extends = value; - } - } + /// + /// Object representation of an Actionscript class + /// + sealed public class ASClass + { + #region actionscript class instance + public FlagType Flags; + private string fileName; + public string ClassName; + public ASMemberList Imports; + public ASMemberList Methods; + public ASMemberList Vars; + public ASMemberList Properties; + public ASMemberList Package; + public bool OutOfDate; + public bool IsAS3; + public string BasePath; + private ASClass extends; + public string Implements; + public string Comments; + + public ASClass Extends + { + get { + if (extends == null) return null; + else return ASClassParser.Context.GetCachedClass(extends); + } + set { + extends = value; + } + } - public string FileName - { - get { - return fileName; - } - set { - fileName = value; - } - } - - public ASClass() - { - ClassName = null; - Imports = new ASMemberList(); - Methods = new ASMemberList(); - Vars = new ASMemberList(); - Properties = new ASMemberList(); - } - - public bool IsVoid() - { - return (ClassName == null || ClassName.Length == 0 || ClassName.ToLower() == "void"); - } - - public ASMember ToASMember() - { - ASMember self = new ASMember(); - int p = ClassName.LastIndexOf("."); - self.Name = (p >= 0) ? ClassName.Substring(p+1) : ClassName; - self.Type = ClassName; - self.Flags = Flags; - return self; - } - - public string GenerateIntrinsic() - { - StringBuilder sb = new StringBuilder(); - string nl = "\r\n"; - char semi = ';'; - char tab = '\t'; - - // IMPORTS - ArrayList known = new ArrayList(); - known.Add(ClassName); - foreach(ASMember import in Imports) - if (!known.Contains(import.Type)) - { - known.Add(import.Type); - sb.Append("import ").Append(import.Type).Append(semi).Append(nl); - } - - // CLASS - sb.Append(CommentDeclaration(Comments, false)); - if ((this.Flags & (FlagType.Intrinsic | FlagType.Interface)) == 0) sb.Append("intrinsic "); - sb.Append(ClassDeclaration(this)); - if (!extends.IsVoid() && (extends.ClassName != "Object")) - sb.Append(" extends ").Append(extends.ClassName); - if (Implements != null) - sb.Append(" implements ").Append(Implements); - sb.Append(nl).Append('{').Append(nl); - - // MEMBERS - int count = 0; - foreach(ASMember var in Vars) - //if ( (var.Flags & FlagType.Public) > 0 ) - { - sb.Append(CommentDeclaration(var.Comments, true)); - sb.Append(tab).Append(MemberDeclaration(var)).Append(semi).Append(nl); - count ++; - } - if (count > 0) sb.Append(nl); - - // MEMBERS - string decl; - ASMember temp; - count = 0; - foreach(ASMember property in Properties) - //if ( (property.Flags & FlagType.Public) > 0 ) - { - sb.Append(CommentDeclaration(property.Comments, true)); - FlagType flags = (property.Flags & ~(FlagType.Setter | FlagType.Getter)) | FlagType.Function; - - if ( (property.Flags & FlagType.Getter) > 0 ) - { - temp = (ASMember)property.Clone(); - temp.Name = "get "+temp.Name; - temp.Flags = flags; - temp.Parameters = ""; - sb.Append(tab).Append(MemberDeclaration(temp)).Append(semi).Append(nl); - } - if ( (property.Flags & FlagType.Setter) > 0 ) - { - temp = (ASMember)property.Clone(); - temp.Name = "set "+temp.Name; - temp.Flags = flags; - temp.Type = (IsAS3) ? "void" : "Void"; - sb.Append(tab).Append(MemberDeclaration(temp)).Append(semi).Append(nl); - } - sb.Append(nl); - count ++; - } - if (count > 0) sb.Append(nl); - - // MEMBERS - count = 0; - foreach(ASMember method in Methods) - //if ( (method.Flags & FlagType.Public) > 0 ) - { - decl = MemberDeclaration(method); - if ( (method.Flags & FlagType.Constructor) > 0 ) decl = decl.Replace(" : constructor", ""); - sb.Append(CommentDeclaration(method.Comments, true)); - sb.Append(tab).Append(decl).Append(semi).Append(nl).Append(nl); - count ++; - } - - // END CLASS - sb.Append('}'); - return sb.ToString(); - } - - public void Sort() - { - Imports.Sort(); - Methods.Sort(); - Vars.Sort(); - Properties.Sort(); - } - - public override string ToString() - { - //string res = ""; - return ClassName; - } - public override bool Equals(object obj) - { - if (!(obj is ASClass)) return false; - return FileName.Equals( ((ASClass)obj).FileName ); - } - public override int GetHashCode() - { - return ClassName.GetHashCode(); - } - #endregion - - #region actionscript declaration generation - static public string ClassDeclaration(ASClass oClass) - { - // package - if (oClass.Flags == FlagType.Package) - { - return "package "+oClass.ClassName.Replace('\\', '.'); - } - else - { - // modifiers - string modifiers = ""; - if ((oClass.Flags & FlagType.Intrinsic) > 0) - modifiers += "intrinsic "; - if ((oClass.Flags & FlagType.Dynamic) > 0) - modifiers += "dynamic "; - - string classType = ((oClass.Flags & FlagType.Interface) > 0) ? "interface" : "class"; - // signature - return String.Format("{0}{1} {2}", modifiers, classType, oClass.ClassName); - } - } - - static public string MemberDeclaration(ASMember member) - { - // modifiers - FlagType ft = member.Flags; - string modifiers = ""; - if ((ft & FlagType.Class) > 0) - { - if ((ft & FlagType.Intrinsic) > 0) - modifiers += "intrinsic "; - if ((ft & FlagType.Dynamic) > 0) - modifiers += "dynamic "; - // TODO (or not?) ASClasses: parse classes in completion list to eval if there are interfaces or classes? - string classType = ((member.Flags & FlagType.Interface) > 0) ? "interface" : "class"; - return String.Format("{0}{1} {2}", modifiers, classType, member.Type); - } - else - { - if ((ft & FlagType.Static) > 0) - modifiers += "static "; - if ((ft & FlagType.Private) > 0) - modifiers += "private "; - else if ((ft & FlagType.Public) > 0) - modifiers += "public "; - } - // signature - if ((ft & FlagType.Function) > 0) - return String.Format("{0}function {1}", modifiers, member.ToString()); - else if ((ft & FlagType.Variable) > 0) - { - if (modifiers.Length == 0) modifiers = "local "; - return String.Format("{0}var {1}", modifiers, member.ToString()); - } - else if ((ft & (FlagType.Getter | FlagType.Setter)) > 0) - return String.Format("{0}property {1}", modifiers, member.ToString()); - else if ((ft & FlagType.Template) > 0) - return String.Format("Template {0}", member.Type); - else if (ft == FlagType.Package) - return String.Format("Package {0}", member.Type); - else - { - if ((ft & FlagType.Intrinsic) > 0) modifiers = "intrinsic "+modifiers; - return String.Format("{0}type {1}", modifiers, member.Type); - } - } - - static public string CommentDeclaration(string comment, bool indent) - { - if (comment == null) return ""; - if (indent) return "\t/**"+comment+"*/\r\n"; - else return "/**"+comment+"*/\r\n"; - } - #endregion - } - - #region class_members - /// - /// Object representation of an Actionscript ASMember - /// - sealed public class ASMember: ICloneable, IComparable - { - public FlagType Flags; - public string Name; - public string Parameters; - public string Type; - public string Comments; - - public Object Clone() - { - ASMember copy = new ASMember(); - copy.Name = Name; - copy.Flags = Flags; - copy.Parameters = Parameters; - copy.Type = Type; - copy.Comments = Comments; - return copy; - } - - public override string ToString() - { - string res = Name; - if ((Flags & FlagType.Function) > 0) - res += "("+Parameters+")"; - if ((Flags & FlagType.Constructor) > 0) - return res+" : constructor"; - else if (Type.Length > 0) - return res+" : "+Type; - else - return res; - } - - public override bool Equals(object obj) - { - if (!(obj is ASMember)) - return false; - return Name.Equals( ((ASMember)obj).Name ); - } - - public override int GetHashCode() - { - return (Name+Flags).GetHashCode(); - } - - private string upperName; - internal string UpperName - { - get { - if (upperName == null) upperName = Name.ToUpper(); - return upperName; - } - } - public int CompareTo(object obj) - { - // using ascii comparison to be compatible with Scintilla completion list - if (!(obj is ASMember)) - throw new InvalidCastException("This object is not of type ASMember"); - return string.CompareOrdinal(UpperName, ((ASMember)obj).UpperName); - } - } - - /// - /// Strong-typed ASMember list with special merging/searching methods - /// - sealed public class ASMemberList: IEnumerable - { - private ArrayList items; - private bool Sorted; - - public IEnumerator GetEnumerator() - { - return items.GetEnumerator(); - } - - /*public ArrayList Items - { - get { - return items; - } - }*/ + public string FileName + { + get { + return fileName; + } + set { + fileName = value; + } + } + + public ASClass() + { + ClassName = null; + Imports = new ASMemberList(); + Methods = new ASMemberList(); + Vars = new ASMemberList(); + Properties = new ASMemberList(); + } + + public bool IsVoid() + { + return (ClassName == null || ClassName.Length == 0 || ClassName.ToLower() == "void"); + } + + public ASMember ToASMember() + { + ASMember self = new ASMember(); + int p = ClassName.LastIndexOf("."); + self.Name = (p >= 0) ? ClassName.Substring(p+1) : ClassName; + self.Type = ClassName; + self.Flags = Flags; + return self; + } + + public string GenerateIntrinsic() + { + StringBuilder sb = new StringBuilder(); + string nl = "\r\n"; + char semi = ';'; + char tab = '\t'; + + // IMPORTS + ArrayList known = new ArrayList(); + known.Add(ClassName); + foreach(ASMember import in Imports) + if (!known.Contains(import.Type)) + { + known.Add(import.Type); + sb.Append("import ").Append(import.Type).Append(semi).Append(nl); + } + + // CLASS + sb.Append(CommentDeclaration(Comments, false)); + if ((this.Flags & (FlagType.Intrinsic | FlagType.Interface)) == 0) sb.Append("intrinsic "); + sb.Append(ClassDeclaration(this)); + if (!extends.IsVoid() && (extends.ClassName != "Object")) + sb.Append(" extends ").Append(extends.ClassName); + if (Implements != null) + sb.Append(" implements ").Append(Implements); + sb.Append(nl).Append('{').Append(nl); + + // MEMBERS + int count = 0; + foreach(ASMember var in Vars) + //if ( (var.Flags & FlagType.Public) > 0 ) + { + sb.Append(CommentDeclaration(var.Comments, true)); + sb.Append(tab).Append(MemberDeclaration(var)).Append(semi).Append(nl); + count ++; + } + if (count > 0) sb.Append(nl); + + // MEMBERS + string decl; + ASMember temp; + count = 0; + foreach(ASMember property in Properties) + //if ( (property.Flags & FlagType.Public) > 0 ) + { + sb.Append(CommentDeclaration(property.Comments, true)); + FlagType flags = (property.Flags & ~(FlagType.Setter | FlagType.Getter)) | FlagType.Function; + + if ( (property.Flags & FlagType.Getter) > 0 ) + { + temp = (ASMember)property.Clone(); + temp.Name = "get "+temp.Name; + temp.Flags = flags; + temp.Parameters = ""; + sb.Append(tab).Append(MemberDeclaration(temp)).Append(semi).Append(nl); + } + if ( (property.Flags & FlagType.Setter) > 0 ) + { + temp = (ASMember)property.Clone(); + temp.Name = "set "+temp.Name; + temp.Flags = flags; + temp.Type = (IsAS3) ? "void" : "Void"; + sb.Append(tab).Append(MemberDeclaration(temp)).Append(semi).Append(nl); + } + sb.Append(nl); + count ++; + } + if (count > 0) sb.Append(nl); + + // MEMBERS + count = 0; + foreach(ASMember method in Methods) + //if ( (method.Flags & FlagType.Public) > 0 ) + { + decl = MemberDeclaration(method); + if ( (method.Flags & FlagType.Constructor) > 0 ) decl = decl.Replace(" : constructor", ""); + sb.Append(CommentDeclaration(method.Comments, true)); + sb.Append(tab).Append(decl).Append(semi).Append(nl).Append(nl); + count ++; + } + + // END CLASS + sb.Append('}'); + return sb.ToString(); + } + + public void Sort() + { + Imports.Sort(); + Methods.Sort(); + Vars.Sort(); + Properties.Sort(); + } + + public override string ToString() + { + //string res = ""; + return ClassName; + } + public override bool Equals(object obj) + { + if (!(obj is ASClass)) return false; + return FileName.Equals( ((ASClass)obj).FileName ); + } + public override int GetHashCode() + { + return ClassName.GetHashCode(); + } + #endregion + + #region actionscript declaration generation + static public string ClassDeclaration(ASClass oClass) + { + // package + if (oClass.Flags == FlagType.Package) + { + return "package "+oClass.ClassName.Replace('\\', '.'); + } + else + { + // modifiers + string modifiers = ""; + if ((oClass.Flags & FlagType.Intrinsic) > 0) + modifiers += "intrinsic "; + if ((oClass.Flags & FlagType.Dynamic) > 0) + modifiers += "dynamic "; + + string classType = ((oClass.Flags & FlagType.Interface) > 0) ? "interface" : "class"; + // signature + return String.Format("{0}{1} {2}", modifiers, classType, oClass.ClassName); + } + } + + static public string MemberDeclaration(ASMember member) + { + // modifiers + FlagType ft = member.Flags; + string modifiers = ""; + if ((ft & FlagType.Class) > 0) + { + if ((ft & FlagType.Intrinsic) > 0) + modifiers += "intrinsic "; + if ((ft & FlagType.Dynamic) > 0) + modifiers += "dynamic "; + // TODO (or not?) ASClasses: parse classes in completion list to eval if there are interfaces or classes? + string classType = ((member.Flags & FlagType.Interface) > 0) ? "interface" : "class"; + return String.Format("{0}{1} {2}", modifiers, classType, member.Type); + } + else + { + if ((ft & FlagType.Static) > 0) + modifiers += "static "; + if ((ft & FlagType.Private) > 0) + modifiers += "private "; + else if ((ft & FlagType.Public) > 0) + modifiers += "public "; + } + // signature + if ((ft & FlagType.Function) > 0) + return String.Format("{0}function {1}", modifiers, member.ToString()); + else if ((ft & FlagType.Variable) > 0) + { + if (modifiers.Length == 0) modifiers = "local "; + return String.Format("{0}var {1}", modifiers, member.ToString()); + } + else if ((ft & (FlagType.Getter | FlagType.Setter)) > 0) + return String.Format("{0}property {1}", modifiers, member.ToString()); + else if ((ft & FlagType.Template) > 0) + return String.Format("Template {0}", member.Type); + else if (ft == FlagType.Package) + return String.Format("Package {0}", member.Type); + else + { + if ((ft & FlagType.Intrinsic) > 0) modifiers = "intrinsic "+modifiers; + return String.Format("{0}type {1}", modifiers, member.Type); + } + } + + static public string CommentDeclaration(string comment, bool indent) + { + if (comment == null) return ""; + if (indent) return "\t/**"+comment+"*/\r\n"; + else return "/**"+comment+"*/\r\n"; + } + #endregion + } + + #region class_members + /// + /// Object representation of an Actionscript ASMember + /// + sealed public class ASMember: ICloneable, IComparable + { + public FlagType Flags; + public string Name; + public string Parameters; + public string Type; + public string Comments; + + public Object Clone() + { + ASMember copy = new ASMember(); + copy.Name = Name; + copy.Flags = Flags; + copy.Parameters = Parameters; + copy.Type = Type; + copy.Comments = Comments; + return copy; + } + + public override string ToString() + { + string res = Name; + if ((Flags & FlagType.Function) > 0) + res += "("+Parameters+")"; + if ((Flags & FlagType.Constructor) > 0) + return res+" : constructor"; + else if (Type.Length > 0) + return res+" : "+Type; + else + return res; + } + + public override bool Equals(object obj) + { + if (!(obj is ASMember)) + return false; + return Name.Equals( ((ASMember)obj).Name ); + } + + public override int GetHashCode() + { + return (Name+Flags).GetHashCode(); + } + + private string upperName; + internal string UpperName + { + get { + if (upperName == null) upperName = Name.ToUpper(); + return upperName; + } + } + public int CompareTo(object obj) + { + // using ascii comparison to be compatible with Scintilla completion list + if (!(obj is ASMember)) + throw new InvalidCastException("This object is not of type ASMember"); + return string.CompareOrdinal(UpperName, ((ASMember)obj).UpperName); + } + } + + /// + /// Strong-typed ASMember list with special merging/searching methods + /// + sealed public class ASMemberList: IEnumerable + { + private ArrayList items; + private bool Sorted; + + public IEnumerator GetEnumerator() + { + return items.GetEnumerator(); + } + + /*public ArrayList Items + { + get { + return items; + } + }*/ - public int Count - { - get { - return items.Count; - } - } - - public ASMemberList() - { - items = new ArrayList(); - } - - public ASMember this[int index] - { - get { - return (ASMember)items[index]; - } - set { - Sorted = false; - items[index] = value; - } - } - - public int Add(ASMember value) - { - Sorted = false; - return items.Add(value); - } - - public void Insert(int index, ASMember value) - { - Sorted = false; - items.Insert(index, value); - } - - public void Remove(ASMember value) - { - Sorted = false; - items.Remove(value); - } - - public void Clear() - { - Sorted = true; - items.Clear(); - } - - public ASMember Search(string name, FlagType mask) { - foreach (ASMember m in items) - if ((m.Name.Equals(name)) && ((m.Flags & mask) == mask)) return m; - return null; - } - - public ASMemberList MultipleSearch(string name, FlagType mask) { - ASMemberList result = new ASMemberList(); - foreach (ASMember m in items) - if ((m.Name.Equals(name)) && ((m.Flags & mask) == mask)) result.Add(m); - return result; - } - - public void Sort() - { - if (!Sorted) - { - items.Sort(); - Sorted = true; - } - } - - /// - /// Merge one item into the list - /// - /// Item to merge - public void Merge(ASMember item) - { - ASMemberList list = new ASMemberList(); - list.Add(item); - Merge(list, 0); - } - - /// - /// Merge SORTED lists without duplicate values - /// - /// Items to merge - public void Merge(ASMemberList list) - { - Merge(list, 0); - } - - /// - /// Merge selected items from the SORTED lists without duplicate values - /// - /// Items to merge - public void Merge(ASMemberList list, FlagType mask) - { - int index = 0; - bool added; - foreach (ASMember m in list) - if ((m.Flags & mask) == mask) - { - added = false; - while (index < items.Count) - { - if (m.CompareTo(items[index]) <= 0) - { - if (!m.Equals(items[index])) - items.Insert(index, m); - added = true; - break; - } - index++; - } - if (!added) items.Add(m); - } - } - - /// - /// Merge selected items from the SORTED lists without duplicate values - /// - /// - /// Items to merge - /// Filter by mask - /// Ignore static members (inheritance) - public void Merge(ASMemberList list, FlagType mask, bool filterStatic) - { - int index = 0; - bool added; - foreach (ASMember m in list) - if ((m.Flags & mask) == mask && (!filterStatic || (m.Flags & FlagType.Static) == 0)) - { - added = false; - while (index < items.Count) - { - if (m.CompareTo(items[index]) <= 0) - { - if (!m.Equals(items[index])) - items.Insert(index, m); - added = true; - break; - } - index++; - } - if (!added) items.Add(m); - } - } - } - #endregion - - [Flags] - public enum FlagType - { - Dynamic = 1<<1, - Static = 1<<2, - Public = 1<<3, - Private = 1<<4, - Getter = 1<<5, - Setter = 1<<6, - Function = 1<<7, - Variable = 1<<8, - Constructor = 1<<9, - Intrinsic = 1<<10, - Class = 1<<11, - Interface = 1<<12, - Package = 1<<13, - Template = 1<<14, - DocTemplate = 1<<15, - CodeTemplate = 1<<16, - Custom = 1<<17 - } - + public int Count + { + get { + return items.Count; + } + } + + public ASMemberList() + { + items = new ArrayList(); + } + + public ASMember this[int index] + { + get { + return (ASMember)items[index]; + } + set { + Sorted = false; + items[index] = value; + } + } + + public int Add(ASMember value) + { + Sorted = false; + return items.Add(value); + } + + public void Insert(int index, ASMember value) + { + Sorted = false; + items.Insert(index, value); + } + + public void Remove(ASMember value) + { + Sorted = false; + items.Remove(value); + } + + public void Clear() + { + Sorted = true; + items.Clear(); + } + + public ASMember Search(string name, FlagType mask) { + foreach (ASMember m in items) + if ((m.Name.Equals(name)) && ((m.Flags & mask) == mask)) return m; + return null; + } + + public ASMemberList MultipleSearch(string name, FlagType mask) { + ASMemberList result = new ASMemberList(); + foreach (ASMember m in items) + if ((m.Name.Equals(name)) && ((m.Flags & mask) == mask)) result.Add(m); + return result; + } + + public void Sort() + { + if (!Sorted) + { + items.Sort(); + Sorted = true; + } + } + + /// + /// Merge one item into the list + /// + /// Item to merge + public void Merge(ASMember item) + { + ASMemberList list = new ASMemberList(); + list.Add(item); + Merge(list, 0); + } + + /// + /// Merge SORTED lists without duplicate values + /// + /// Items to merge + public void Merge(ASMemberList list) + { + Merge(list, 0); + } + + /// + /// Merge selected items from the SORTED lists without duplicate values + /// + /// Items to merge + public void Merge(ASMemberList list, FlagType mask) + { + int index = 0; + bool added; + foreach (ASMember m in list) + if ((m.Flags & mask) == mask) + { + added = false; + while (index < items.Count) + { + if (m.CompareTo(items[index]) <= 0) + { + if (!m.Equals(items[index])) + items.Insert(index, m); + added = true; + break; + } + index++; + } + if (!added) items.Add(m); + } + } + + /// + /// Merge selected items from the SORTED lists without duplicate values + /// + /// + /// Items to merge + /// Filter by mask + /// Ignore static members (inheritance) + public void Merge(ASMemberList list, FlagType mask, bool filterStatic) + { + int index = 0; + bool added; + foreach (ASMember m in list) + if ((m.Flags & mask) == mask && (!filterStatic || (m.Flags & FlagType.Static) == 0)) + { + added = false; + while (index < items.Count) + { + if (m.CompareTo(items[index]) <= 0) + { + if (!m.Equals(items[index])) + items.Insert(index, m); + added = true; + break; + } + index++; + } + if (!added) items.Add(m); + } + } + } + #endregion + + [Flags] + public enum FlagType + { + Dynamic = 1<<1, + Static = 1<<2, + Public = 1<<3, + Private = 1<<4, + Getter = 1<<5, + Setter = 1<<6, + Function = 1<<7, + Variable = 1<<8, + Constructor = 1<<9, + Intrinsic = 1<<10, + Class = 1<<11, + Interface = 1<<12, + Package = 1<<13, + Template = 1<<14, + DocTemplate = 1<<15, + CodeTemplate = 1<<16, + Custom = 1<<17 + } + } diff --git a/External/Tools/IGen/IASContext.cs b/External/Tools/IGen/IASContext.cs index c64a5614d6..68744b7221 100644 --- a/External/Tools/IGen/IASContext.cs +++ b/External/Tools/IGen/IASContext.cs @@ -8,64 +8,64 @@ namespace ASCompletion { - public interface IASContext - { - #region methods - - /// - /// Add the current class' base path to the classpath - /// - /// Relative to this file - /// Resolved this base path - void SetTemporaryBasePath(string fileName, string basePath); - - /// - /// Retrieves a parsed class from its name - /// - /// Class (short or full) name - /// Current class - /// A parsed class or an empty ASClass if the class is not found - ASClass GetClassByName(string cname, ASClass inClass); - - /// - /// Retrieves a parsed class from its filename - /// - /// Class' file name - /// A parsed class or an empty ASClass if the class is not found or invalid - ASClass GetClassByFile(string fileName); - - /// - /// Retrieves the current active class - /// - /// ASClass objet - ASClass GetCurrentClass(); - - /// - /// Find folder and classes in classpath - /// - /// Path to eval - /// Package folders and classes - ASMemberList GetSubClasses(string folder); - - /// - /// (Re)Parse (if necessary) and cache a class file - /// - /// Class object - /// The class object - ASClass GetCachedClass(ASClass aClass); - - /// - /// Resolve wildcards in imports - /// - /// Package to explore - /// Current class - /// Packages already added - void ResolveWildcards(string package, ASClass inClass, ArrayList known); - - /// - /// Depending on the context UI, display some message - /// - void DisplayError(string message); - #endregion - } + public interface IASContext + { + #region methods + + /// + /// Add the current class' base path to the classpath + /// + /// Relative to this file + /// Resolved this base path + void SetTemporaryBasePath(string fileName, string basePath); + + /// + /// Retrieves a parsed class from its name + /// + /// Class (short or full) name + /// Current class + /// A parsed class or an empty ASClass if the class is not found + ASClass GetClassByName(string cname, ASClass inClass); + + /// + /// Retrieves a parsed class from its filename + /// + /// Class' file name + /// A parsed class or an empty ASClass if the class is not found or invalid + ASClass GetClassByFile(string fileName); + + /// + /// Retrieves the current active class + /// + /// ASClass objet + ASClass GetCurrentClass(); + + /// + /// Find folder and classes in classpath + /// + /// Path to eval + /// Package folders and classes + ASMemberList GetSubClasses(string folder); + + /// + /// (Re)Parse (if necessary) and cache a class file + /// + /// Class object + /// The class object + ASClass GetCachedClass(ASClass aClass); + + /// + /// Resolve wildcards in imports + /// + /// Package to explore + /// Current class + /// Packages already added + void ResolveWildcards(string package, ASClass inClass, ArrayList known); + + /// + /// Depending on the context UI, display some message + /// + void DisplayError(string message); + #endregion + } } diff --git a/External/Tools/IGen/IGen.csproj b/External/Tools/IGen/IGen.csproj index b33747fe58..8f5726e1ee 100644 --- a/External/Tools/IGen/IGen.csproj +++ b/External/Tools/IGen/IGen.csproj @@ -1,11 +1,9 @@ - + Debug AnyCPU - 8.0.50727 - 2.0 {95A2D92B-34F7-4211-ACA5-0F25EDCCFEA7} - Exe + WinExe Properties IGen IGen @@ -39,12 +37,4 @@ - - \ No newline at end of file diff --git a/External/Tools/IGen/IGenMain.cs b/External/Tools/IGen/IGenMain.cs index 8c97d71284..784848510d 100644 --- a/External/Tools/IGen/IGenMain.cs +++ b/External/Tools/IGen/IGenMain.cs @@ -11,315 +11,315 @@ namespace IGenMain { - class MainClass: IASContext - { - #region IASContext interface members + class MainClass: IASContext + { + #region IASContext interface members - /// - /// Add the current class' base path to the classpath - /// - /// Relative to this file - /// Resolved this base path - public void SetTemporaryBasePath(string fileName, string basePath) - { - // - } + /// + /// Add the current class' base path to the classpath + /// + /// Relative to this file + /// Resolved this base path + public void SetTemporaryBasePath(string fileName, string basePath) + { + // + } - /// - /// Retrieves a parsed class from its name - /// - /// Class (short or full) name - /// Current class - /// A parsed class or an empty ASClass if the class is not found - public ASClass GetClassByName(string cname, ASClass inClass) - { - ASClass aClass = new ASClass(); - aClass.ClassName = cname; - return aClass; - } + /// + /// Retrieves a parsed class from its name + /// + /// Class (short or full) name + /// Current class + /// A parsed class or an empty ASClass if the class is not found + public ASClass GetClassByName(string cname, ASClass inClass) + { + ASClass aClass = new ASClass(); + aClass.ClassName = cname; + return aClass; + } - /// - /// Retrieves a parsed class from its filename - /// - /// Class' file name - /// A parsed class or an empty ASClass if the class is not found or invalid - public ASClass GetClassByFile(string fileName) - { - ASClass aClass = new ASClass(); - aClass.FileName = fileName; - return aClass; - } + /// + /// Retrieves a parsed class from its filename + /// + /// Class' file name + /// A parsed class or an empty ASClass if the class is not found or invalid + public ASClass GetClassByFile(string fileName) + { + ASClass aClass = new ASClass(); + aClass.FileName = fileName; + return aClass; + } - /// - /// Retrieves the current active class - /// - /// ASClass objet - public ASClass GetCurrentClass() - { - return null; - } + /// + /// Retrieves the current active class + /// + /// ASClass objet + public ASClass GetCurrentClass() + { + return null; + } - /// - /// Find folder and classes in classpath - /// - /// Path to eval - /// Package folders and classes - public ASMemberList GetSubClasses(string folder) - { - return null; - } + /// + /// Find folder and classes in classpath + /// + /// Path to eval + /// Package folders and classes + public ASMemberList GetSubClasses(string folder) + { + return null; + } - /// - /// (Re)Parse and cache a class file - /// - /// Class object - /// The class object - public ASClass GetCachedClass(ASClass aClass) - { - return aClass; - } + /// + /// (Re)Parse and cache a class file + /// + /// Class object + /// The class object + public ASClass GetCachedClass(ASClass aClass) + { + return aClass; + } - /// - /// Resolve wildcards in imports - /// - /// Package to explore - /// Current class - /// Packages already added - public void ResolveWildcards(string package, ASClass inClass, ArrayList known) - { - if (!known.Contains(package)) - { - known.Add(package); - ASMember pMember = new ASMember(); - pMember.Name = package+"*"; - pMember.Type = package+"*"; - inClass.Imports.Add(pMember); - } - } + /// + /// Resolve wildcards in imports + /// + /// Package to explore + /// Current class + /// Packages already added + public void ResolveWildcards(string package, ASClass inClass, ArrayList known) + { + if (!known.Contains(package)) + { + known.Add(package); + ASMember pMember = new ASMember(); + pMember.Name = package+"*"; + pMember.Type = package+"*"; + inClass.Imports.Add(pMember); + } + } - /// - /// Depending on the context UI, display some message - /// - public void DisplayError(string message) - { - Console.WriteLine("IGen Parser error: "+message); - } - #endregion + /// + /// Depending on the context UI, display some message + /// + public void DisplayError(string message) + { + Console.WriteLine("IGen Parser error: "+message); + } + #endregion - // already explored pathes - static ArrayList known; - // remove orphan intrinsic classes and empty folders - static bool clean; - static int filesCleaned; - static int foldersCleaned; - // source path - static string srcPath; - // destination path - static string destPath; - // classes processed - static string currentFile; - static int total; + // already explored pathes + static ArrayList known; + // remove orphan intrinsic classes and empty folders + static bool clean; + static int filesCleaned; + static int foldersCleaned; + // source path + static string srcPath; + // destination path + static string destPath; + // classes processed + static string currentFile; + static int total; - #region tools IO methods - /// - /// From FlashDevelop: FileSystem.cs - /// Reads the file codepage from the file data. - /// - static int GetFileCodepage(string file) - { - byte[] bom = new byte[4]; - System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); - if (fs.CanSeek) - { - fs.Read(bom, 0, 4); fs.Close(); - if ((bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf)) - { - return Encoding.UTF8.CodePage; - } - else if ((bom[0] == 0xff && bom[1] == 0xfe)) - { - return Encoding.Unicode.CodePage; - } - else if ((bom[0] == 0xfe && bom[1] == 0xff)) - { - return Encoding.BigEndianUnicode.CodePage; - } - else if ((bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0xfe && bom[3] == 0x76)) - { - return Encoding.UTF7.CodePage; - } - else - { - return Encoding.Default.CodePage; - } - } - else - { - return Encoding.Default.CodePage; - } - } + #region tools IO methods + /// + /// From FlashDevelop: FileSystem.cs + /// Reads the file codepage from the file data. + /// + static int GetFileCodepage(string file) + { + byte[] bom = new byte[4]; + System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); + if (fs.CanSeek) + { + fs.Read(bom, 0, 4); fs.Close(); + if ((bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf)) + { + return Encoding.UTF8.CodePage; + } + else if ((bom[0] == 0xff && bom[1] == 0xfe)) + { + return Encoding.Unicode.CodePage; + } + else if ((bom[0] == 0xfe && bom[1] == 0xff)) + { + return Encoding.BigEndianUnicode.CodePage; + } + else if ((bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0xfe && bom[3] == 0x76)) + { + return Encoding.UTF7.CodePage; + } + else + { + return Encoding.Default.CodePage; + } + } + else + { + return Encoding.Default.CodePage; + } + } - /// - /// From FlashDevelop: FileSystem.cs - /// - static void Write(string file, string text, Encoding enc) - { - using (StreamWriter sw = new StreamWriter(file, false, enc)) - { - sw.Write(text); - } - } - #endregion + /// + /// From FlashDevelop: FileSystem.cs + /// + static void Write(string file, string text, Encoding enc) + { + using (StreamWriter sw = new StreamWriter(file, false, enc)) + { + sw.Write(text); + } + } + #endregion - /// - /// Recursively convert classes - /// - /// folder to convert - static void ExploreFolder(string path) - { - currentFile = path; - known.Add(path); + /// + /// Recursively convert classes + /// + /// folder to convert + static void ExploreFolder(string path) + { + currentFile = path; + known.Add(path); - // convert classes - string[] files = Directory.GetFiles(path, "*.as"); - ASClass fClass; - string destFile; - DateTime timestamp; - int codepage; - foreach(string file in files) - { - currentFile = file; - destFile = destPath+file.Substring(srcPath.Length); - // not modified: ignore - timestamp = File.GetLastWriteTime(file); - if (File.Exists(destFile) && File.GetLastWriteTime(destFile) == timestamp) - continue; + // convert classes + string[] files = Directory.GetFiles(path, "*.as"); + ASClass fClass; + string destFile; + DateTime timestamp; + int codepage; + foreach(string file in files) + { + currentFile = file; + destFile = destPath+file.Substring(srcPath.Length); + // not modified: ignore + timestamp = File.GetLastWriteTime(file); + if (File.Exists(destFile) && File.GetLastWriteTime(destFile) == timestamp) + continue; - // parse class - codepage = GetFileCodepage(file); - fClass = new ASClass(); - fClass.FileName = file; - ASClassParser.ParseClass(fClass); - if (fClass.IsVoid()) - continue; + // parse class + codepage = GetFileCodepage(file); + fClass = new ASClass(); + fClass.FileName = file; + ASClassParser.ParseClass(fClass); + if (fClass.IsVoid()) + continue; - // create intrinsic - Directory.CreateDirectory(Path.GetDirectoryName(destFile)); - Write(destFile, fClass.GenerateIntrinsic(), Encoding.GetEncoding(codepage)); - File.SetCreationTime(destFile, timestamp); - File.SetLastWriteTime(destFile, timestamp); - total++; - } + // create intrinsic + Directory.CreateDirectory(Path.GetDirectoryName(destFile)); + Write(destFile, fClass.GenerateIntrinsic(), Encoding.GetEncoding(codepage)); + File.SetCreationTime(destFile, timestamp); + File.SetLastWriteTime(destFile, timestamp); + total++; + } - // explore subfolders - currentFile = path; - string[] dirs = Directory.GetDirectories(path); - foreach(string dir in dirs) - { - if (!known.Contains(dir)) ExploreFolder(dir); - } - } + // explore subfolders + currentFile = path; + string[] dirs = Directory.GetDirectories(path); + foreach(string dir in dirs) + { + if (!known.Contains(dir)) ExploreFolder(dir); + } + } - /// - /// Remove empty folders and classes without match in the destination path - /// - /// Path to clean - /// Don't delete this folder if it's empty - /// The folder was empty & deleted - static bool CleanFolder(string path, bool keepFolder) - { - known.Add(path); + /// + /// Remove empty folders and classes without match in the destination path + /// + /// Path to clean + /// Don't delete this folder if it's empty + /// The folder was empty & deleted + static bool CleanFolder(string path, bool keepFolder) + { + known.Add(path); - // check classes without match - string[] files = Directory.GetFiles(path, "*.as"); - string checkFile; - int filesCount = files.Length; - foreach(string file in files) - { - checkFile = srcPath+file.Substring(destPath.Length); - if (!File.Exists(checkFile)) - { - File.Delete(file); - filesCount--; - filesCleaned++; - } - } + // check classes without match + string[] files = Directory.GetFiles(path, "*.as"); + string checkFile; + int filesCount = files.Length; + foreach(string file in files) + { + checkFile = srcPath+file.Substring(destPath.Length); + if (!File.Exists(checkFile)) + { + File.Delete(file); + filesCount--; + filesCleaned++; + } + } - // explore subfolders - string[] dirs = Directory.GetDirectories(path); - int folderCount = dirs.Length; - foreach(string dir in dirs) - { - if (!known.Contains(dir)) - if (CleanFolder(dir, false)) - folderCount--; - } + // explore subfolders + string[] dirs = Directory.GetDirectories(path); + int folderCount = dirs.Length; + foreach(string dir in dirs) + { + if (!known.Contains(dir)) + if (CleanFolder(dir, false)) + folderCount--; + } - // folder is empty - // -> will fail silently if there are still files in the folder - if (!keepFolder && (folderCount == 0) && (filesCount == 0)) - { - try - { - Directory.Delete(path); - foldersCleaned++; - return true; - } - catch {} - } - return false; - } + // folder is empty + // -> will fail silently if there are still files in the folder + if (!keepFolder && (folderCount == 0) && (filesCount == 0)) + { + try + { + Directory.Delete(path); + foldersCleaned++; + return true; + } + catch {} + } + return false; + } - /// - /// IGen application - /// - public static int Main(string[] args) - { - // parameters - if (args.Length < 2) - { - Console.WriteLine("IGen 1.1 - Intrinsic Classes Generator for ActionScript 2"); - Console.WriteLine("Copyright (c) 2007 Philippe Elsass"); - Console.WriteLine(""); - Console.WriteLine("Usage: igen [-clean] "); - return 1; - } - clean = (args[0] == "-clean"); - srcPath = args[args.Length-2]; - destPath = args[args.Length-1]; - if (srcPath == destPath) - { - Console.WriteLine("IGen Error: and must be different"); - return 2; - } + /// + /// IGen application + /// + public static int Main(string[] args) + { + // parameters + if (args.Length < 2) + { + Console.WriteLine("IGen 1.1 - Intrinsic Classes Generator for ActionScript 2"); + Console.WriteLine("Copyright (c) 2007 Philippe Elsass"); + Console.WriteLine(""); + Console.WriteLine("Usage: igen [-clean] "); + return 1; + } + clean = (args[0] == "-clean"); + srcPath = args[args.Length-2]; + destPath = args[args.Length-1]; + if (srcPath == destPath) + { + Console.WriteLine("IGen Error: and must be different"); + return 2; + } - // parser context - ASClassParser.Context = new MainClass(); - // exploration context - known = new ArrayList(); - known.Add(destPath); + // parser context + ASClassParser.Context = new MainClass(); + // exploration context + known = new ArrayList(); + known.Add(destPath); - // explore - try - { - ExploreFolder(srcPath); - if (clean) - CleanFolder(destPath, true); - } - catch (Exception ex) - { - Console.WriteLine("IGen Exception: "+currentFile+"\n"+ex.Message+"\n"+ex.StackTrace); - return 3; - } + // explore + try + { + ExploreFolder(srcPath); + if (clean) + CleanFolder(destPath, true); + } + catch (Exception ex) + { + Console.WriteLine("IGen Exception: "+currentFile+"\n"+ex.Message+"\n"+ex.StackTrace); + return 3; + } - // done - Console.WriteLine("IGen: "+total+" classes processed"); - if (clean) - { - Console.WriteLine(" "+filesCleaned+" classes cleaned"); - Console.WriteLine(" "+foldersCleaned+" empty folders removed"); - } - return 0; - } - } + // done + Console.WriteLine("IGen: "+total+" classes processed"); + if (clean) + { + Console.WriteLine(" "+filesCleaned+" classes cleaned"); + Console.WriteLine(" "+foldersCleaned+" empty folders removed"); + } + return 0; + } + } } diff --git a/External/Tools/IconComposer/IconComposer.csproj b/External/Tools/IconComposer/IconComposer.csproj index d703a70593..ad796cf3e2 100644 --- a/External/Tools/IconComposer/IconComposer.csproj +++ b/External/Tools/IconComposer/IconComposer.csproj @@ -2,8 +2,6 @@ Debug AnyCPU - 8.0.50727 - 2.0 {A659C7D9-F2C4-44EF-A0E9-3283648619EC} WinExe Properties @@ -11,10 +9,14 @@ icomp - 2.0 - v3.5 + net48 + true + false + false + false + false true @@ -66,12 +68,5 @@ ComposerForm.cs - - + \ No newline at end of file diff --git a/External/Tools/IconResources/IconResources.csproj b/External/Tools/IconResources/IconResources.csproj index 675fc2fbcc..794b5a3ed8 100644 --- a/External/Tools/IconResources/IconResources.csproj +++ b/External/Tools/IconResources/IconResources.csproj @@ -1,35 +1,33 @@  - + Debug AnyCPU - 9.0.21022 - 2.0 {2F27A4B8-82C3-403E-9A99-EB332189BACE} WinExe Properties IconResources winres - v2.0 + net48 + true + false + false + false 512 Properties\IconResources.res LocalIntranet false + + + + + publish\ true Disk - false - Foreground - 7 - Days - false - false true - 0 - 1.0.0.%2a - false false - true + false false @@ -49,6 +47,16 @@ 4 Auto + + x86 + bin\x86\Debug\ + + + x86 + ..\..\..\FlashDevelop\Bin\Debug\Tools\winres\ + TRACE + true + @@ -64,29 +72,5 @@ - - - False - .NET Framework 2.0 %28x86%29 - true - - - False - .NET Framework 3.0 %28x86%29 - false - - - False - .NET Framework 3.5 - false - - - - + \ No newline at end of file diff --git a/External/Tools/IconResources/IconResources.sln b/External/Tools/IconResources/IconResources.sln index 002d970fb4..1dfc202bcd 100644 --- a/External/Tools/IconResources/IconResources.sln +++ b/External/Tools/IconResources/IconResources.sln @@ -1,18 +1,26 @@  -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C# Express 2008 +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IconResources", "IconResources.csproj", "{2F27A4B8-82C3-403E-9A99-EB332189BACE}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {2F27A4B8-82C3-403E-9A99-EB332189BACE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F27A4B8-82C3-403E-9A99-EB332189BACE}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2F27A4B8-82C3-403E-9A99-EB332189BACE}.Debug|x86.ActiveCfg = Debug|x86 + {2F27A4B8-82C3-403E-9A99-EB332189BACE}.Debug|x86.Build.0 = Debug|x86 {2F27A4B8-82C3-403E-9A99-EB332189BACE}.Release|Any CPU.ActiveCfg = Release|Any CPU {2F27A4B8-82C3-403E-9A99-EB332189BACE}.Release|Any CPU.Build.0 = Release|Any CPU + {2F27A4B8-82C3-403E-9A99-EB332189BACE}.Release|x86.ActiveCfg = Release|x86 + {2F27A4B8-82C3-403E-9A99-EB332189BACE}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/External/Tools/IconResources/Properties/IconResources.res b/External/Tools/IconResources/Properties/IconResources.res index 2f9ca9ddd7..56b32a5f28 100644 Binary files a/External/Tools/IconResources/Properties/IconResources.res and b/External/Tools/IconResources/Properties/IconResources.res differ diff --git a/External/Tools/MXMLCompletionBuilder/MXMLCompletionBuilder/MXMLCompletionBuilder.csproj b/External/Tools/MXMLCompletionBuilder/MXMLCompletionBuilder/MXMLCompletionBuilder.csproj index bcf8fdfcb5..c03a506d9d 100644 --- a/External/Tools/MXMLCompletionBuilder/MXMLCompletionBuilder/MXMLCompletionBuilder.csproj +++ b/External/Tools/MXMLCompletionBuilder/MXMLCompletionBuilder/MXMLCompletionBuilder.csproj @@ -1,16 +1,18 @@  - + Debug AnyCPU - 9.0.30729 - 2.0 {BEEA3146-4CE6-400A-9D21-7217760404D2} - Exe + WinExe Properties MXMLCompletionBuilder MXMLCompletionBuilder - v3.5 + net48 + true + false + false + false 512 @@ -65,12 +67,4 @@ - - \ No newline at end of file diff --git a/External/Tools/PHPFunctionsParser/PHPFunctionsParser/PHPFunctionsParser.csproj b/External/Tools/PHPFunctionsParser/PHPFunctionsParser/PHPFunctionsParser.csproj index d8e9cd3c53..38968c440e 100644 --- a/External/Tools/PHPFunctionsParser/PHPFunctionsParser/PHPFunctionsParser.csproj +++ b/External/Tools/PHPFunctionsParser/PHPFunctionsParser/PHPFunctionsParser.csproj @@ -1,16 +1,18 @@  - + Debug AnyCPU - 9.0.21022 - 2.0 {21040C2F-A055-4C8B-82FC-5F72260243A6} - Exe + WinExe Properties PHPFunctionsParser PHPFunctionsParser - v2.0 + net48 + true + false + false + false 512 @@ -39,12 +41,4 @@ - - \ No newline at end of file diff --git a/External/Tools/SOReader/SOReader.csproj b/External/Tools/SOReader/SOReader.csproj index 3a7f205ae8..48ca417ea5 100644 --- a/External/Tools/SOReader/SOReader.csproj +++ b/External/Tools/SOReader/SOReader.csproj @@ -2,8 +2,6 @@ Debug AnyCPU - 9.0.30729 - 2.0 {15E23F72-78EF-4C9B-98BB-0030E0B4968D} WinExe Properties @@ -11,8 +9,11 @@ SOReaderUI - 2.0 - v2.0 + net48 + true + false + false + false @@ -143,12 +144,4 @@ Designer - - \ No newline at end of file diff --git a/External/Tools/SOReader/SOReader.dll b/External/Tools/SOReader/SOReader.dll old mode 100644 new mode 100755 diff --git a/External/Tools/SetVersion/Program.cs b/External/Tools/SetVersion/Program.cs index 832c95d1ef..d59f087ba5 100644 --- a/External/Tools/SetVersion/Program.cs +++ b/External/Tools/SetVersion/Program.cs @@ -25,20 +25,40 @@ static void Main(string[] args) Console.WriteLine("Template not found: " + revOut); return; } - var head = File.ReadAllText(Path.Combine(git, "HEAD")).Trim(); - var headRef = Regex.Match(head, "ref: refs/heads/(.*)"); - if (!headRef.Success) + var headFile = Path.Combine(git, "HEAD"); + Match headRef; + if (!File.Exists(headFile)) + { + Console.WriteLine("Git folder not found"); + headRef = null; + } + else + { + var head = File.ReadAllText(headFile).Trim(); + headRef = Regex.Match(head, "ref: refs/heads/(.*)"); + } + if (headRef == null || !headRef.Success) { - Console.WriteLine("SetVersion: Can not find HEAD ref, write from env vars."); commit = Environment.ExpandEnvironmentVariables("%APPVEYOR_REPO_COMMIT%"); - if (commit.Length == 40) commit = commit.Substring(0, 10); - branch = Environment.ExpandEnvironmentVariables("%APPVEYOR_REPO_BRANCH%"); - build = Environment.ExpandEnvironmentVariables("%APPVEYOR_BUILD_NUMBER%"); + if (commit != "%APPVEYOR_REPO_COMMIT%") + { + Console.WriteLine("SetVersion: Can not find HEAD ref, write from env vars."); + if (commit.Length == 40) commit = commit.Substring(0, 10); + branch = Environment.ExpandEnvironmentVariables("%APPVEYOR_REPO_BRANCH%"); + build = Environment.ExpandEnvironmentVariables("%APPVEYOR_BUILD_NUMBER%"); + } + else + { + Console.WriteLine("SetVersion: Can not find HEAD ref nor CI env vars. Setting dummy values"); + commit = string.Empty; + branch = "local"; + build = "0"; + } WriteFile(output, revOut, commit, branch, build); return; } branch = headRef.Groups[1].Value; - var refPath = Path.Combine(Path.Combine(git, "refs\\heads"), branch); + var refPath = Path.Combine(Path.Combine(git, Path.Combine("refs", "heads")), branch); if (!File.Exists(refPath)) { Console.WriteLine("SetVersion: Can not read ref commit hash."); diff --git a/External/Tools/SetVersion/SetVersion.csproj b/External/Tools/SetVersion/SetVersion.csproj index ce1fdef048..5bcbacd456 100644 --- a/External/Tools/SetVersion/SetVersion.csproj +++ b/External/Tools/SetVersion/SetVersion.csproj @@ -1,18 +1,19 @@  - + Debug x86 - 8.0.30703 - 2.0 {58296E46-7B4B-45CF-A8BA-0A91B6D8080A} - Exe + WinExe Properties SetVersion SetVersion - v2.0 - - + net48 + true + false + false + false + Client 512 @@ -43,12 +44,4 @@ - - \ No newline at end of file diff --git a/External/Tools/SetVersion/SetVersion.exe b/External/Tools/SetVersion/SetVersion.exe old mode 100644 new mode 100755 index 87918ebf2a..a629fe8daf Binary files a/External/Tools/SetVersion/SetVersion.exe and b/External/Tools/SetVersion/SetVersion.exe differ diff --git a/External/Tools/SnippetEditor/SnippetEditor.csproj b/External/Tools/SnippetEditor/SnippetEditor.csproj index e27a048155..a814b2ce0d 100644 --- a/External/Tools/SnippetEditor/SnippetEditor.csproj +++ b/External/Tools/SnippetEditor/SnippetEditor.csproj @@ -2,8 +2,6 @@ Debug AnyCPU - 9.0.30729 - 2.0 {6D7024C6-9D59-4AEA-886E-91F3FD72DAEC} WinExe Properties @@ -11,8 +9,11 @@ snedit - 2.0 - v3.5 + net48 + true + false + false + false @@ -65,12 +66,4 @@ - - \ No newline at end of file diff --git a/External/Tools/SwfOp/ByteCode/ActionCode.cs b/External/Tools/SwfOp/ByteCode/ActionCode.cs index 0a136ac054..7350d66701 100644 --- a/External/Tools/SwfOp/ByteCode/ActionCode.cs +++ b/External/Tools/SwfOp/ByteCode/ActionCode.cs @@ -1,260 +1,260 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace SwfOp.ByteCode -{ - /// - /// Action (byte-)codes for actions derived from . - /// - /// - /// Pseudo actions are given negative values since they are not compiled into swf. - /// - public enum ActionCode { - - /// NextFrame instruction - NextFrame = 0x04, - /// PreviousFrame instruction - PreviousFrame = 0x05, - /// Play instruction - Play = 0x06, - /// Stop instruction - Stop = 0x07, - /// ToggleQuality instruction - ToggleQuality = 0x08, - /// StopSounds instruction - StopSounds = 0x09, - /// Pop instruction - Pop = 0x17, - /// Add instruction - Add = 0x0A, - /// Subtract instruction - Subtract = 0x0B, - /// Multiply instruction - Multiply = 0x0C, - /// Divide instruction - Divide = 0x0D, - /// Equals instruction - Equals = 0x0E, - /// Less instruction - Less = 0x0F, - /// And instruction - And = 0x10, - /// Or instruction - Or = 0x11, - /// Not instruction - Not = 0x12, - /// StringAdd instruction - StringAdd = 0x21, - /// StringEquals instruction - StringEquals = 0x13, - /// StringExtract instruction - StringExtract = 0x15, - /// StringLength instruction - StringLength = 0x14, - /// StringLess instruction - StringLess = 0x29, - /// MBStringExtract instruction - MBStringExtract = 0x35, - /// MBStringLength instruction - MBStringLength = 0x31, - /// AsciiToChar instruction - AsciiToChar = 0x33, - /// CharToAscii instruction - CharToAscii = 0x32, - /// ToInteger instruction - ToInteger = 0x18, - /// MBAsciiToChar instruction - MBAsciiToChar = 0x37, - /// MBCharToAscii instruction - MBCharToAscii = 0x36, - /// Call instruction - Call = 0x9E, - /// GetVariable instruction - GetVariable = 0x1C, - /// SetVariable instruction - SetVariable = 0x1D, - /// GetPropertye instruction - GetProperty = 0x22, - /// RemoveSprite instruction - RemoveSprite = 0x25, - /// SetProperty instruction - SetProperty = 0x23, - /// SetTarget2 instruction - SetTarget2 = 0x20, - /// StartDrag instruction - StartDrag = 0x27, - /// CloneSprite instruction - CloneSprite = 0x24, - /// EndDrag instruction - EndDrag = 0x28, - /// GetTime instruction - GetTime = 0x34, - /// RandomNumber instruction - RandomNumber = 0x30, - /// Trace instruction - Trace = 0x26, - /// CallFunction instruction - CallFunction = 0x3D, - /// CallMethod instruction - CallMethod = 0x52, - /// DefineLocal instruction - DefineLocal = 0x3C, - /// DefineLocal2 instruction - DefineLocal2 = 0x41, - /// Delete instruction - Delete = 0x3A, - /// Delete2 instruction - Delete2 = 0x3B, - /// Enumerate instruction - Enumerate = 0x46, - /// Equals2 instruction - Equals2 = 0x49, - /// GetMembe instruction - GetMember = 0x4E, - /// InitArray instruction - InitArray = 0x42, - /// InitObject instruction - InitObject = 0x43, - /// NewMethod instruction - NewMethod = 0x53, - /// NewObject instruction - NewObject = 0x40, - /// SetMember instruction - SetMember = 0x4F, - /// TargetPath instruction - TargetPath = 0x45, - /// ToNumber instruction - ToNumber = 0x4A, - /// ToString instruction - ToString = 0x4B, - /// TypeOf instruction - TypeOf = 0x44, - /// Add2 instruction - Add2 = 0x47, - /// Less2 instruction - Less2 = 0x48, - /// Modulo instruction - Modulo = 0x3F, - /// BitAnd instruction - BitAnd = 0x60, - /// BitLShift instruction - BitLShift = 0x63, - /// BitOr instruction - BitOr = 0x61, - /// BitRShift instruction - BitRShift = 0x64, - /// BitURShift instruction - BitURShift = 0x65, - /// BitXor instruction - BitXor = 0x62, - /// Decremente instruction - Decrement = 0x51, - /// Increment instruction - Increment = 0x50, - /// PushDuplicate instruction - PushDuplicate = 0x4C, - /// Return instruction - Return = 0x3E, - /// StackSwap instruction - StackSwap = 0x4D, - /// InstanceOf instruction - InstanceOf = 0x54, - /// Enumerate2 instruction - Enumerate2 = 0x55, - /// StrictEquals instruction - StrictEquals = 0x66, - /// Greater instruction - Greater = 0x67, - /// StringGreater instruction - StringGreater = 0x68, - /// Extends instruction - Extends = 0x69, - /// CastOp instruction - CastOp = 0x2B, - /// Implements instruction - Implements = 0x2C, - /// Throw instruction - Throw = 0x2A, - /// Action Record End - End = 0x00, - - /// multibyte actions: - /// SetTarget instruction; multi-byte - SetTarget = 0x8B, - /// GotoFrame instruction; multi-byte - GotoFrame = 0x81, - /// GotoFrame2 instruction; multi-byte - GotoFrame2 = 0x9F, - /// GoToLabel instruction; multi-byte - GoToLabel = 0x8C, - /// GetURL instruction; multi-byte - GetURL = 0x83, - /// GetURL2 instruction; multi-byte - GetURL2 = 0x9A, - /// StoreRegister instruction; multi-byte - StoreRegister = 0x87, - /// ConstantPool instruction; multi-byte - ConstantPool = 0x88, - - /// jump actions: - /// If instruction (conditional branch); multi-byte - If = 0x9D, - /// Jump instruction (branch); multi-byte - Jump = 0x99, - - /// block actions: - /// DefineFunction (block) instruction; multi-byte - DefineFunction = 0x9B, - /// DefineFunction2 (block) instruction; multi-byte - DefineFunction2 = 0x8E, - - /// Push instruction; multi-byte - Push = 0x96, - /// Try (block) instruction; multi-byte - Try = 0x8F, - /// With instruction; multi-byte - With = 0x94, - /// WaitForFrame instruction; multi-byte - WaitForFrame = 0x8A, - /// WaitForFrame2 instruction; multi-byte - WaitForFrame2 = 0x8D, - - /// pseudo actions: - /// Dummy pseudo instruction - Dummy = -1, - /// PushList pseudo instruction - PushList = -2, - /// Label pseudo instruction - Label = -3, - /// Catch pseudo instruction - Catch = -4, - /// Finally pseudo instruction - Finally = -5, - /// EndTry pseudo instruction - EndTry = -6, - /// EndWith pseudo instruction - EndWith = -7, - /// EndWait pseudo instruction - EndWait = -8, - /// action container pseudo instruction - Container = -9 - } +{ + /// + /// Action (byte-)codes for actions derived from . + /// + /// + /// Pseudo actions are given negative values since they are not compiled into swf. + /// + public enum ActionCode { + + /// NextFrame instruction + NextFrame = 0x04, + /// PreviousFrame instruction + PreviousFrame = 0x05, + /// Play instruction + Play = 0x06, + /// Stop instruction + Stop = 0x07, + /// ToggleQuality instruction + ToggleQuality = 0x08, + /// StopSounds instruction + StopSounds = 0x09, + /// Pop instruction + Pop = 0x17, + /// Add instruction + Add = 0x0A, + /// Subtract instruction + Subtract = 0x0B, + /// Multiply instruction + Multiply = 0x0C, + /// Divide instruction + Divide = 0x0D, + /// Equals instruction + Equals = 0x0E, + /// Less instruction + Less = 0x0F, + /// And instruction + And = 0x10, + /// Or instruction + Or = 0x11, + /// Not instruction + Not = 0x12, + /// StringAdd instruction + StringAdd = 0x21, + /// StringEquals instruction + StringEquals = 0x13, + /// StringExtract instruction + StringExtract = 0x15, + /// StringLength instruction + StringLength = 0x14, + /// StringLess instruction + StringLess = 0x29, + /// MBStringExtract instruction + MBStringExtract = 0x35, + /// MBStringLength instruction + MBStringLength = 0x31, + /// AsciiToChar instruction + AsciiToChar = 0x33, + /// CharToAscii instruction + CharToAscii = 0x32, + /// ToInteger instruction + ToInteger = 0x18, + /// MBAsciiToChar instruction + MBAsciiToChar = 0x37, + /// MBCharToAscii instruction + MBCharToAscii = 0x36, + /// Call instruction + Call = 0x9E, + /// GetVariable instruction + GetVariable = 0x1C, + /// SetVariable instruction + SetVariable = 0x1D, + /// GetPropertye instruction + GetProperty = 0x22, + /// RemoveSprite instruction + RemoveSprite = 0x25, + /// SetProperty instruction + SetProperty = 0x23, + /// SetTarget2 instruction + SetTarget2 = 0x20, + /// StartDrag instruction + StartDrag = 0x27, + /// CloneSprite instruction + CloneSprite = 0x24, + /// EndDrag instruction + EndDrag = 0x28, + /// GetTime instruction + GetTime = 0x34, + /// RandomNumber instruction + RandomNumber = 0x30, + /// Trace instruction + Trace = 0x26, + /// CallFunction instruction + CallFunction = 0x3D, + /// CallMethod instruction + CallMethod = 0x52, + /// DefineLocal instruction + DefineLocal = 0x3C, + /// DefineLocal2 instruction + DefineLocal2 = 0x41, + /// Delete instruction + Delete = 0x3A, + /// Delete2 instruction + Delete2 = 0x3B, + /// Enumerate instruction + Enumerate = 0x46, + /// Equals2 instruction + Equals2 = 0x49, + /// GetMembe instruction + GetMember = 0x4E, + /// InitArray instruction + InitArray = 0x42, + /// InitObject instruction + InitObject = 0x43, + /// NewMethod instruction + NewMethod = 0x53, + /// NewObject instruction + NewObject = 0x40, + /// SetMember instruction + SetMember = 0x4F, + /// TargetPath instruction + TargetPath = 0x45, + /// ToNumber instruction + ToNumber = 0x4A, + /// ToString instruction + ToString = 0x4B, + /// TypeOf instruction + TypeOf = 0x44, + /// Add2 instruction + Add2 = 0x47, + /// Less2 instruction + Less2 = 0x48, + /// Modulo instruction + Modulo = 0x3F, + /// BitAnd instruction + BitAnd = 0x60, + /// BitLShift instruction + BitLShift = 0x63, + /// BitOr instruction + BitOr = 0x61, + /// BitRShift instruction + BitRShift = 0x64, + /// BitURShift instruction + BitURShift = 0x65, + /// BitXor instruction + BitXor = 0x62, + /// Decremente instruction + Decrement = 0x51, + /// Increment instruction + Increment = 0x50, + /// PushDuplicate instruction + PushDuplicate = 0x4C, + /// Return instruction + Return = 0x3E, + /// StackSwap instruction + StackSwap = 0x4D, + /// InstanceOf instruction + InstanceOf = 0x54, + /// Enumerate2 instruction + Enumerate2 = 0x55, + /// StrictEquals instruction + StrictEquals = 0x66, + /// Greater instruction + Greater = 0x67, + /// StringGreater instruction + StringGreater = 0x68, + /// Extends instruction + Extends = 0x69, + /// CastOp instruction + CastOp = 0x2B, + /// Implements instruction + Implements = 0x2C, + /// Throw instruction + Throw = 0x2A, + /// Action Record End + End = 0x00, + + /// multibyte actions: + /// SetTarget instruction; multi-byte + SetTarget = 0x8B, + /// GotoFrame instruction; multi-byte + GotoFrame = 0x81, + /// GotoFrame2 instruction; multi-byte + GotoFrame2 = 0x9F, + /// GoToLabel instruction; multi-byte + GoToLabel = 0x8C, + /// GetURL instruction; multi-byte + GetURL = 0x83, + /// GetURL2 instruction; multi-byte + GetURL2 = 0x9A, + /// StoreRegister instruction; multi-byte + StoreRegister = 0x87, + /// ConstantPool instruction; multi-byte + ConstantPool = 0x88, + + /// jump actions: + /// If instruction (conditional branch); multi-byte + If = 0x9D, + /// Jump instruction (branch); multi-byte + Jump = 0x99, + + /// block actions: + /// DefineFunction (block) instruction; multi-byte + DefineFunction = 0x9B, + /// DefineFunction2 (block) instruction; multi-byte + DefineFunction2 = 0x8E, + + /// Push instruction; multi-byte + Push = 0x96, + /// Try (block) instruction; multi-byte + Try = 0x8F, + /// With instruction; multi-byte + With = 0x94, + /// WaitForFrame instruction; multi-byte + WaitForFrame = 0x8A, + /// WaitForFrame2 instruction; multi-byte + WaitForFrame2 = 0x8D, + + /// pseudo actions: + /// Dummy pseudo instruction + Dummy = -1, + /// PushList pseudo instruction + PushList = -2, + /// Label pseudo instruction + Label = -3, + /// Catch pseudo instruction + Catch = -4, + /// Finally pseudo instruction + Finally = -5, + /// EndTry pseudo instruction + EndTry = -6, + /// EndWith pseudo instruction + EndWith = -7, + /// EndWait pseudo instruction + EndWait = -8, + /// action container pseudo instruction + Container = -9 + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionAdd.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionAdd.cs index 3364d3ab19..60e01bd231 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionAdd.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionAdd.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionAdd : BaseAction { - - /// - /// constructor - /// - public ActionAdd():base(ActionCode.Add) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionAdd : BaseAction { + + /// + /// constructor + /// + public ActionAdd():base(ActionCode.Add) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "add"; - } - } + /// overriden ToString method + public override string ToString() { + return "add"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionAdd2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionAdd2.cs index d610fe5e10..f0e1c05cbd 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionAdd2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionAdd2.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionAdd2 : BaseAction { - - /// - /// constructor - /// - public ActionAdd2():base(ActionCode.Add2) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionAdd2 : BaseAction { + + /// + /// constructor + /// + public ActionAdd2():base(ActionCode.Add2) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "add2"; - } - } + /// overriden ToString method + public override string ToString() { + return "add2"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionAnd.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionAnd.cs index 3712a36f0c..9fec26265a 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionAnd.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionAnd.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionAnd : BaseAction { - - /// - /// constructor - /// - public ActionAnd():base(ActionCode.And) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionAnd : BaseAction { + + /// + /// constructor + /// + public ActionAnd():base(ActionCode.And) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "and"; - } - } + /// overriden ToString method + public override string ToString() { + return "and"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionAsciiiToChar.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionAsciiiToChar.cs index 2a1563ad6c..69af760a4e 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionAsciiiToChar.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionAsciiiToChar.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,28 +25,28 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionAsciiToChar : BaseAction { - - /// - /// constructor - /// - public ActionAsciiToChar():base(ActionCode.AsciiToChar) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionAsciiToChar : BaseAction { + + /// + /// constructor + /// + public ActionAsciiToChar():base(ActionCode.AsciiToChar) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "ascii2char"; - } - } + /// overriden ToString method + public override string ToString() { + return "ascii2char"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionBitAnd.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionBitAnd.cs index de902989fd..db768ba98e 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionBitAnd.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionBitAnd.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,28 +24,28 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionBitAnd : BaseAction { - - /// - /// constructor - /// - public ActionBitAnd():base(ActionCode.BitAnd) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionBitAnd : BaseAction { + + /// + /// constructor + /// + public ActionBitAnd():base(ActionCode.BitAnd) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "bitWiseAnd"; - } - } + /// overriden ToString method + public override string ToString() { + return "bitWiseAnd"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionBitLShift.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionBitLShift.cs index 9ea485f817..5c023c0966 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionBitLShift.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionBitLShift.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionBitLShift : BaseAction { - - /// - /// constructor - /// - public ActionBitLShift():base(ActionCode.BitLShift) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionBitLShift : BaseAction { + + /// + /// constructor + /// + public ActionBitLShift():base(ActionCode.BitLShift) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "bit shift l"; - } - } + /// overriden ToString method + public override string ToString() { + return "bit shift l"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionBitOr.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionBitOr.cs index 45178e3473..45ad1478fb 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionBitOr.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionBitOr.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionBitOr : BaseAction { - - /// - /// constructor - /// - public ActionBitOr():base(ActionCode.BitOr) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionBitOr : BaseAction { + + /// + /// constructor + /// + public ActionBitOr():base(ActionCode.BitOr) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "bit or"; - } - } + /// overriden ToString method + public override string ToString() { + return "bit or"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionBitRShift.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionBitRShift.cs index f9aeef212f..f57715f2c5 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionBitRShift.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionBitRShift.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,28 +24,28 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionBitRShift : BaseAction { - - /// - /// constructor - /// - public ActionBitRShift():base(ActionCode.BitRShift) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionBitRShift : BaseAction { + + /// + /// constructor + /// + public ActionBitRShift():base(ActionCode.BitRShift) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "bit shift r"; - } - } + /// overriden ToString method + public override string ToString() { + return "bit shift r"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionBitURShift.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionBitURShift.cs index 620dac109f..4469d63547 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionBitURShift.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionBitURShift.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionBitURShift : BaseAction { - - /// - /// constructor - /// - public ActionBitURShift():base(ActionCode.BitURShift) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionBitURShift : BaseAction { + + /// + /// constructor + /// + public ActionBitURShift():base(ActionCode.BitURShift) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "bit shift ur"; - } - } + /// overriden ToString method + public override string ToString() { + return "bit shift ur"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionBitXor.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionBitXor.cs index 6f4501766f..012162c5fc 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionBitXor.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionBitXor.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionBitXor : BaseAction { - - /// - /// constructor - /// - public ActionBitXor():base(ActionCode.BitXor) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionBitXor : BaseAction { + + /// + /// constructor + /// + public ActionBitXor():base(ActionCode.BitXor) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "bit xor"; - } - } + /// overriden ToString method + public override string ToString() { + return "bit xor"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionCall.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionCall.cs index 0820bb5152..63ee0326c8 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionCall.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionCall.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionCall : BaseAction { - - /// - /// constructor - /// - public ActionCall():base(ActionCode.Call) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "call"; - } - } + public class ActionCall : BaseAction { + + /// + /// constructor + /// + public ActionCall():base(ActionCode.Call) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "call"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionCallFunction.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionCallFunction.cs index 4b21241d1c..591a0313cc 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionCallFunction.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionCallFunction.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,46 +25,46 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - - /// - /// bytecode instruction object - /// + + /// + /// bytecode instruction object + /// - public class ActionCallFunction : BaseAction { - - /// - /// constructor - /// - public ActionCallFunction():base(ActionCode.CallFunction) - { - } - - private int numArgs = 0; - - /// - /// argument count as found by - /// - public int NumArgs { - set { - numArgs = value; - } - } - - /// - public override int PopCount { - - get { - return numArgs+2; - } - } - - /// - public override int PushCount { get { return 1; } } - - /// overriden ToString method - public override string ToString() { - return String.Format("callFunction ({0} args)",numArgs); - } - } + public class ActionCallFunction : BaseAction { + + /// + /// constructor + /// + public ActionCallFunction():base(ActionCode.CallFunction) + { + } + + private int numArgs = 0; + + /// + /// argument count as found by + /// + public int NumArgs { + set { + numArgs = value; + } + } + + /// + public override int PopCount { + + get { + return numArgs+2; + } + } + + /// + public override int PushCount { get { return 1; } } + + /// overriden ToString method + public override string ToString() { + return String.Format("callFunction ({0} args)",numArgs); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionCallMethod.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionCallMethod.cs index 362268b810..a1ea8b88b6 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionCallMethod.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionCallMethod.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,43 +24,43 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionCallMethod : BaseAction { - - /// - /// constructor - /// - public ActionCallMethod():base(ActionCode.CallMethod) - { - } - - private int numArgs = 0; - - /// - /// argument count as found by - /// - public int NumArgs { - set { - numArgs = value; - } - } - - /// - public override int PopCount { - get { - return numArgs+3; - } - } - - /// - public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return String.Format("callMethod ({0} args)",numArgs); - } - } + public class ActionCallMethod : BaseAction { + + /// + /// constructor + /// + public ActionCallMethod():base(ActionCode.CallMethod) + { + } + + private int numArgs = 0; + + /// + /// argument count as found by + /// + public int NumArgs { + set { + numArgs = value; + } + } + + /// + public override int PopCount { + get { + return numArgs+3; + } + } + + /// + public override int PushCount { get { return 1; } } + /// overriden ToString method + public override string ToString() { + return String.Format("callMethod ({0} args)",numArgs); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionCastOp.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionCastOp.cs index 2490f9e2c5..a27c5c6946 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionCastOp.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionCastOp.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionCastOp : BaseAction { - - /// - /// constructor - /// - public ActionCastOp():base(ActionCode.CastOp) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionCastOp : BaseAction { + + /// + /// constructor + /// + public ActionCastOp():base(ActionCode.CastOp) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "cast"; - } - } + /// overriden ToString method + public override string ToString() { + return "cast"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionCatch.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionCatch.cs index da146d4920..6dc7c186b0 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionCatch.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionCatch.cs @@ -1,56 +1,56 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionCatch : BaseAction { - - /// - /// constructor - /// - public ActionCatch():base(ActionCode.Catch) - { - } - - /// overriden ToString method - public override string ToString() { - return "catch "; - } - - /// - public override int ByteCount { - get { - return 0; - } - } - - /// - public override void Compile(BinaryWriter w) - {} - } + public class ActionCatch : BaseAction { + + /// + /// constructor + /// + public ActionCatch():base(ActionCode.Catch) + { + } + + /// overriden ToString method + public override string ToString() { + return "catch "; + } + + /// + public override int ByteCount { + get { + return 0; + } + } + + /// + public override void Compile(BinaryWriter w) + {} + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionCharToAscii.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionCharToAscii.cs index edb70965ba..ccbb06283e 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionCharToAscii.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionCharToAscii.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,29 +25,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionCharToAscii : BaseAction { - - /// - /// constructor - /// - public ActionCharToAscii():base(ActionCode.CharToAscii) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionCharToAscii : BaseAction { + + /// + /// constructor + /// + public ActionCharToAscii():base(ActionCode.CharToAscii) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "char2ascii"; - } - } + /// overriden ToString method + public override string ToString() { + return "char2ascii"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionCloneSprite.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionCloneSprite.cs index a0092d8b42..441a89c657 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionCloneSprite.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionCloneSprite.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionCloneSprite : BaseAction { - - /// - /// constructor - /// - public ActionCloneSprite():base(ActionCode.CloneSprite) - { - } - - /// - public override int PopCount { get { return 3; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "duplicateMovie"; - } - } + public class ActionCloneSprite : BaseAction { + + /// + /// constructor + /// + public ActionCloneSprite():base(ActionCode.CloneSprite) + { + } + + /// + public override int PopCount { get { return 3; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "duplicateMovie"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionConstantpool.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionConstantpool.cs index 6abc4a5971..64de5ed851 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionConstantpool.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionConstantpool.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,61 +25,61 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Utils; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionConstantPool : MultiByteAction { - - /// - /// list of constant pool strings by index - /// - public ArrayList ConstantList; - - /// - /// constructor - /// - /// constant list - public ActionConstantPool(string[] c):base(ActionCode.ConstantPool) - { - ConstantList = new ArrayList(c); - } - - /// - public override int ByteCount { - get { - int count = 5; - for (int i=0; i - /// overriden ToString() method - /// /// overriden ToString method - public override string ToString() { - string[] clist = new string[ConstantList.Count]; - for (int i=0; i/// - public override void Compile(BinaryWriter w) + public class ActionConstantPool : MultiByteAction { + + /// + /// list of constant pool strings by index + /// + public ArrayList ConstantList; + + /// + /// constructor + /// + /// constant list + public ActionConstantPool(string[] c):base(ActionCode.ConstantPool) + { + ConstantList = new ArrayList(c); + } + + /// + public override int ByteCount { + get { + int count = 5; + for (int i=0; i + /// overriden ToString() method + /// /// overriden ToString method + public override string ToString() { + string[] clist = new string[ConstantList.Count]; + for (int i=0; i/// + public override void Compile(BinaryWriter w) { - - base.Compile(w); - w.Write(Convert.ToUInt16(ConstantList.Count)); - - foreach(object c in ConstantList) { - string stringToWrite = (string) c; - BinaryStringRW.WriteString(w,stringToWrite); - } - } - } + + base.Compile(w); + w.Write(Convert.ToUInt16(ConstantList.Count)); + + foreach(object c in ConstantList) { + string stringToWrite = (string) c; + BinaryStringRW.WriteString(w,stringToWrite); + } + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionContainer.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionContainer.cs index 0b7bc27944..bbb50f19e1 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionContainer.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionContainer.cs @@ -1,92 +1,92 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// pseudo/helper action for aggregating a whole list of actions into one action. - /// - public class ActionContainer : BaseAction { +{ + /// + /// pseudo/helper action for aggregating a whole list of actions into one action. + /// + public class ActionContainer : BaseAction { - private BaseAction[] actionList; - private int byteCount; - private int popCount; - private int pushCount; + private BaseAction[] actionList; + private int byteCount; + private int popCount; + private int pushCount; - /// constructor - public ActionContainer(BaseAction[] aList) : base(ActionCode.Container) { - actionList = aList; - byteCount = 0; - pushCount = 0; - popCount = 0; - foreach (BaseAction a in aList) { - byteCount+=a.ByteCount; - pushCount+=a.PushCount; - popCount+=a.PopCount; - } - } - - /// list of contained actions - public BaseAction[] ActionList { - get { - return actionList; - } - } + /// constructor + public ActionContainer(BaseAction[] aList) : base(ActionCode.Container) { + actionList = aList; + byteCount = 0; + pushCount = 0; + popCount = 0; + foreach (BaseAction a in aList) { + byteCount+=a.ByteCount; + pushCount+=a.PushCount; + popCount+=a.PopCount; + } + } + + /// list of contained actions + public BaseAction[] ActionList { + get { + return actionList; + } + } - /// - public override int ByteCount { - get { - return byteCount; - } - } + /// + public override int ByteCount { + get { + return byteCount; + } + } - /// - public override int PushCount { - get { - return pushCount; - } - set { + /// + public override int PushCount { + get { + return pushCount; + } + set { - } - } - - /// - public override int PopCount { - get { - return popCount; - } - set { + } + } + + /// + public override int PopCount { + get { + return popCount; + } + set { - } - } - - /// - public override void Compile(BinaryWriter w) { - for (int i=0; i + public override void Compile(BinaryWriter w) { + for (int i=0; i - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionDecrement : BaseAction { - - /// - /// constructor - /// - public ActionDecrement():base(ActionCode.Decrement) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionDecrement : BaseAction { + + /// + /// constructor + /// + public ActionDecrement():base(ActionCode.Decrement) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "decrement"; - } - } + /// overriden ToString method + public override string ToString() { + return "decrement"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionDefineLocal.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionDefineLocal.cs index 22b1680ecf..fe3ddcbac2 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionDefineLocal.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionDefineLocal.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionDefineLocal : BaseAction { - - /// - /// constructor - /// - public ActionDefineLocal():base(ActionCode.DefineLocal) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return String.Format("varEquals"); - } - } + public class ActionDefineLocal : BaseAction { + + /// + /// constructor + /// + public ActionDefineLocal():base(ActionCode.DefineLocal) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return String.Format("varEquals"); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionDefineLocal2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionDefineLocal2.cs index c2c40e27e2..3ca38a3790 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionDefineLocal2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionDefineLocal2.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionDefineLocal2 : BaseAction { - - /// - /// constructor - /// - public ActionDefineLocal2():base(ActionCode.DefineLocal2) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return String.Format("var"); - } - } + public class ActionDefineLocal2 : BaseAction { + + /// + /// constructor + /// + public ActionDefineLocal2():base(ActionCode.DefineLocal2) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return String.Format("var"); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionDelete.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionDelete.cs index bdbdb8a35d..bab926d06b 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionDelete.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionDelete.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionDelete : BaseAction { - - /// - /// constructor - /// - public ActionDelete():base(ActionCode.Delete) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionDelete : BaseAction { + + /// + /// constructor + /// + public ActionDelete():base(ActionCode.Delete) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "delete"; - } - } + /// overriden ToString method + public override string ToString() { + return "delete"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionDelete2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionDelete2.cs index b1d9310f37..1ac955cbb1 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionDelete2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionDelete2.cs @@ -1,50 +1,50 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// - public class ActionDelete2 : BaseAction { - - /// - /// constructor - /// - public ActionDelete2():base(ActionCode.Delete2) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } +{ + /// + /// bytecode instruction object + /// + public class ActionDelete2 : BaseAction { + + /// + /// constructor + /// + public ActionDelete2():base(ActionCode.Delete2) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "delete2"; - } - } + /// overriden ToString method + public override string ToString() { + return "delete2"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionDivide.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionDivide.cs index a961daa989..d0651f2b96 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionDivide.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionDivide.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// - public class ActionDivide : BaseAction { - - /// - /// constructor - /// - public ActionDivide():base(ActionCode.Divide) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } +{ + /// + /// bytecode instruction object + /// + public class ActionDivide : BaseAction { + + /// + /// constructor + /// + public ActionDivide():base(ActionCode.Divide) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "divide"; - } - } + /// overriden ToString method + public override string ToString() { + return "divide"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEnd.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEnd.cs index 861223099b..e726b985c1 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEnd.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEnd.cs @@ -1,45 +1,45 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ +{ - /// - /// action record end instruction - /// - public class ActionEnd : BaseAction { - - /// - /// constructor - /// - public ActionEnd():base(ActionCode.End) - { - } - - /// overriden ToString method - public override string ToString() { - return "end"; - } - } + /// + /// action record end instruction + /// + public class ActionEnd : BaseAction { + + /// + /// constructor + /// + public ActionEnd():base(ActionCode.End) + { + } + + /// overriden ToString method + public override string ToString() { + return "end"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEndDrag.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEndDrag.cs index aad58b5c26..365ccedaa3 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEndDrag.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEndDrag.cs @@ -1,50 +1,50 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// - public class ActionEndDrag : BaseAction { - - /// - /// constructor - /// - public ActionEndDrag():base(ActionCode.EndDrag) - { - } - - /// - public override int PopCount { get { return 0; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "stopDrag"; - } - } +{ + /// + /// bytecode instruction object + /// + public class ActionEndDrag : BaseAction { + + /// + /// constructor + /// + public ActionEndDrag():base(ActionCode.EndDrag) + { + } + + /// + public override int PopCount { get { return 0; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "stopDrag"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEndTryBlock.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEndTryBlock.cs index a1fa19232a..6ed5760ae8 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEndTryBlock.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEndTryBlock.cs @@ -1,56 +1,56 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// pseudo instruction - /// - public class ActionEndTryBlock : BaseAction { - - /// - /// constructor - /// - public ActionEndTryBlock():base(ActionCode.EndTry) - { - //ByteSize = 0; - }/// overriden ToString method - public override string ToString() { - return "end try/catch/finally"; - } - - /// - public override int ByteCount { - get { - return 0; - } - } - - /// - public override void Compile(BinaryWriter w) - {} - - } +{ + /// + /// pseudo instruction + /// + public class ActionEndTryBlock : BaseAction { + + /// + /// constructor + /// + public ActionEndTryBlock():base(ActionCode.EndTry) + { + //ByteSize = 0; + }/// overriden ToString method + public override string ToString() { + return "end try/catch/finally"; + } + + /// + public override int ByteCount { + get { + return 0; + } + } + + /// + public override void Compile(BinaryWriter w) + {} + + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEndWait.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEndWait.cs index 02fe6d4416..dad4319dfa 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEndWait.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEndWait.cs @@ -1,56 +1,56 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// - public class ActionEndWait : BaseAction { - - /// - /// constructor - /// - public ActionEndWait():base(ActionCode.EndWait) - { - } - - /// overriden ToString method - public override string ToString() { - return "end waitForFrame"; - } - - /// - public override int ByteCount { - get { - return 0; - } - } - - /// - public override void Compile(BinaryWriter w) - {} - } +{ + /// + /// bytecode instruction object + /// + public class ActionEndWait : BaseAction { + + /// + /// constructor + /// + public ActionEndWait():base(ActionCode.EndWait) + { + } + + /// overriden ToString method + public override string ToString() { + return "end waitForFrame"; + } + + /// + public override int ByteCount { + get { + return 0; + } + } + + /// + public override void Compile(BinaryWriter w) + {} + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEndWith.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEndWith.cs index 7bff01aa39..bab9016a98 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEndWith.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEndWith.cs @@ -1,56 +1,56 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// pseudo instruction for end of with-block - /// - public class ActionEndWith : BaseAction { - - /// - /// constructor - /// - public ActionEndWith():base(ActionCode.EndWith) - { - } - - /// overriden ToString method - public override string ToString() { - return "end with"; - } - - /// - public override int ByteCount { - get { - return 0; - } - } - - /// - public override void Compile(BinaryWriter w) - {} - } +{ + /// + /// pseudo instruction for end of with-block + /// + public class ActionEndWith : BaseAction { + + /// + /// constructor + /// + public ActionEndWith():base(ActionCode.EndWith) + { + } + + /// overriden ToString method + public override string ToString() { + return "end with"; + } + + /// + public override int ByteCount { + get { + return 0; + } + } + + /// + public override void Compile(BinaryWriter w) + {} + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEnumerate.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEnumerate.cs index 4e838667ae..9ca258425d 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEnumerate.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEnumerate.cs @@ -1,49 +1,49 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// - public class ActionEnumerate : BaseAction { - - /// - /// constructor - /// - public ActionEnumerate():base(ActionCode.Enumerate) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "enumerate"; - } - } + /// + /// bytecode instruction object + /// + public class ActionEnumerate : BaseAction { + + /// + /// constructor + /// + public ActionEnumerate():base(ActionCode.Enumerate) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "enumerate"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEnumerate2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEnumerate2.cs index 5e7685f8dd..15c5bbf473 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEnumerate2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEnumerate2.cs @@ -1,48 +1,48 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionEnumerate2 : BaseAction { - - /// - /// constructor - /// - public ActionEnumerate2():base(ActionCode.Enumerate2) - { - } - - /// - public override int PopCount { get { return 1; } } - /// - public override int PushCount { get { return 0; } } - /// overriden ToString method - public override string ToString() { - return "enumerateObject"; - } - } + public class ActionEnumerate2 : BaseAction { + + /// + /// constructor + /// + public ActionEnumerate2():base(ActionCode.Enumerate2) + { + } + + /// + public override int PopCount { get { return 1; } } + /// + public override int PushCount { get { return 0; } } + /// overriden ToString method + public override string ToString() { + return "enumerateObject"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEquals.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEquals.cs index 740498f166..8dbff37910 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEquals.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEquals.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// - public class ActionEquals : BaseAction { - - /// - /// constructor - /// - public ActionEquals():base(ActionCode.Equals) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } +{ + /// + /// bytecode instruction object + /// + public class ActionEquals : BaseAction { + + /// + /// constructor + /// + public ActionEquals():base(ActionCode.Equals) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "equals"; - } - } + /// overriden ToString method + public override string ToString() { + return "equals"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionEquals2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionEquals2.cs index a8ad7d9914..b4e94cf3e7 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionEquals2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionEquals2.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionEquals2 : BaseAction { - - /// - /// constructor - /// - public ActionEquals2():base(ActionCode.Equals2) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionEquals2 : BaseAction { + + /// + /// constructor + /// + public ActionEquals2():base(ActionCode.Equals2) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "equals2"; - } - } + /// overriden ToString method + public override string ToString() { + return "equals2"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionExtends.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionExtends.cs index ca2b40450c..4bc5b193fe 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionExtends.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionExtends.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,28 +24,28 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// - public class ActionExtends : BaseAction { - - /// - /// constructor - /// - public ActionExtends():base(ActionCode.Extends) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "extends"; - } - } + /// + /// bytecode instruction object + /// + public class ActionExtends : BaseAction { + + /// + /// constructor + /// + public ActionExtends():base(ActionCode.Extends) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "extends"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionFinally.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionFinally.cs index 0f1885aae1..13c24f14ac 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionFinally.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionFinally.cs @@ -1,56 +1,56 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// pseudo instruction object - /// - public class ActionFinally : BaseAction { - - /// - /// constructor - /// - public ActionFinally():base(ActionCode.Finally) - { - } - - /// overriden ToString method - public override string ToString() { - return "finally "; - } - - /// - public override int ByteCount { - get { - return 0; - } - } - - /// - public override void Compile(BinaryWriter w) - {} - } +{ + /// + /// pseudo instruction object + /// + public class ActionFinally : BaseAction { + + /// + /// constructor + /// + public ActionFinally():base(ActionCode.Finally) + { + } + + /// overriden ToString method + public override string ToString() { + return "finally "; + } + + /// + public override int ByteCount { + get { + return 0; + } + } + + /// + public override void Compile(BinaryWriter w) + {} + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionFunction.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionFunction.cs index 5342474739..1cf7229ec4 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionFunction.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionFunction.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -26,105 +26,105 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionDefineFunction : MultiByteAction { - - /// - /// function name - /// - public string Name; - - /// - /// list of function parameters - /// - public string[] ParameterList; - - /// - /// inner actions (function body) - /// - public ArrayList ActionRecord; // inner actions, function body - - /// - /// constructor - /// - /// function name - /// funtion parameters - /// inner action block (function body) - public ActionDefineFunction(string n,string[] parmList,ArrayList actionRec) : - base(ActionCode.DefineFunction) - { - Name = n; - ParameterList = parmList; - ActionRecord = actionRec; - } - - private int innerByteCount { - get { - int count = 0; - for (int i=0; i - public override int ByteCount { - get { - int count = 3+Name.Length+1+2+2; - for (int i=0; i - public override void Compile(BinaryWriter w) + public class ActionDefineFunction : MultiByteAction { + + /// + /// function name + /// + public string Name; + + /// + /// list of function parameters + /// + public string[] ParameterList; + + /// + /// inner actions (function body) + /// + public ArrayList ActionRecord; // inner actions, function body + + /// + /// constructor + /// + /// function name + /// funtion parameters + /// inner action block (function body) + public ActionDefineFunction(string n,string[] parmList,ArrayList actionRec) : + base(ActionCode.DefineFunction) + { + Name = n; + ParameterList = parmList; + ActionRecord = actionRec; + } + + private int innerByteCount { + get { + int count = 0; + for (int i=0; i + public override int ByteCount { + get { + int count = 3+Name.Length+1+2+2; + for (int i=0; i + public override void Compile(BinaryWriter w) { - - w.Write( Convert.ToByte(Code)); - w.Write(Convert.ToUInt16(ByteCount-innerByteCount-3)); - BinaryStringRW.WriteString(w,Name); - - w.Write(Convert.ToUInt16(ParameterList.Length)); - foreach(string str in ParameterList) { - BinaryStringRW.WriteString(w,str); - } - - w.Write(Convert.ToUInt16(innerByteCount)); - foreach (object a in ActionRecord) { - BaseAction action = (BaseAction) a; - action.Compile(w); - } - } - - /// - public override int PopCount { get { return 0; } } - - /// - public override int PushCount { get { return 1; } } - - /// overriden ToString method - public override string ToString() { - - string[] s = new string[ActionRecord.Count]; - for (int i=0; i + public override int PopCount { get { return 0; } } + + /// + public override int PushCount { get { return 1; } } + + /// overriden ToString method + public override string ToString() { + + string[] s = new string[ActionRecord.Count]; + for (int i=0; i - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionDefineFunction2 : MultiByteAction { - - /// - /// register/name pair of function parameter - /// - public struct RegParamPair { - - internal int Register; - internal string Parameter; - - /// - /// constructor - /// - public RegParamPair(int r,string p) { - Register = r; - Parameter = p; - } - - /// - /// overriden ToString method, called by outer class - /// - public override string ToString() { - return String.Format("r:{0}='{1}'",Register,Parameter); - } - } - - /// - /// set of flags for automatically storing variables in registers - /// - public struct VariableFlagSet { - - /// preload '_parent' variable - public bool PreloadParent; - /// preload '_root' variable - public bool PreloadRoot; - /// suppress '_root' variable - public bool SuppressSuper; - /// preload 'super' variable - public bool PreloadSuper; - /// suppress 'super' variable - public bool SuppressArguments; - /// preload 'arguments' variable - public bool PreloadArguments; - /// suppress 'arguments' variable - public bool SuppressThis; - /// preload 'this' variable - public bool PreloadThis; - /// preload '_global' variable - public bool PreloadGlobal; - - /// constructor - public VariableFlagSet(bool loadParent, - bool loadRoot, - bool dontSuper, - bool loadSuper, - bool dontArgs, - bool loadArgs, - bool dontThis, - bool loadThis, - bool loadGlobal) - - { - PreloadParent = loadParent; - PreloadRoot = loadRoot; - SuppressSuper =dontSuper; - PreloadSuper = loadSuper; - SuppressArguments = dontArgs; - PreloadArguments = loadArgs; - SuppressThis = dontThis; - PreloadThis = loadThis; - PreloadGlobal = loadGlobal; - } - - /// - /// count of positive flags - /// - internal int Count { - get { - int i=0; - - if (PreloadParent) i++; - if (PreloadRoot) i++; - if (SuppressSuper) i++; - if (PreloadSuper) i++; - if (SuppressArguments) i++; - if (PreloadArguments) i++; - if (SuppressThis) i++; - if (PreloadThis) i++; - if (PreloadGlobal) i++; - - return i; - } - } - - /// - /// check wether flags exclude each other - /// - internal void CheckExclusion() { - - if (PreloadSuper) { - SuppressSuper = false; - } - if (PreloadArguments) { - SuppressArguments = false; - } - if (PreloadThis) { - SuppressThis = false; - } - } - - /// - /// bytecode for flag set - /// - internal byte[] Bytecode { - - get { - byte b0 = 0; - byte b1 = 0; - - CheckExclusion(); - - if (PreloadParent) b0+=0x80; - if (PreloadRoot) b0+=0x40; - if (SuppressSuper) b0+=0x20; - if (PreloadSuper) b0+=0x10; - if (SuppressArguments) b0+=0x08; - if (PreloadArguments) b0+=0x04; - if (SuppressThis) b0+=0x02; - if (PreloadThis) b0+=0x01; - if (PreloadGlobal) b1+=0x01; - - return new byte[2] { b0,b1 }; - } - } - - /// - /// ToString method, called by outer class´ ToString - /// - public override string ToString() { - - int reg = 1; - StringBuilder stb = new StringBuilder(); - - if (PreloadThis) { - stb.AppendFormat("r:{0}='this'",reg); - reg++; - } - if (PreloadArguments) { - stb.AppendFormat("{0}r:{1}='arguments'",(reg>1) ? "," : "" ,reg); - reg++; - } - if (PreloadSuper) { - stb.AppendFormat("{0}r:{1}='super'",(reg>1) ? "," : "" ,reg); - reg++; - } - if (PreloadRoot) { - stb.AppendFormat("{0}r:{1}='_root'",(reg>1) ? "," : "" ,reg); - reg++; - } - if (PreloadParent) { - stb.AppendFormat("{0}r:{1}='_parent'",(reg>1) ? "," : "" ,reg); - reg++; - } - if (PreloadGlobal) { - stb.AppendFormat("{0}r:{1}='_global'",(reg>1) ? "," : "" ,reg); - reg++; - } - return stb.ToString(); - } - } - - /// - /// function name - /// - public string Name; - - /// - /// RegParamPair of expected parameters - /// - public RegParamPair[] ParameterList; - - /// - /// registers allocated by function - /// - public int RegisterCount; - - /// - /// inner actions (function body) - /// - public ArrayList ActionRecord; - - private VariableFlagSet flags; - - /// - /// automatically allocated registers flags (this, _global etc.) - /// - public VariableFlagSet Flags { - get { - return flags; - } - } - /// - /// constructor - /// - /// function name - /// function parameters - /// register count - /// flags for automatic register allocation - /// inner action block (body) - public ActionDefineFunction2(string n, - RegParamPair[] p, - int r, - VariableFlagSet f, - ArrayList actionRec) - : base(ActionCode.DefineFunction2) - { - Name = n; - ParameterList = p; - RegisterCount = r; - flags = f; - ActionRecord = actionRec; - } - - /// - /// summarized byte count of inner action block - /// - protected int InnerByteCount { - get { - int count = 0; - for (int i=0; i - public override int ByteCount { - get { - int count = 3+Name.Length+1+2+1+2+2+InnerByteCount; - for (int i=0; i + /// register/name pair of function parameter + /// + public struct RegParamPair { + + internal int Register; + internal string Parameter; + + /// + /// constructor + /// + public RegParamPair(int r,string p) { + Register = r; + Parameter = p; + } + + /// + /// overriden ToString method, called by outer class + /// + public override string ToString() { + return String.Format("r:{0}='{1}'",Register,Parameter); + } + } + + /// + /// set of flags for automatically storing variables in registers + /// + public struct VariableFlagSet { + + /// preload '_parent' variable + public bool PreloadParent; + /// preload '_root' variable + public bool PreloadRoot; + /// suppress '_root' variable + public bool SuppressSuper; + /// preload 'super' variable + public bool PreloadSuper; + /// suppress 'super' variable + public bool SuppressArguments; + /// preload 'arguments' variable + public bool PreloadArguments; + /// suppress 'arguments' variable + public bool SuppressThis; + /// preload 'this' variable + public bool PreloadThis; + /// preload '_global' variable + public bool PreloadGlobal; + + /// constructor + public VariableFlagSet(bool loadParent, + bool loadRoot, + bool dontSuper, + bool loadSuper, + bool dontArgs, + bool loadArgs, + bool dontThis, + bool loadThis, + bool loadGlobal) + + { + PreloadParent = loadParent; + PreloadRoot = loadRoot; + SuppressSuper =dontSuper; + PreloadSuper = loadSuper; + SuppressArguments = dontArgs; + PreloadArguments = loadArgs; + SuppressThis = dontThis; + PreloadThis = loadThis; + PreloadGlobal = loadGlobal; + } + + /// + /// count of positive flags + /// + internal int Count { + get { + int i=0; + + if (PreloadParent) i++; + if (PreloadRoot) i++; + if (SuppressSuper) i++; + if (PreloadSuper) i++; + if (SuppressArguments) i++; + if (PreloadArguments) i++; + if (SuppressThis) i++; + if (PreloadThis) i++; + if (PreloadGlobal) i++; + + return i; + } + } + + /// + /// check wether flags exclude each other + /// + internal void CheckExclusion() { + + if (PreloadSuper) { + SuppressSuper = false; + } + if (PreloadArguments) { + SuppressArguments = false; + } + if (PreloadThis) { + SuppressThis = false; + } + } + + /// + /// bytecode for flag set + /// + internal byte[] Bytecode { + + get { + byte b0 = 0; + byte b1 = 0; + + CheckExclusion(); + + if (PreloadParent) b0+=0x80; + if (PreloadRoot) b0+=0x40; + if (SuppressSuper) b0+=0x20; + if (PreloadSuper) b0+=0x10; + if (SuppressArguments) b0+=0x08; + if (PreloadArguments) b0+=0x04; + if (SuppressThis) b0+=0x02; + if (PreloadThis) b0+=0x01; + if (PreloadGlobal) b1+=0x01; + + return new byte[2] { b0,b1 }; + } + } + + /// + /// ToString method, called by outer class´ ToString + /// + public override string ToString() { + + int reg = 1; + StringBuilder stb = new StringBuilder(); + + if (PreloadThis) { + stb.AppendFormat("r:{0}='this'",reg); + reg++; + } + if (PreloadArguments) { + stb.AppendFormat("{0}r:{1}='arguments'",(reg>1) ? "," : "" ,reg); + reg++; + } + if (PreloadSuper) { + stb.AppendFormat("{0}r:{1}='super'",(reg>1) ? "," : "" ,reg); + reg++; + } + if (PreloadRoot) { + stb.AppendFormat("{0}r:{1}='_root'",(reg>1) ? "," : "" ,reg); + reg++; + } + if (PreloadParent) { + stb.AppendFormat("{0}r:{1}='_parent'",(reg>1) ? "," : "" ,reg); + reg++; + } + if (PreloadGlobal) { + stb.AppendFormat("{0}r:{1}='_global'",(reg>1) ? "," : "" ,reg); + reg++; + } + return stb.ToString(); + } + } + + /// + /// function name + /// + public string Name; + + /// + /// RegParamPair of expected parameters + /// + public RegParamPair[] ParameterList; + + /// + /// registers allocated by function + /// + public int RegisterCount; + + /// + /// inner actions (function body) + /// + public ArrayList ActionRecord; + + private VariableFlagSet flags; + + /// + /// automatically allocated registers flags (this, _global etc.) + /// + public VariableFlagSet Flags { + get { + return flags; + } + } + /// + /// constructor + /// + /// function name + /// function parameters + /// register count + /// flags for automatic register allocation + /// inner action block (body) + public ActionDefineFunction2(string n, + RegParamPair[] p, + int r, + VariableFlagSet f, + ArrayList actionRec) + : base(ActionCode.DefineFunction2) + { + Name = n; + ParameterList = p; + RegisterCount = r; + flags = f; + ActionRecord = actionRec; + } + + /// + /// summarized byte count of inner action block + /// + protected int InnerByteCount { + get { + int count = 0; + for (int i=0; i + public override int ByteCount { + get { + int count = 3+Name.Length+1+2+1+2+2+InnerByteCount; + for (int i=0; i - public override void Compile(BinaryWriter w) + return count; + } + } + /// + public override void Compile(BinaryWriter w) { - - w.Write( Convert.ToByte(Code)); - w.Write(Convert.ToUInt16(ByteCount-InnerByteCount-3)); - BinaryStringRW.WriteString(w,Name); - - w.Write(Convert.ToUInt16(ParameterList.Length)); - w.Write(Convert.ToByte(RegisterCount)); - w.Write(flags.Bytecode); - - foreach (RegParamPair rp in ParameterList) { - w.Write(Convert.ToByte(rp.Register)); - BinaryStringRW.WriteString(w,rp.Parameter); - } - - w.Write(Convert.ToUInt16(InnerByteCount)); - - foreach (object a in ActionRecord) { - BaseAction action = (BaseAction) a; - action.Compile(w); - } - - } - - /// - public override int PopCount { get { return 0; } } - /// - public override int PushCount { get { return 1; } } + + w.Write( Convert.ToByte(Code)); + w.Write(Convert.ToUInt16(ByteCount-InnerByteCount-3)); + BinaryStringRW.WriteString(w,Name); + + w.Write(Convert.ToUInt16(ParameterList.Length)); + w.Write(Convert.ToByte(RegisterCount)); + w.Write(flags.Bytecode); + + foreach (RegParamPair rp in ParameterList) { + w.Write(Convert.ToByte(rp.Register)); + BinaryStringRW.WriteString(w,rp.Parameter); + } + + w.Write(Convert.ToUInt16(InnerByteCount)); + + foreach (object a in ActionRecord) { + BaseAction action = (BaseAction) a; + action.Compile(w); + } + + } + + /// + public override int PopCount { get { return 0; } } + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - - string[] s = new string[ParameterList.Length]; - - for (int i=0; ioverriden ToString method + public override string ToString() { + + string[] s = new string[ParameterList.Length]; + + for (int i=0; i - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionGetMember : BaseAction { - - /// - /// constructor - /// - public ActionGetMember():base(ActionCode.GetMember) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionGetMember : BaseAction { + + /// + /// constructor + /// + public ActionGetMember():base(ActionCode.GetMember) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return String.Format("getMember"); - } - } + /// overriden ToString method + public override string ToString() { + return String.Format("getMember"); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGetProperty.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGetProperty.cs index f7852e239b..b386d600e3 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGetProperty.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGetProperty.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionGetProperty : BaseAction { - - /// - /// constructor - /// - public ActionGetProperty():base(ActionCode.GetProperty) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } - - /// overriden ToString method - public override string ToString() { - return "getproperty"; - } - } + public class ActionGetProperty : BaseAction { + + /// + /// constructor + /// + public ActionGetProperty():base(ActionCode.GetProperty) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } + + /// overriden ToString method + public override string ToString() { + return "getproperty"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGetTime.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGetTime.cs index a80139b073..9dc9066681 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGetTime.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGetTime.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionGetTime : BaseAction { - - /// - /// constructor - /// - public ActionGetTime():base(ActionCode.GetTime) - { - } - - /// - public override int PopCount { get { return 0; } } - - /// - public override int PushCount { get { return 1; } } - - /// overriden ToString method - public override string ToString() { - return "getTime"; - } - } + public class ActionGetTime : BaseAction { + + /// + /// constructor + /// + public ActionGetTime():base(ActionCode.GetTime) + { + } + + /// + public override int PopCount { get { return 0; } } + + /// + public override int PushCount { get { return 1; } } + + /// overriden ToString method + public override string ToString() { + return "getTime"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGetUrl.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGetUrl.cs index bf37ee8774..470a7cb49a 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGetUrl.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGetUrl.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -26,43 +26,43 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionGetUrl : MultiByteAction { - - private string urlString; - private string targetString; - - /// - /// constructor - /// - public ActionGetUrl(string url,string target):base(ActionCode.GetURL) - { - urlString = url; - targetString = target; - } - - /// - public override int ByteCount { - get { - return 3 + urlString.Length + targetString.Length + 2; - } - } - - /// overriden ToString method - public override string ToString() { - return String.Format("getUrl '{0}','{1}'",urlString,targetString); - } - - /// - public override void Compile(BinaryWriter w) + public class ActionGetUrl : MultiByteAction { + + private string urlString; + private string targetString; + + /// + /// constructor + /// + public ActionGetUrl(string url,string target):base(ActionCode.GetURL) + { + urlString = url; + targetString = target; + } + + /// + public override int ByteCount { + get { + return 3 + urlString.Length + targetString.Length + 2; + } + } + + /// overriden ToString method + public override string ToString() { + return String.Format("getUrl '{0}','{1}'",urlString,targetString); + } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - BinaryStringRW.WriteString(w,urlString); - BinaryStringRW.WriteString(w,targetString); - } - } + base.Compile(w); + BinaryStringRW.WriteString(w,urlString); + BinaryStringRW.WriteString(w,targetString); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGetUrl2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGetUrl2.cs index b26b5a8d58..99d3dad189 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGetUrl2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGetUrl2.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,46 +24,46 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Utils; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionGetUrl2 : MultiByteAction { - - private byte flags; - - /// - /// constructor - /// - /// flag settings - public ActionGetUrl2(byte flags):base(ActionCode.GetURL2) - { - this.flags = flags; - } - /// overriden ToString method - public override string ToString() { - return String.Format("getUrl2 [{0}]",flags); - } - - /// - public override int ByteCount { - get { - return 4; - } - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 0; } } - - /// - public override void Compile(BinaryWriter w) + public class ActionGetUrl2 : MultiByteAction { + + private byte flags; + + /// + /// constructor + /// + /// flag settings + public ActionGetUrl2(byte flags):base(ActionCode.GetURL2) + { + this.flags = flags; + } + /// overriden ToString method + public override string ToString() { + return String.Format("getUrl2 [{0}]",flags); + } + + /// + public override int ByteCount { + get { + return 4; + } + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 0; } } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(flags); - } - } + base.Compile(w); + w.Write(flags); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGetVariable.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGetVariable.cs index 1c1a282bb2..11780ab9c7 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGetVariable.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGetVariable.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionGetVariable : BaseAction { - - /// - /// constructor - /// - public ActionGetVariable():base(ActionCode.GetVariable) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionGetVariable : BaseAction { + + /// + /// constructor + /// + public ActionGetVariable():base(ActionCode.GetVariable) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return String.Format("getVariable"); - } - } + /// overriden ToString method + public override string ToString() { + return String.Format("getVariable"); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGotoFrame.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGotoFrame.cs index d3d0614e6f..e5a69b6338 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGotoFrame.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGotoFrame.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -26,39 +26,39 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionGotoFrame : MultiByteAction { - - private short frame; - - /// - /// constructor - /// - public ActionGotoFrame(short f):base(ActionCode.GotoFrame) - { - frame = f; - } - - /// - public override int ByteCount { - get { - return 5; - } - } - - /// overriden ToString method - public override string ToString() { - return "gotoFrame "+frame.ToString(); - } - - /// - public override void Compile(BinaryWriter w) + public class ActionGotoFrame : MultiByteAction { + + private short frame; + + /// + /// constructor + /// + public ActionGotoFrame(short f):base(ActionCode.GotoFrame) + { + frame = f; + } + + /// + public override int ByteCount { + get { + return 5; + } + } + + /// overriden ToString method + public override string ToString() { + return "gotoFrame "+frame.ToString(); + } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(frame); - } - } + base.Compile(w); + w.Write(frame); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGotoFrame2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGotoFrame2.cs index ef22750d0e..b881c6b279 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGotoFrame2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGotoFrame2.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -26,42 +26,42 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionGotoFrame2 : MultiByteAction { - - private byte[] gotoData; - - /// - /// constructor - /// - public ActionGotoFrame2(byte[] data):base(ActionCode.GotoFrame2) - { - gotoData = data; - } - - /// - public override int ByteCount { - get { - return gotoData.Length + 3; - } - } - - /// - public override int PopCount { get { return 1; } } - /// - public override int PushCount { get { return 0; } } - /// overriden ToString method - public override string ToString() { - return "gotoFrame2 [...]"; - } - /// - public override void Compile(BinaryWriter w) + public class ActionGotoFrame2 : MultiByteAction { + + private byte[] gotoData; + + /// + /// constructor + /// + public ActionGotoFrame2(byte[] data):base(ActionCode.GotoFrame2) + { + gotoData = data; + } + + /// + public override int ByteCount { + get { + return gotoData.Length + 3; + } + } + + /// + public override int PopCount { get { return 1; } } + /// + public override int PushCount { get { return 0; } } + /// overriden ToString method + public override string ToString() { + return "gotoFrame2 [...]"; + } + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(gotoData); - } - } + base.Compile(w); + w.Write(gotoData); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGotoLabel.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGotoLabel.cs index 1f9190ab50..32c2f71a0f 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGotoLabel.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGotoLabel.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,40 +25,40 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionGotoLabel : MultiByteAction { - - private string label; - - /// - /// constructor - /// - public ActionGotoLabel(string l):base(ActionCode.GoToLabel) - { - label = l; - } - - /// - public override int ByteCount { - get { - return 3+label.Length+1; - } - } - - /// overriden ToString method - public override string ToString() { - return String.Format("gotoLabel '{0}'",label); - } - - /// - public override void Compile(BinaryWriter w) + public class ActionGotoLabel : MultiByteAction { + + private string label; + + /// + /// constructor + /// + public ActionGotoLabel(string l):base(ActionCode.GoToLabel) + { + label = l; + } + + /// + public override int ByteCount { + get { + return 3+label.Length+1; + } + } + + /// overriden ToString method + public override string ToString() { + return String.Format("gotoLabel '{0}'",label); + } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - BinaryStringRW.WriteString(w,label); - } - } + base.Compile(w); + BinaryStringRW.WriteString(w,label); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionGreater.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionGreater.cs index 4746beecb1..b6828fa73b 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionGreater.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionGreater.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionGreater : BaseAction { - - /// - /// constructor - /// - public ActionGreater():base(ActionCode.Greater) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionGreater : BaseAction { + + /// + /// constructor + /// + public ActionGreater():base(ActionCode.Greater) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "greaterThan"; - } - } + /// overriden ToString method + public override string ToString() { + return "greaterThan"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionIf.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionIf.cs index 4763dd3cc6..63e4039e62 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionIf.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionIf.cs @@ -1,96 +1,96 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionIf : MultiByteAction,IJump { - - // branch offset - private int _offset; - private int _labelId; - - /// - /// constructor - /// - /// branch offset - public ActionIf(int labelId):base(ActionCode.If) - { - _offset = 0; - _labelId = labelId; - } - - /// - /// branch offset - /// - public int Offset { - get { - return _offset; - } - set { - _offset = value; - } - } - - /// - /// label id - /// - public int LabelId { - get { - return _labelId; - } - set { - _labelId = value; - } - } - - /// - public override int ByteCount { - get { - return 5; - } - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } - - /// - public override void Compile(BinaryWriter w) + public class ActionIf : MultiByteAction,IJump { + + // branch offset + private int _offset; + private int _labelId; + + /// + /// constructor + /// + /// branch offset + public ActionIf(int labelId):base(ActionCode.If) + { + _offset = 0; + _labelId = labelId; + } + + /// + /// branch offset + /// + public int Offset { + get { + return _offset; + } + set { + _offset = value; + } + } + + /// + /// label id + /// + public int LabelId { + get { + return _labelId; + } + set { + _labelId = value; + } + } + + /// + public override int ByteCount { + get { + return 5; + } + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(Convert.ToInt16(Offset)); - } - - /// overriden ToString method - public override string ToString() { - return String.Format("branchIf {0} ({1})",LabelId,Offset); - } - } + base.Compile(w); + w.Write(Convert.ToInt16(Offset)); + } + + /// overriden ToString method + public override string ToString() { + return String.Format("branchIf {0} ({1})",LabelId,Offset); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionImplements.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionImplements.cs index 42e10cc748..a232bf0f9c 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionImplements.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionImplements.cs @@ -1,67 +1,67 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionImplements : BaseAction { - - /// - /// constructor - /// - public ActionImplements():base(ActionCode.Implements) - { - } - - private int numI = 0; - - /// number of interfaces implemented - public int NumInterfaces { - get { - return numI; - } - set { - numI = value; - } - } - - /// - public override int PopCount { - get { - return numI+2; - } - } - /// - public override int PushCount { get { return 1; } } + public class ActionImplements : BaseAction { + + /// + /// constructor + /// + public ActionImplements():base(ActionCode.Implements) + { + } + + private int numI = 0; + + /// number of interfaces implemented + public int NumInterfaces { + get { + return numI; + } + set { + numI = value; + } + } + + /// + public override int PopCount { + get { + return numI+2; + } + } + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "implements"; - } - } + /// overriden ToString method + public override string ToString() { + return "implements"; + } + } } - + diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionIncrement.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionIncrement.cs index 5ed29b9c8d..ba729c25fa 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionIncrement.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionIncrement.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionIncrement : BaseAction { - - /// - /// constructor - /// - public ActionIncrement():base(ActionCode.Increment) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionIncrement : BaseAction { + + /// + /// constructor + /// + public ActionIncrement():base(ActionCode.Increment) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "increment"; - } - } + /// overriden ToString method + public override string ToString() { + return "increment"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionInitArray.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionInitArray.cs index ae4ae4ac4b..ab74fbde5b 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionInitArray.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionInitArray.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,46 +24,46 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionInitArray : BaseAction { - - /// - /// constructor - /// - public ActionInitArray():base(ActionCode.InitArray) - { - } - - private int numValues = 0; - - /// - /// array count as found by Invocation Examiner - /// - public int NumValues { - get { - return numValues; - } - set { - numValues = value; - } - } - - /// - public override int PopCount { - get { - return numValues+1; - } - } - /// - public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "initArray"; - } - } + public class ActionInitArray : BaseAction { + + /// + /// constructor + /// + public ActionInitArray():base(ActionCode.InitArray) + { + } + + private int numValues = 0; + + /// + /// array count as found by Invocation Examiner + /// + public int NumValues { + get { + return numValues; + } + set { + numValues = value; + } + } + + /// + public override int PopCount { + get { + return numValues+1; + } + } + /// + public override int PushCount { get { return 1; } } + /// overriden ToString method + public override string ToString() { + return "initArray"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionInitObject.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionInitObject.cs index 5751625530..b671d1cf93 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionInitObject.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionInitObject.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,43 +24,43 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionInitObject : BaseAction { + public class ActionInitObject : BaseAction { - /// - /// constructor - /// - public ActionInitObject():base(ActionCode.InitObject) - { - } - - private int numProps = 0; - - /// - /// property count as found by Invocation Examiner - /// - public int NumProps { - set { - numProps = value; - } - } - - /// - public override int PopCount { - get { - return numProps*2+1; - } - } - /// - public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "initObject"; - } - } + /// + /// constructor + /// + public ActionInitObject():base(ActionCode.InitObject) + { + } + + private int numProps = 0; + + /// + /// property count as found by Invocation Examiner + /// + public int NumProps { + set { + numProps = value; + } + } + + /// + public override int PopCount { + get { + return numProps*2+1; + } + } + /// + public override int PushCount { get { return 1; } } + /// overriden ToString method + public override string ToString() { + return "initObject"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionInstanceOf.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionInstanceOf.cs index 6331da8258..5c4ee40d76 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionInstanceOf.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionInstanceOf.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,30 +24,30 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - - /// - /// bytecode instruction object - /// + + /// + /// bytecode instruction object + /// - public class ActionInstanceOf : BaseAction { - - /// - /// array count as found by Invocation Examiner - /// - public ActionInstanceOf():base(ActionCode.InstanceOf) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionInstanceOf : BaseAction { + + /// + /// array count as found by Invocation Examiner + /// + public ActionInstanceOf():base(ActionCode.InstanceOf) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "instanceof"; - } - } + /// overriden ToString method + public override string ToString() { + return "instanceof"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionJump.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionJump.cs index 6b31faf684..9187f777df 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionJump.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionJump.cs @@ -1,92 +1,92 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionJump : MultiByteAction,IJump { - - // branch offset - private int _offset; - private int _labelId; - - /// - /// constructor - /// - /// branch offset - public ActionJump(int labelId) : base(ActionCode.Jump) - { - _offset = 0; - _labelId = labelId; - } - - /// - /// branch offsets - /// - public int Offset { - get { - return _offset; - } - set { - _offset = value; - } - } - - /// - /// label id - /// - public int LabelId { - get { - return _labelId; - } - set { - _labelId = value; - } - } - - /// - public override int ByteCount { - get { - return 5; - } - } - - /// - public override void Compile(BinaryWriter w) + public class ActionJump : MultiByteAction,IJump { + + // branch offset + private int _offset; + private int _labelId; + + /// + /// constructor + /// + /// branch offset + public ActionJump(int labelId) : base(ActionCode.Jump) + { + _offset = 0; + _labelId = labelId; + } + + /// + /// branch offsets + /// + public int Offset { + get { + return _offset; + } + set { + _offset = value; + } + } + + /// + /// label id + /// + public int LabelId { + get { + return _labelId; + } + set { + _labelId = value; + } + } + + /// + public override int ByteCount { + get { + return 5; + } + } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(Convert.ToInt16(Offset)); - } - - /// overriden ToString method - public override string ToString() { - return String.Format("branch {0} ({1})",LabelId,Offset); - } - - } + base.Compile(w); + w.Write(Convert.ToInt16(Offset)); + } + + /// overriden ToString method + public override string ToString() { + return String.Format("branch {0} ({1})",LabelId,Offset); + } + + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionLabel.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionLabel.cs index cf8c7e3014..137f20ecbf 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionLabel.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionLabel.cs @@ -1,64 +1,64 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionLabel : BaseAction { - - /// - /// label id - /// - public int LabelId; + public class ActionLabel : BaseAction { + + /// + /// label id + /// + public int LabelId; - /// - /// constructor - /// - public ActionLabel(int l):base(ActionCode.Label) - { - LabelId = l; - //ByteSize = 0; - } - - /// overriden ToString method - public override string ToString() { - return String.Format("label{0}:",LabelId); - } - - /// - public override int ByteCount { - get { - return 0; - } - } - - /// - public override void Compile(BinaryWriter w) + /// + /// constructor + /// + public ActionLabel(int l):base(ActionCode.Label) + { + LabelId = l; + //ByteSize = 0; + } + + /// overriden ToString method + public override string ToString() { + return String.Format("label{0}:",LabelId); + } + + /// + public override int ByteCount { + get { + return 0; + } + } + + /// + public override void Compile(BinaryWriter w) {} - } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionLess.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionLess.cs index dc488d2d84..18ef9339d9 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionLess.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionLess.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionLess : BaseAction { - - /// - /// constructor - /// - public ActionLess():base(ActionCode.Less) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionLess : BaseAction { + + /// + /// constructor + /// + public ActionLess():base(ActionCode.Less) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "less than"; - } - } + /// overriden ToString method + public override string ToString() { + return "less than"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionLess2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionLess2.cs index 51c6d38134..7f91f68705 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionLess2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionLess2.cs @@ -1,53 +1,53 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - - /// - /// bytecode instruction object - /// +{ + + /// + /// bytecode instruction object + /// - public class ActionLess2 : BaseAction { - - /// - /// constructor - /// - public ActionLess2():base(ActionCode.Less2) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionLess2 : BaseAction { + + /// + /// constructor + /// + public ActionLess2():base(ActionCode.Less2) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "less2"; - } - } + /// overriden ToString method + public override string ToString() { + return "less2"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionMBAsciiToChar.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionMBAsciiToChar.cs index 3ed4fa4583..f5f16ab261 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionMBAsciiToChar.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionMBAsciiToChar.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,31 +24,31 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionMBAsciiToChar : BaseAction { - - /// - /// constructor - /// - public ActionMBAsciiToChar():base(ActionCode.MBAsciiToChar) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionMBAsciiToChar : BaseAction { + + /// + /// constructor + /// + public ActionMBAsciiToChar():base(ActionCode.MBAsciiToChar) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "mbAscii2Char"; - } - - } + /// overriden ToString method + public override string ToString() { + return "mbAscii2Char"; + } + + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionMBCharToAscii.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionMBCharToAscii.cs index 5dbc47d27f..1ae32a22e9 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionMBCharToAscii.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionMBCharToAscii.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionMBCharToAscii : BaseAction { - - /// - /// constructor - /// - public ActionMBCharToAscii():base(ActionCode.MBCharToAscii) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionMBCharToAscii : BaseAction { + + /// + /// constructor + /// + public ActionMBCharToAscii():base(ActionCode.MBCharToAscii) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "mbChar2Ascii"; - } - } + /// overriden ToString method + public override string ToString() { + return "mbChar2Ascii"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionMBStringExtract.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionMBStringExtract.cs index 03815cc7bd..ba3ec1ebb9 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionMBStringExtract.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionMBStringExtract.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionMBStringExtract : BaseAction { - - /// - /// constructor - /// - public ActionMBStringExtract():base(ActionCode.MBStringExtract) - { - } - - /// - public override int PopCount { get { return 3; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionMBStringExtract : BaseAction { + + /// + /// constructor + /// + public ActionMBStringExtract():base(ActionCode.MBStringExtract) + { + } + + /// + public override int PopCount { get { return 3; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "mbSubstring"; - } - } + /// overriden ToString method + public override string ToString() { + return "mbSubstring"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionMBStringLength.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionMBStringLength.cs index 7bb5e0ee39..858cfe6d42 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionMBStringLength.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionMBStringLength.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionMBStringLength : BaseAction { - - /// - /// constructor - /// - public ActionMBStringLength():base(ActionCode.MBStringLength) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionMBStringLength : BaseAction { + + /// + /// constructor + /// + public ActionMBStringLength():base(ActionCode.MBStringLength) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "mbStrLen"; - } - } - + /// overriden ToString method + public override string ToString() { + return "mbStrLen"; + } + } + } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionModulo.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionModulo.cs index 7d75e572bf..0051627206 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionModulo.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionModulo.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionModulo : BaseAction { - - /// - /// constructor - /// - public ActionModulo():base(ActionCode.Modulo) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionModulo : BaseAction { + + /// + /// constructor + /// + public ActionModulo():base(ActionCode.Modulo) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "modulo"; - } - } + /// overriden ToString method + public override string ToString() { + return "modulo"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionMultiply.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionMultiply.cs index 391f84f7b6..7454a1f751 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionMultiply.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionMultiply.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionMultiply : BaseAction { - - /// - /// constructor - /// - public ActionMultiply():base(ActionCode.Multiply) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionMultiply : BaseAction { + + /// + /// constructor + /// + public ActionMultiply():base(ActionCode.Multiply) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "multiply"; - } - } + /// overriden ToString method + public override string ToString() { + return "multiply"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionNewMethod.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionNewMethod.cs index 6f65faa322..c4ae1374c7 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionNewMethod.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionNewMethod.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,45 +24,45 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionNewMethod : BaseAction { - - /// - /// constructor - /// - public ActionNewMethod():base(ActionCode.NewMethod) - { - } - - private int numArgs = 0; - - /// - /// number of arguments found by InvocationExaminer - /// - public int NumArgs { - set { - numArgs = value; - } - } - - /// - public override int PopCount { - get { - return numArgs+3; - } - } - - /// - public override int PushCount { get { return 1; } } - - /// overriden ToString method - public override string ToString() { - return "newMethod"; - } - } + public class ActionNewMethod : BaseAction { + + /// + /// constructor + /// + public ActionNewMethod():base(ActionCode.NewMethod) + { + } + + private int numArgs = 0; + + /// + /// number of arguments found by InvocationExaminer + /// + public int NumArgs { + set { + numArgs = value; + } + } + + /// + public override int PopCount { + get { + return numArgs+3; + } + } + + /// + public override int PushCount { get { return 1; } } + + /// overriden ToString method + public override string ToString() { + return "newMethod"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionNewObject.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionNewObject.cs index 2c3310a206..5bec984ea5 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionNewObject.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionNewObject.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,42 +24,42 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionNewObject : BaseAction { - - /// - /// constructor - /// - public ActionNewObject():base(ActionCode.NewObject) - { - } - - private int numArgs = 0; - - /// - /// argument count found by InvocationExaminer - /// - public int NumArgs { - set { - numArgs = value; - } - } - - /// - public override int PopCount { - get { - return numArgs+2; - } - } - /// - public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "new"; - } - } + public class ActionNewObject : BaseAction { + + /// + /// constructor + /// + public ActionNewObject():base(ActionCode.NewObject) + { + } + + private int numArgs = 0; + + /// + /// argument count found by InvocationExaminer + /// + public int NumArgs { + set { + numArgs = value; + } + } + + /// + public override int PopCount { + get { + return numArgs+2; + } + } + /// + public override int PushCount { get { return 1; } } + /// overriden ToString method + public override string ToString() { + return "new"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionNextFrame.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionNextFrame.cs index 79a7b2789d..f8a1a50da6 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionNextFrame.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionNextFrame.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,22 +24,22 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionNextFrame : BaseAction { - - /// - /// constructor - /// - public ActionNextFrame():base(ActionCode.NextFrame) - { - } - - /// overriden ToString method - public override string ToString() { - return "next"; - } - } + public class ActionNextFrame : BaseAction { + + /// + /// constructor + /// + public ActionNextFrame():base(ActionCode.NextFrame) + { + } + + /// overriden ToString method + public override string ToString() { + return "next"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionNot.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionNot.cs index 6d88c4986b..574828bafb 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionNot.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionNot.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionNot : BaseAction { - - /// - /// constructor - /// - public ActionNot():base(ActionCode.Not) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionNot : BaseAction { + + /// + /// constructor + /// + public ActionNot():base(ActionCode.Not) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "not"; - } - } + /// overriden ToString method + public override string ToString() { + return "not"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionOr.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionOr.cs index f22e9480a8..57072885ad 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionOr.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionOr.cs @@ -1,53 +1,53 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - - /// - /// bytecode instruction object - /// +{ + + /// + /// bytecode instruction object + /// - public class ActionOr : BaseAction { - - /// - /// constructor - /// - public ActionOr():base(ActionCode.Or) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionOr : BaseAction { + + /// + /// constructor + /// + public ActionOr():base(ActionCode.Or) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "or"; - } - } + /// overriden ToString method + public override string ToString() { + return "or"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionPlay.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionPlay.cs index 1f147414ba..d75a8262c6 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionPlay.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionPlay.cs @@ -1,47 +1,47 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - // pop: 0, push: 0 - /// - /// bytecode instruction object - /// +{ + // pop: 0, push: 0 + /// + /// bytecode instruction object + /// - public class ActionPlay : BaseAction { - - /// - /// constructor - /// - public ActionPlay():base(ActionCode.Play) - { - } - - /// overriden ToString method - public override string ToString() { - return "play"; - } - } + public class ActionPlay : BaseAction { + + /// + /// constructor + /// + public ActionPlay():base(ActionCode.Play) + { + } + + /// overriden ToString method + public override string ToString() { + return "play"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionPop.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionPop.cs index b20e12bf36..cda06895c3 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionPop.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionPop.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -27,31 +27,31 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Utils; namespace SwfOp.ByteCode.Actions -{ - - /// - /// bytecode instruction object - /// +{ + + /// + /// bytecode instruction object + /// - public class ActionPop : BaseAction { - - /// - /// constructor - /// - public ActionPop():base(ActionCode.Pop) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "pop"; - } - } + public class ActionPop : BaseAction { + + /// + /// constructor + /// + public ActionPop():base(ActionCode.Pop) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "pop"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionPreviousFrame.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionPreviousFrame.cs index 43a9da1341..c20a46cc9e 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionPreviousFrame.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionPreviousFrame.cs @@ -1,47 +1,47 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - // pop: 0, push: 0 - /// - /// bytecode instruction object - /// +{ + // pop: 0, push: 0 + /// + /// bytecode instruction object + /// - public class ActionPreviousFrame : BaseAction { - - /// - /// constructor - /// - public ActionPreviousFrame():base(ActionCode.PreviousFrame) - { - } - - /// overriden ToString method - public override string ToString() { - return "prev"; - } - } + public class ActionPreviousFrame : BaseAction { + + /// + /// constructor + /// + public ActionPreviousFrame():base(ActionCode.PreviousFrame) + { + } + + /// overriden ToString method + public override string ToString() { + return "prev"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionPush.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionPush.cs index f8b0b73e31..980e99e3c4 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionPush.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionPush.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -32,219 +32,219 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionPush : MultiByteAction { - - /// - /// enumaration of push types - /// - public enum PushType { - /// push type 0: string - String = 0, - /// push type 1: float - Float = 1, - /// push type 2: null - Null = 2, - /// push type 3: undef - Undef = 3, - /// push type 4: register - Register = 4, - /// push type 5: bool - Boolean = 5, - /// push type 6: double - Double = 6, - /// push type 7: int - Int = 7, - /// push type 8: constant8 - Constant8 = 8, - /// push type 9: constant9 - Constant16 = 9 - } - - private string[] PushTypeNames = new string[10] { - "string ", - "float ", - "null ", - "undef ", - "register ", - "bool ", - "double ", - "int ", - "var ", - "var " - }; - - /// - /// push type - /// - public int Type; - - /// - /// push value - /// - public object Value; - - /// - /// constructor. - /// - /// push type - /// push value - public ActionPush(int type,object val):base(ActionCode.Push) - { - if ((type<(int)PushType.String)||(type>(int)PushType.Constant16)) { - throw new InvalidPushTypeException(); - } - Type = type; - Value = val; - } - - /// - public override int ByteCount { - - get { - - switch ( (PushType) Type) { - - case PushType.String: - string str = (string) Value; - return str.Length + 5; - - case PushType.Float: - return 8; - - case PushType.Register: - return 5; - - case PushType.Boolean: - return 5; - - case PushType.Double: - return 12; - - case PushType.Int: - return 8; - - case PushType.Constant8: - return 5; - - case PushType.Constant16: - return 6; - } - // Null, Undef - return 4; - } - } - - /// - /// get push value as int - /// - /// pushed value as int - public int GetIntValue() { - - switch ( (PushType) Type) { - - case PushType.Float: return Convert.ToInt32((Single)Value); - - case PushType.Double: return Convert.ToInt32((double)Value); - - case PushType.String: return Convert.ToInt32((string)Value); - - case PushType.Int: return (int)Value; - - default: //Console.WriteLine("WARNING"); - return -1; - } - } - - /// - /// get value as string - /// - /// pushed value as string - public string GetStringValue() { - return ((PushType)Type==PushType.String) ? (string)Value : null; - } - - /// - /// compile push type and value (but not action code), so method can - /// be used by ActionPushList as well - /// - public void CompileBody(BinaryWriter w) { - - w.Write(Convert.ToByte(Type)); - - switch ( (PushType) Type) { - - case PushType.String: - string stringToWrite = (string) Value; - BinaryStringRW.WriteString(w,stringToWrite); - break; - - case PushType.Float: - w.Write(Convert.ToSingle(Value)); - break; - - case PushType.Register: - w.Write(Convert.ToByte(Value)); - break; - - case PushType.Boolean: - w.Write((bool)Value); - break; - - case PushType.Double: - byte[] b = BitConverter.GetBytes((double)Value); - for (int i=0; i<4; i++) { - byte temp = b[i]; - b[i] = b[4+i]; - b[4+i] = temp; - } - w.Write(b); - break; - - case PushType.Int: - w.Write((int)Value); - break; - - case PushType.Constant8: - w.Write(Convert.ToByte(Value)); - break; - - case PushType.Constant16: - w.Write(Convert.ToUInt16(Value)); - break; - - } - } - - /// - public override int PopCount { - get { - return 0; - } - } - - /// - public override int PushCount { - get { - return 1; - } - } - - /// - public override void Compile(BinaryWriter w) + public class ActionPush : MultiByteAction { + + /// + /// enumaration of push types + /// + public enum PushType { + /// push type 0: string + String = 0, + /// push type 1: float + Float = 1, + /// push type 2: null + Null = 2, + /// push type 3: undef + Undef = 3, + /// push type 4: register + Register = 4, + /// push type 5: bool + Boolean = 5, + /// push type 6: double + Double = 6, + /// push type 7: int + Int = 7, + /// push type 8: constant8 + Constant8 = 8, + /// push type 9: constant9 + Constant16 = 9 + } + + private string[] PushTypeNames = new string[10] { + "string ", + "float ", + "null ", + "undef ", + "register ", + "bool ", + "double ", + "int ", + "var ", + "var " + }; + + /// + /// push type + /// + public int Type; + + /// + /// push value + /// + public object Value; + + /// + /// constructor. + /// + /// push type + /// push value + public ActionPush(int type,object val):base(ActionCode.Push) + { + if ((type<(int)PushType.String)||(type>(int)PushType.Constant16)) { + throw new InvalidPushTypeException(); + } + Type = type; + Value = val; + } + + /// + public override int ByteCount { + + get { + + switch ( (PushType) Type) { + + case PushType.String: + string str = (string) Value; + return str.Length + 5; + + case PushType.Float: + return 8; + + case PushType.Register: + return 5; + + case PushType.Boolean: + return 5; + + case PushType.Double: + return 12; + + case PushType.Int: + return 8; + + case PushType.Constant8: + return 5; + + case PushType.Constant16: + return 6; + } + // Null, Undef + return 4; + } + } + + /// + /// get push value as int + /// + /// pushed value as int + public int GetIntValue() { + + switch ( (PushType) Type) { + + case PushType.Float: return Convert.ToInt32((Single)Value); + + case PushType.Double: return Convert.ToInt32((double)Value); + + case PushType.String: return Convert.ToInt32((string)Value); + + case PushType.Int: return (int)Value; + + default: //Console.WriteLine("WARNING"); + return -1; + } + } + + /// + /// get value as string + /// + /// pushed value as string + public string GetStringValue() { + return ((PushType)Type==PushType.String) ? (string)Value : null; + } + + /// + /// compile push type and value (but not action code), so method can + /// be used by ActionPushList as well + /// + public void CompileBody(BinaryWriter w) { + + w.Write(Convert.ToByte(Type)); + + switch ( (PushType) Type) { + + case PushType.String: + string stringToWrite = (string) Value; + BinaryStringRW.WriteString(w,stringToWrite); + break; + + case PushType.Float: + w.Write(Convert.ToSingle(Value)); + break; + + case PushType.Register: + w.Write(Convert.ToByte(Value)); + break; + + case PushType.Boolean: + w.Write((bool)Value); + break; + + case PushType.Double: + byte[] b = BitConverter.GetBytes((double)Value); + for (int i=0; i<4; i++) { + byte temp = b[i]; + b[i] = b[4+i]; + b[4+i] = temp; + } + w.Write(b); + break; + + case PushType.Int: + w.Write((int)Value); + break; + + case PushType.Constant8: + w.Write(Convert.ToByte(Value)); + break; + + case PushType.Constant16: + w.Write(Convert.ToUInt16(Value)); + break; + + } + } + + /// + public override int PopCount { + get { + return 0; + } + } + + /// + public override int PushCount { + get { + return 1; + } + } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - CompileBody(w); - } - - /// overriden ToString method - public override string ToString() { - string b = (( (PushType)Type == PushType.String) ? "'" :""); - return String.Format("push {1} as {0}",PushTypeNames[(int)Type],b+Value+b); - } - } + base.Compile(w); + CompileBody(w); + } + + /// overriden ToString method + public override string ToString() { + string b = (( (PushType)Type == PushType.String) ? "'" :""); + return String.Format("push {1} as {0}",PushTypeNames[(int)Type],b+Value+b); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionPushDuplicate.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionPushDuplicate.cs index 332f60090d..952e97ca4d 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionPushDuplicate.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionPushDuplicate.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -27,30 +27,30 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Utils; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionPushDuplicate : BaseAction { - - /// - /// constructor - /// - public ActionPushDuplicate():base(ActionCode.PushDuplicate) - { - } - - /// - public override int PopCount { get { return 0; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionPushDuplicate : BaseAction { + + /// + /// constructor + /// + public ActionPushDuplicate():base(ActionCode.PushDuplicate) + { + } + + /// + public override int PopCount { get { return 0; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "dup"; - } - } + /// overriden ToString method + public override string ToString() { + return "dup"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionPushList.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionPushList.cs index da9c0f4c2a..f021647ac2 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionPushList.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionPushList.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -27,88 +27,88 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Utils; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionPushList : MultiByteAction { - - private ActionPush[] pushList; - - /// - /// length of push list - /// - public int Length { - get { - return pushList.Length; - } - } - - /// - /// constructor - /// - /// list of single push instructions - public ActionPushList(ActionPush[] p):base(ActionCode.PushList) - { - pushList = p; - - } - - /// - /// indexer to access single push actions - /// - public ActionPush this[int i] { - get { - return pushList[i]; - } - } - - /// - public override int ByteCount { - get { - int count = 3; - foreach (ActionPush p in pushList) { - count+=p.ByteCount-3; - } - return count; - } - } - - /// - public override int PopCount { - get { - return 0; - } - } - - /// - public override int PushCount { - get { - return pushList.Length; - } - } - /// - public override void Compile(BinaryWriter w) + public class ActionPushList : MultiByteAction { + + private ActionPush[] pushList; + + /// + /// length of push list + /// + public int Length { + get { + return pushList.Length; + } + } + + /// + /// constructor + /// + /// list of single push instructions + public ActionPushList(ActionPush[] p):base(ActionCode.PushList) + { + pushList = p; + + } + + /// + /// indexer to access single push actions + /// + public ActionPush this[int i] { + get { + return pushList[i]; + } + } + + /// + public override int ByteCount { + get { + int count = 3; + foreach (ActionPush p in pushList) { + count+=p.ByteCount-3; + } + return count; + } + } + + /// + public override int PopCount { + get { + return 0; + } + } + + /// + public override int PushCount { + get { + return pushList.Length; + } + } + /// + public override void Compile(BinaryWriter w) { - - // base.Compile(w); - w.Write((byte)0x96); - w.Write(Convert.ToUInt16(ByteCount-3)); - - foreach (ActionPush push in pushList) { - push.CompileBody(w); - } - } - - /// overriden ToString method - public override string ToString() { - string[] s = new string[pushList.Length]; - for (int i=0; ioverriden ToString method + public override string ToString() { + string[] s = new string[pushList.Length]; + for (int i=0; i - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionRandomNumber : BaseAction { - - /// - /// constructor - /// - public ActionRandomNumber():base(ActionCode.RandomNumber) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionRandomNumber : BaseAction { + + /// + /// constructor + /// + public ActionRandomNumber():base(ActionCode.RandomNumber) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "random"; - } - } + /// overriden ToString method + public override string ToString() { + return "random"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionRemoveSprite.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionRemoveSprite.cs index 81e05a9d9d..8e9a47ca7a 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionRemoveSprite.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionRemoveSprite.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionRemoveSprite : BaseAction { - - /// - /// constructor - /// - public ActionRemoveSprite():base(ActionCode.RemoveSprite) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "removeMovie"; - } - } + public class ActionRemoveSprite : BaseAction { + + /// + /// constructor + /// + public ActionRemoveSprite():base(ActionCode.RemoveSprite) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "removeMovie"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionReturn.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionReturn.cs index fbe6df7695..447118534a 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionReturn.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionReturn.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,30 +24,30 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionReturn : BaseAction { - - /// - /// constructor - /// - public ActionReturn():base(ActionCode.Return) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } + public class ActionReturn : BaseAction { + + /// + /// constructor + /// + public ActionReturn():base(ActionCode.Return) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } - /// overriden ToString method - public override string ToString() { - return "return"; - } - } - + /// overriden ToString method + public override string ToString() { + return "return"; + } + } + } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionSetMember.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionSetMember.cs index e03d161acd..fd5c5f6062 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionSetMember.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionSetMember.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionSetMember : BaseAction { - - /// - /// constructor - /// - public ActionSetMember():base(ActionCode.SetMember) - { - } + public class ActionSetMember : BaseAction { + + /// + /// constructor + /// + public ActionSetMember():base(ActionCode.SetMember) + { + } - /// - public override int PopCount { get { return 3; } } + /// + public override int PopCount { get { return 3; } } - /// - public override int PushCount { get { return 0; } } + /// + public override int PushCount { get { return 0; } } - /// overriden ToString method - public override string ToString() { - return String.Format("setMember"); - } - } + /// overriden ToString method + public override string ToString() { + return String.Format("setMember"); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionSetProperty.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionSetProperty.cs index 26e031d8e0..4a4cd365da 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionSetProperty.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionSetProperty.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionSetProperty : BaseAction { - - /// - /// constructor - /// - public ActionSetProperty():base(ActionCode.SetProperty) - { - } - - /// - public override int PopCount { get { return 3; } } - - /// - public override int PushCount { get { return 0; } } + public class ActionSetProperty : BaseAction { + + /// + /// constructor + /// + public ActionSetProperty():base(ActionCode.SetProperty) + { + } + + /// + public override int PopCount { get { return 3; } } + + /// + public override int PushCount { get { return 0; } } - /// overriden ToString method - public override string ToString() { - return "setProperty"; - } - } + /// overriden ToString method + public override string ToString() { + return "setProperty"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionSetTarget.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionSetTarget.cs index a1a0b8939e..8663cfe845 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionSetTarget.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionSetTarget.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -26,39 +26,39 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - - /// - /// bytecode instruction object - /// + + /// + /// bytecode instruction object + /// - public class ActionSetTarget : MultiByteAction { - - private string target; - - /// - /// constructor - /// - public ActionSetTarget(string t):base(ActionCode.SetTarget) - { - target = t; - } - - /// - public override int ByteCount { - get { - return target.Length+4; - } - } + public class ActionSetTarget : MultiByteAction { + + private string target; + + /// + /// constructor + /// + public ActionSetTarget(string t):base(ActionCode.SetTarget) + { + target = t; + } + + /// + public override int ByteCount { + get { + return target.Length+4; + } + } - /// overriden ToString method - public override string ToString() { - return String.Format("setTarget '{0}'",target); - } + /// overriden ToString method + public override string ToString() { + return String.Format("setTarget '{0}'",target); + } - /// - public override void Compile(BinaryWriter w) { - base.Compile(w); - BinaryStringRW.WriteString(w,target); - } - } + /// + public override void Compile(BinaryWriter w) { + base.Compile(w); + BinaryStringRW.WriteString(w,target); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionSetTarget2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionSetTarget2.cs index 18a1f2311d..4d9185d0b7 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionSetTarget2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionSetTarget2.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,37 +25,37 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionSetTarget2 : BaseAction { - - /// - /// constructor - /// - public ActionSetTarget2():base(ActionCode.SetTarget2) - { - } - - /// - public override int PopCount { - get { - return 1; - } - } - - /// - public override int PushCount { - get { - return 0; - } - } + public class ActionSetTarget2 : BaseAction { + + /// + /// constructor + /// + public ActionSetTarget2():base(ActionCode.SetTarget2) + { + } + + /// + public override int PopCount { + get { + return 1; + } + } + + /// + public override int PushCount { + get { + return 0; + } + } - /// overriden ToString method - public override string ToString() { - return "setTargetExpr"; - } - } + /// overriden ToString method + public override string ToString() { + return "setTargetExpr"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionSetVariable.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionSetVariable.cs index 4188ed27b8..11a2285a41 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionSetVariable.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionSetVariable.cs @@ -1,53 +1,53 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionSetVariable : BaseAction { - - - /// - /// constructor - /// - public ActionSetVariable():base(ActionCode.SetVariable) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return String.Format("setVariable"); - } - } + public class ActionSetVariable : BaseAction { + + + /// + /// constructor + /// + public ActionSetVariable():base(ActionCode.SetVariable) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return String.Format("setVariable"); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStackSwap.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStackSwap.cs index 7849d2492c..5fc48687d6 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStackSwap.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStackSwap.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -27,29 +27,29 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Utils; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionStackSwap : BaseAction { - - /// - /// constructor - /// - public ActionStackSwap():base(ActionCode.StackSwap) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionStackSwap : BaseAction { + + /// + /// constructor + /// + public ActionStackSwap():base(ActionCode.StackSwap) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "swap"; - } - } + /// overriden ToString method + public override string ToString() { + return "swap"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStartDrag.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStartDrag.cs index 365df80938..6304dfc6ba 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStartDrag.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStartDrag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,46 +24,46 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - - /// - /// bytecode instruction object - /// + + /// + /// bytecode instruction object + /// - public class ActionStartDrag : BaseAction { - - /// - /// constructor - /// - public ActionStartDrag():base(ActionCode.StartDrag) - { - } - - private bool _constrain = false; - - /// - /// constrain property; see swf specs - /// - public bool Constrain { - set { - _constrain = value; - } - get { - return _constrain ; - } - } - - /// - public override int PopCount { - get { - return _constrain ? 7 : 3; - } - } - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "startDrag"; - } - } + public class ActionStartDrag : BaseAction { + + /// + /// constructor + /// + public ActionStartDrag():base(ActionCode.StartDrag) + { + } + + private bool _constrain = false; + + /// + /// constrain property; see swf specs + /// + public bool Constrain { + set { + _constrain = value; + } + get { + return _constrain ; + } + } + + /// + public override int PopCount { + get { + return _constrain ? 7 : 3; + } + } + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "startDrag"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStop.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStop.cs index ecf883e071..e2d29999f4 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStop.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStop.cs @@ -1,46 +1,46 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - // pop: 0, push: 0 - /// - /// bytecode instruction object - /// +{ + // pop: 0, push: 0 + /// + /// bytecode instruction object + /// - public class ActionStop : BaseAction { - - /// - /// constructor - /// - public ActionStop():base(ActionCode.Stop) - { - } - - /// overriden ToString method - public override string ToString() { - return "stop"; - } - } + public class ActionStop : BaseAction { + + /// + /// constructor + /// + public ActionStop():base(ActionCode.Stop) + { + } + + /// overriden ToString method + public override string ToString() { + return "stop"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStopSounds.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStopSounds.cs index a907a2c412..1121a4e7e3 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStopSounds.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStopSounds.cs @@ -1,47 +1,47 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - // pop: 0, push: 0 - /// - /// bytecode instruction object - /// +{ + // pop: 0, push: 0 + /// + /// bytecode instruction object + /// - public class ActionStopSounds : BaseAction { - - /// - /// constructor - /// - public ActionStopSounds():base(ActionCode.StopSounds) - { - } - - /// overriden ToString method - public override string ToString() { - return "stopAllSounds"; - } - } + public class ActionStopSounds : BaseAction { + + /// + /// constructor + /// + public ActionStopSounds():base(ActionCode.StopSounds) + { + } + + /// overriden ToString method + public override string ToString() { + return "stopAllSounds"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStoreRegister.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStoreRegister.cs index 0ba6753b6e..2996f58325 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStoreRegister.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStoreRegister.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,42 +25,42 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// - public class ActionStoreRegister : MultiByteAction { - - /// - /// register number - /// - public byte Register; // register number - - /// - /// constructor - /// - /// register number - public ActionStoreRegister(byte r):base(ActionCode.StoreRegister) - { - Register = r; - } - - /// - public override int ByteCount { - get { - return 4; - } - } - - /// - public override void Compile(BinaryWriter w) + /// + /// bytecode instruction object + /// + public class ActionStoreRegister : MultiByteAction { + + /// + /// register number + /// + public byte Register; // register number + + /// + /// constructor + /// + /// register number + public ActionStoreRegister(byte r):base(ActionCode.StoreRegister) + { + Register = r; + } + + /// + public override int ByteCount { + get { + return 4; + } + } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(Register); - } - - /// overriden ToString method - public override string ToString() { - return String.Format("set r:{0}",Register); - } - } + base.Compile(w); + w.Write(Register); + } + + /// overriden ToString method + public override string ToString() { + return String.Format("set r:{0}",Register); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStrictEquals.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStrictEquals.cs index 8e09b6519d..83c2d570c9 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStrictEquals.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStrictEquals.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionStrictEquals : BaseAction { - - /// - /// constructor - /// - public ActionStrictEquals():base(ActionCode.StrictEquals) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionStrictEquals : BaseAction { + + /// + /// constructor + /// + public ActionStrictEquals():base(ActionCode.StrictEquals) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "strictEquals"; - } - } + /// overriden ToString method + public override string ToString() { + return "strictEquals"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStringAdd.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStringAdd.cs index ca2b07c0a6..40cb789541 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStringAdd.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStringAdd.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionStringAdd : BaseAction { - - /// - /// constructor - /// - public ActionStringAdd():base(ActionCode.StringAdd) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionStringAdd : BaseAction { + + /// + /// constructor + /// + public ActionStringAdd():base(ActionCode.StringAdd) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "string add"; - } - } + /// overriden ToString method + public override string ToString() { + return "string add"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStringEquals.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStringEquals.cs index f9d0e7beb4..49761af53f 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStringEquals.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStringEquals.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionStringEquals : BaseAction { - - /// - /// constructor - /// - public ActionStringEquals():base(ActionCode.StringEquals) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionStringEquals : BaseAction { + + /// + /// constructor + /// + public ActionStringEquals():base(ActionCode.StringEquals) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "string equals"; - } - } + /// overriden ToString method + public override string ToString() { + return "string equals"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStringExtract.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStringExtract.cs index 818377040c..67530bcfdb 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStringExtract.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStringExtract.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionStringExtract : BaseAction { - - /// - /// constructor - /// - public ActionStringExtract():base(ActionCode.StringExtract) - { - } - - /// - public override int PopCount { get { return 3; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionStringExtract : BaseAction { + + /// + /// constructor + /// + public ActionStringExtract():base(ActionCode.StringExtract) + { + } + + /// + public override int PopCount { get { return 3; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "substring"; - } - } + /// overriden ToString method + public override string ToString() { + return "substring"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStringGreater.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStringGreater.cs index fd054c2c20..b2f8fa66bb 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStringGreater.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStringGreater.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,30 +24,30 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - - /// - /// bytecode instruction object - /// + + /// + /// bytecode instruction object + /// - public class ActionStringGreater : BaseAction { - - /// - /// constructor - /// - public ActionStringGreater():base(ActionCode.StringGreater) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionStringGreater : BaseAction { + + /// + /// constructor + /// + public ActionStringGreater():base(ActionCode.StringGreater) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "setRegister"; - } - } + /// overriden ToString method + public override string ToString() { + return "setRegister"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStringLength.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStringLength.cs index 7e76c3577a..7e544224d3 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStringLength.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStringLength.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// bytecode instruction object - /// + /// + /// bytecode instruction object + /// - public class ActionStringLength : BaseAction { - - /// - /// constructor - /// - public ActionStringLength():base(ActionCode.StringLength) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionStringLength : BaseAction { + + /// + /// constructor + /// + public ActionStringLength():base(ActionCode.StringLength) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "strLen"; - } - } + /// overriden ToString method + public override string ToString() { + return "strLen"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionStringLess.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionStringLess.cs index 6727ddc3eb..6c5e1b5419 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionStringLess.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionStringLess.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,30 +24,30 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - - /// - /// bytecode instruction object - /// + + /// + /// bytecode instruction object + /// - public class ActionStringLess : BaseAction { - - /// - /// constructor - /// - public ActionStringLess():base(ActionCode.StringLess) - { - } - - /// - public override int PopCount { get { return 2; } } + public class ActionStringLess : BaseAction { + + /// + /// constructor + /// + public ActionStringLess():base(ActionCode.StringLess) + { + } + + /// + public override int PopCount { get { return 2; } } - /// - public override int PushCount { get { return 1; } } + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "strLess"; - } - } + /// overriden ToString method + public override string ToString() { + return "strLess"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionSubtract.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionSubtract.cs index 5792b7b7e4..0a2b0700db 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionSubtract.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionSubtract.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - - /// - /// bytecode instruction object - /// - public class ActionSubtract : BaseAction { - - /// - /// constructor - /// - public ActionSubtract():base(ActionCode.Subtract) - { - } - - /// - public override int PopCount { get { return 2; } } - - /// - public override int PushCount { get { return 1; } } +{ + + /// + /// bytecode instruction object + /// + public class ActionSubtract : BaseAction { + + /// + /// constructor + /// + public ActionSubtract():base(ActionCode.Subtract) + { + } + + /// + public override int PopCount { get { return 2; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "subtract"; - } - } + /// overriden ToString method + public override string ToString() { + return "subtract"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionTargetPath.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionTargetPath.cs index feadecbbaf..0a85d0a5fd 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionTargetPath.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionTargetPath.cs @@ -1,52 +1,52 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionTargetPath : BaseAction { - - - /// - /// constructor - /// - public ActionTargetPath():base(ActionCode.TargetPath) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } - - /// overriden ToString method - public override string ToString() { - return "targetPath"; - } - } + public class ActionTargetPath : BaseAction { + + + /// + /// constructor + /// + public ActionTargetPath():base(ActionCode.TargetPath) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } + + /// overriden ToString method + public override string ToString() { + return "targetPath"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionThrow.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionThrow.cs index 9c4d131ccd..49cdaa5c88 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionThrow.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionThrow.cs @@ -1,50 +1,50 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace SwfOp.ByteCode.Actions -{ - - /// - /// bytecode instruction object - /// +{ + + /// + /// bytecode instruction object + /// - public class ActionThrow : BaseAction { - - /// - /// constructor - /// - public ActionThrow():base(ActionCode.Throw) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "throw"; - } - } + public class ActionThrow : BaseAction { + + /// + /// constructor + /// + public ActionThrow():base(ActionCode.Throw) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "throw"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionToInteger.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionToInteger.cs index 1e46e32812..2e4fc97f28 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionToInteger.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionToInteger.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,29 +24,29 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionToInteger : BaseAction { - - /// - /// constructor - /// - public ActionToInteger():base(ActionCode.ToInteger) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionToInteger : BaseAction { + + /// + /// constructor + /// + public ActionToInteger():base(ActionCode.ToInteger) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "int"; - } - } + /// overriden ToString method + public override string ToString() { + return "int"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionToNumber.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionToNumber.cs index c7132fc0c5..7bc6bb3fcd 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionToNumber.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionToNumber.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,30 +24,30 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionToNumber : BaseAction { - - /// - /// constructor - /// - public ActionToNumber():base(ActionCode.ToNumber) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } - - /// overriden ToString method - public override string ToString() { - return "number"; - } - } + public class ActionToNumber : BaseAction { + + /// + /// constructor + /// + public ActionToNumber():base(ActionCode.ToNumber) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } + + /// overriden ToString method + public override string ToString() { + return "number"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionToString.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionToString.cs index 953711e3d7..b8b22e9c6a 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionToString.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionToString.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,30 +24,30 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionToString : BaseAction { - - /// - /// constructor - /// - public ActionToString():base(ActionCode.ToString) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } - - /// overriden ToString method - public override string ToString() { - return "string"; - } - } + public class ActionToString : BaseAction { + + /// + /// constructor + /// + public ActionToString():base(ActionCode.ToString) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } + + /// overriden ToString method + public override string ToString() { + return "string"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionToggleQuality.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionToggleQuality.cs index 95a6207803..9ead2b3ad1 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionToggleQuality.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionToggleQuality.cs @@ -1,46 +1,46 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionToggleQuality : BaseAction { - - /// - /// constructor - /// - public ActionToggleQuality():base(ActionCode.ToggleQuality) - { - } - - /// overriden ToString method - public override string ToString() { - return "toggleQuality"; - } - } + public class ActionToggleQuality : BaseAction { + + /// + /// constructor + /// + public ActionToggleQuality():base(ActionCode.ToggleQuality) + { + } + + /// overriden ToString method + public override string ToString() { + return "toggleQuality"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionTrace.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionTrace.cs index 2d76898488..8a589b82ba 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionTrace.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionTrace.cs @@ -1,51 +1,51 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionTrace : BaseAction { - - /// - /// constructor - /// - public ActionTrace():base(ActionCode.Trace) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } - - /// overriden ToString method - public override string ToString() { - return "trace"; - } - } + public class ActionTrace : BaseAction { + + /// + /// constructor + /// + public ActionTrace():base(ActionCode.Trace) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } + + /// overriden ToString method + public override string ToString() { + return "trace"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionTry.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionTry.cs index 267dba5125..1e59cd4db9 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionTry.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionTry.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,119 +25,119 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Utils; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object try/catch/finally block - /// +{ + /// + /// bytecode instruction object try/catch/finally block + /// - public class ActionTry : MultiByteAction { - - private bool catchesInReg; - private bool hasFinally,hasCatch; - private ushort trySize,catchSize,finallySize; - private string catchVar; - private byte catchReg; - - /// - /// byte size of try block - /// - public int SizeTry { - get { - return Convert.ToInt32(trySize); - } - set { - trySize = Convert.ToUInt16(value); - } - } - - /// - /// byte size of catch block - /// - public int SizeCatch { - get { - return Convert.ToInt32(catchSize); - } - set { - catchSize = Convert.ToUInt16(value); - hasCatch = (catchSize>(ushort)0); - } - } - - /// - /// byte size of finally block - /// - public int SizeFinally { - get { - return Convert.ToInt32(finallySize); - } - set { - finallySize = Convert.ToUInt16(value); - hasFinally = (finallySize>(ushort)0); - } - } - - /// - /// constructor - /// - public ActionTry( bool catchRegFlag, - bool finallyFlag, - bool catchFlag, - ushort trySize, - ushort catchSize, - ushort finallySize, - string catchName, - byte catchRegister - ) : base(ActionCode.Try) - { - hasFinally = finallyFlag; - hasCatch = catchFlag; - catchesInReg = catchRegFlag; - - SizeTry = trySize; - SizeCatch = hasCatch ? catchSize : (ushort)0; - SizeFinally = hasFinally ? finallySize : (ushort)0; - - catchVar = catchName; - catchReg = catchRegister; - } - - /// - public override int ByteCount { - get { - return 10+(catchesInReg ? 1 : catchVar.Length+1); - } - } - - /// overriden ToString method - public override string ToString() { - string catchStr = hasCatch ? - String.Format("catch({0}) [{1}]",(catchesInReg ? ("r:"+catchReg.ToString()):"'"+catchVar+"'"),catchSize) - : ""; - string finallyStr = hasFinally ? String.Format("finally [{0}]",finallySize) : ""; - return String.Format("TryBlock: try[{0}] {1} {2}",trySize,catchStr,finallyStr); - } - - /// - public override void Compile(BinaryWriter w) + public class ActionTry : MultiByteAction { + + private bool catchesInReg; + private bool hasFinally,hasCatch; + private ushort trySize,catchSize,finallySize; + private string catchVar; + private byte catchReg; + + /// + /// byte size of try block + /// + public int SizeTry { + get { + return Convert.ToInt32(trySize); + } + set { + trySize = Convert.ToUInt16(value); + } + } + + /// + /// byte size of catch block + /// + public int SizeCatch { + get { + return Convert.ToInt32(catchSize); + } + set { + catchSize = Convert.ToUInt16(value); + hasCatch = (catchSize>(ushort)0); + } + } + + /// + /// byte size of finally block + /// + public int SizeFinally { + get { + return Convert.ToInt32(finallySize); + } + set { + finallySize = Convert.ToUInt16(value); + hasFinally = (finallySize>(ushort)0); + } + } + + /// + /// constructor + /// + public ActionTry( bool catchRegFlag, + bool finallyFlag, + bool catchFlag, + ushort trySize, + ushort catchSize, + ushort finallySize, + string catchName, + byte catchRegister + ) : base(ActionCode.Try) + { + hasFinally = finallyFlag; + hasCatch = catchFlag; + catchesInReg = catchRegFlag; + + SizeTry = trySize; + SizeCatch = hasCatch ? catchSize : (ushort)0; + SizeFinally = hasFinally ? finallySize : (ushort)0; + + catchVar = catchName; + catchReg = catchRegister; + } + + /// + public override int ByteCount { + get { + return 10+(catchesInReg ? 1 : catchVar.Length+1); + } + } + + /// overriden ToString method + public override string ToString() { + string catchStr = hasCatch ? + String.Format("catch({0}) [{1}]",(catchesInReg ? ("r:"+catchReg.ToString()):"'"+catchVar+"'"),catchSize) + : ""; + string finallyStr = hasFinally ? String.Format("finally [{0}]",finallySize) : ""; + return String.Format("TryBlock: try[{0}] {1} {2}",trySize,catchStr,finallyStr); + } + + /// + public override void Compile(BinaryWriter w) { - - base.Compile(w); - - byte flags = (byte)0; - if (catchesInReg) flags+=(byte) 0x04; - if (hasFinally) flags+=(byte) 0x02; - if (hasCatch) flags+=(byte) 0x01; - - w.Write(flags); - w.Write(trySize); - w.Write(catchSize); - w.Write(finallySize); - - if (catchesInReg) { - w.Write(catchReg); - } else { - BinaryStringRW.WriteString(w,catchVar); - } - } - } + + base.Compile(w); + + byte flags = (byte)0; + if (catchesInReg) flags+=(byte) 0x04; + if (hasFinally) flags+=(byte) 0x02; + if (hasCatch) flags+=(byte) 0x01; + + w.Write(flags); + w.Write(trySize); + w.Write(catchSize); + w.Write(finallySize); + + if (catchesInReg) { + w.Write(catchReg); + } else { + BinaryStringRW.WriteString(w,catchVar); + } + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionTypeOf.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionTypeOf.cs index c420d12156..8477ccd18f 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionTypeOf.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionTypeOf.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,30 +24,30 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// bytecode instruction object - /// +{ + /// + /// bytecode instruction object + /// - public class ActionTypeOf : BaseAction { - - /// - /// constructor - /// - public ActionTypeOf():base(ActionCode.TypeOf) - { - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 1; } } + public class ActionTypeOf : BaseAction { + + /// + /// constructor + /// + public ActionTypeOf():base(ActionCode.TypeOf) + { + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 1; } } - /// overriden ToString method - public override string ToString() { - return "typeof"; - } - } + /// overriden ToString method + public override string ToString() { + return "typeof"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionWaitForFrame.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionWaitForFrame.cs index cde1593a2d..76570c32d4 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionWaitForFrame.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionWaitForFrame.cs @@ -1,80 +1,80 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - - /// - /// bytecode instruction object - /// +{ + + /// + /// bytecode instruction object + /// - public class ActionWaitForFrame : MultiByteAction { - - private short waitFrame; - private byte skipCount; - - /// - /// count of byte to skip - /// - public int SkipCount { - get { - return Convert.ToInt32(skipCount); - } - set { - skipCount = Convert.ToByte(value); - } - } - - /// - /// constructor - /// - public ActionWaitForFrame(short wait,byte skip):base(ActionCode.WaitForFrame) - { - waitFrame = wait; - skipCount = skip; - } - - /// - public override int ByteCount { - get { - return 6; - } - } - - /// overriden ToString method - public override string ToString() { - return String.Format("WaitForFrame {0}",waitFrame.ToString()); - } - - /// - public override void Compile(BinaryWriter w) + public class ActionWaitForFrame : MultiByteAction { + + private short waitFrame; + private byte skipCount; + + /// + /// count of byte to skip + /// + public int SkipCount { + get { + return Convert.ToInt32(skipCount); + } + set { + skipCount = Convert.ToByte(value); + } + } + + /// + /// constructor + /// + public ActionWaitForFrame(short wait,byte skip):base(ActionCode.WaitForFrame) + { + waitFrame = wait; + skipCount = skip; + } + + /// + public override int ByteCount { + get { + return 6; + } + } + + /// overriden ToString method + public override string ToString() { + return String.Format("WaitForFrame {0}",waitFrame.ToString()); + } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(waitFrame); - w.Write(skipCount); - } - } - + base.Compile(w); + w.Write(waitFrame); + w.Write(skipCount); + } + } + } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionWaitForFrame2.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionWaitForFrame2.cs index 81bdb32ddf..63ddf10e2c 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionWaitForFrame2.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionWaitForFrame2.cs @@ -1,72 +1,72 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - - /// - /// bytecode instruction object - /// +{ + + /// + /// bytecode instruction object + /// - public class ActionWaitForFrame2 : MultiByteAction { - - private byte skipCount; - - /// count of bytes to skip - public int SkipCount { - get { - return Convert.ToInt32(skipCount); - } - set { - skipCount = Convert.ToByte(value); - } - } - - /// constructor - /// bytes to skip - public ActionWaitForFrame2(byte skip):base(ActionCode.WaitForFrame2) - { - skipCount = skip; - } - - /// - public override int ByteCount { - get { - return 4; - } - } - - /// overriden ToString method - public override string ToString() { - return "WaitForFrame2"; - } - - /// - public override void Compile(BinaryWriter w) + public class ActionWaitForFrame2 : MultiByteAction { + + private byte skipCount; + + /// count of bytes to skip + public int SkipCount { + get { + return Convert.ToInt32(skipCount); + } + set { + skipCount = Convert.ToByte(value); + } + } + + /// constructor + /// bytes to skip + public ActionWaitForFrame2(byte skip):base(ActionCode.WaitForFrame2) + { + skipCount = skip; + } + + /// + public override int ByteCount { + get { + return 4; + } + } + + /// overriden ToString method + public override string ToString() { + return "WaitForFrame2"; + } + + /// + public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(skipCount); - } - } + base.Compile(w); + w.Write(skipCount); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/ActionWith.cs b/External/Tools/SwfOp/ByteCode/Actions/ActionWith.cs index 0e91f6671c..bae2ad14d9 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/ActionWith.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/ActionWith.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,59 +24,59 @@ You should have received a copy of the GNU Lesser General Public using System; namespace SwfOp.ByteCode.Actions -{ - - /// - /// bytecode instruction object - /// +{ + + /// + /// bytecode instruction object + /// - public class ActionWith : MultiByteAction { - - private ushort blockLength; - - /// - /// block length of actions enclosed by 'with' - /// - public int BlockLength { - get { - return Convert.ToInt32(blockLength); - } - set { - blockLength = Convert.ToUInt16(value); - } - } - - /// - /// constructor - /// - /// block length of enclosed action - public ActionWith(ushort blockLen):base(ActionCode.With) - { - blockLength = blockLen; - } - - /// - public override int ByteCount { - get { - return 5; - } - } - - /// - public override int PopCount { get { return 1; } } - - /// - public override int PushCount { get { return 0; } } + public class ActionWith : MultiByteAction { + + private ushort blockLength; + + /// + /// block length of actions enclosed by 'with' + /// + public int BlockLength { + get { + return Convert.ToInt32(blockLength); + } + set { + blockLength = Convert.ToUInt16(value); + } + } + + /// + /// constructor + /// + /// block length of enclosed action + public ActionWith(ushort blockLen):base(ActionCode.With) + { + blockLength = blockLen; + } + + /// + public override int ByteCount { + get { + return 5; + } + } + + /// + public override int PopCount { get { return 1; } } + + /// + public override int PushCount { get { return 0; } } - /// overriden ToString method - public override string ToString() { - return String.Format("with [{0}]",blockLength.ToString()); - } - - /// - public override void Compile(BinaryWriter w) { - base.Compile(w); - w.Write(blockLength); - } - } + /// overriden ToString method + public override string ToString() { + return String.Format("with [{0}]",blockLength.ToString()); + } + + /// + public override void Compile(BinaryWriter w) { + base.Compile(w); + w.Write(blockLength); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/BaseAction.cs b/External/Tools/SwfOp/ByteCode/Actions/BaseAction.cs index 396c8b75fe..d4f12e1b2e 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/BaseAction.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/BaseAction.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,76 +25,76 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// BaseAction is an abstract class that serves as a base for all Action - /// classes resembling swf bytecode instructions - /// - - public abstract class BaseAction { - - /// - /// Action code of the class when compiled to swf - /// Action codes are enumerated in - /// - public readonly int Code; - - // no longer needed - //public int ByteSize; - - /// - /// public constructor - /// - /// action code as occuring in swf. Codes are listed in this enumeration - public BaseAction(ActionCode c) { - Code = (int) c; - //ByteSize = 1; - } - - /// - /// byte count, calculated during compilation for multibyte actions - /// - public virtual int ByteCount { - get { - return 1; - } - } - - /// - /// values pushed on stack by the operation associated with this action - /// during swf runtime - /// - public virtual int PushCount { - get { - return 0; - } - set { - - } - } - - /// - /// values popped from stack by the operation associated with this action - /// during swf runtime - /// - public virtual int PopCount { - get { - return 0; - } - set { - - } - } - - /// - /// compile action to byte code - /// - /// - /// Binary writer for writing byte code to stream - /// - public virtual void Compile(BinaryWriter writer) { - writer.Write(Convert.ToByte(Code)); - } + /// + /// BaseAction is an abstract class that serves as a base for all Action + /// classes resembling swf bytecode instructions + /// + + public abstract class BaseAction { + + /// + /// Action code of the class when compiled to swf + /// Action codes are enumerated in + /// + public readonly int Code; + + // no longer needed + //public int ByteSize; + + /// + /// public constructor + /// + /// action code as occuring in swf. Codes are listed in this enumeration + public BaseAction(ActionCode c) { + Code = (int) c; + //ByteSize = 1; + } + + /// + /// byte count, calculated during compilation for multibyte actions + /// + public virtual int ByteCount { + get { + return 1; + } + } + + /// + /// values pushed on stack by the operation associated with this action + /// during swf runtime + /// + public virtual int PushCount { + get { + return 0; + } + set { + + } + } + + /// + /// values popped from stack by the operation associated with this action + /// during swf runtime + /// + public virtual int PopCount { + get { + return 0; + } + set { + + } + } + + /// + /// compile action to byte code + /// + /// + /// Binary writer for writing byte code to stream + /// + public virtual void Compile(BinaryWriter writer) { + writer.Write(Convert.ToByte(Code)); + } - } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/DummyAction.cs b/External/Tools/SwfOp/ByteCode/Actions/DummyAction.cs index 3932f1dbd2..7c620c8dc7 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/DummyAction.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/DummyAction.cs @@ -1,54 +1,54 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; using System; namespace SwfOp.ByteCode.Actions -{ - /// - /// 'null' instruction - /// - public class DummyAction : BaseAction { - - /// - /// constructor - /// - public DummyAction():base(ActionCode.Dummy) - { - } +{ + /// + /// 'null' instruction + /// + public class DummyAction : BaseAction { + + /// + /// constructor + /// + public DummyAction():base(ActionCode.Dummy) + { + } - public override void Compile(BinaryWriter writer) { - - } + public override void Compile(BinaryWriter writer) { + + } - public override int ByteCount { - get { - return 0; - } - } - - /// overriden ToString method - public override string ToString() { - return ""; - } - } + public override int ByteCount { + get { + return 0; + } + } + + /// overriden ToString method + public override string ToString() { + return ""; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/IJump.cs b/External/Tools/SwfOp/ByteCode/Actions/IJump.cs index 5859beb02e..5ad3037d90 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/IJump.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/IJump.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -24,20 +24,20 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// interface for branch action - /// - public interface IJump { - - /// - /// branch offset - /// - int Offset { get; set; } - - /// - /// label id - /// - int LabelId { get; set; } - } + /// + /// interface for branch action + /// + public interface IJump { + + /// + /// branch offset + /// + int Offset { get; set; } + + /// + /// label id + /// + int LabelId { get; set; } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/InvalidPushTypeException.cs b/External/Tools/SwfOp/ByteCode/Actions/InvalidPushTypeException.cs index da4bf78621..6fa6533dfb 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/InvalidPushTypeException.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/InvalidPushTypeException.cs @@ -1,37 +1,37 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; namespace SwfOp.ByteCode.Actions { - /// - /// invalid push type exception - /// - public class InvalidPushTypeException : ApplicationException { - - /// - /// constructor - /// - public InvalidPushTypeException():base("InvalidPushTypeException") { - } - } + /// + /// invalid push type exception + /// + public class InvalidPushTypeException : ApplicationException { + + /// + /// constructor + /// + public InvalidPushTypeException():base("InvalidPushTypeException") { + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/MultiByteAction.cs b/External/Tools/SwfOp/ByteCode/Actions/MultiByteAction.cs index e936ef2eb6..8124962a50 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/MultiByteAction.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/MultiByteAction.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,20 +25,20 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - ///base class for multibyte actions (>0x80) - public abstract class MultiByteAction : BaseAction { - - /// - /// constructor - /// - /// action code as occuring in swf. Codes are listed in this enumeration - public MultiByteAction(ActionCode c) : base(c) { - } - - /// - public override void Compile(BinaryWriter writer) { - base.Compile(writer); - writer.Write(Convert.ToUInt16(ByteCount-3)); - } - } + ///base class for multibyte actions (>0x80) + public abstract class MultiByteAction : BaseAction { + + /// + /// constructor + /// + /// action code as occuring in swf. Codes are listed in this enumeration + public MultiByteAction(ActionCode c) : base(c) { + } + + /// + public override void Compile(BinaryWriter writer) { + base.Compile(writer); + writer.Write(Convert.ToUInt16(ByteCount-3)); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Actions/UnknownAction.cs b/External/Tools/SwfOp/ByteCode/Actions/UnknownAction.cs index 801cc4b73b..0c0ee47dbc 100644 --- a/External/Tools/SwfOp/ByteCode/Actions/UnknownAction.cs +++ b/External/Tools/SwfOp/ByteCode/Actions/UnknownAction.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,38 +25,38 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode.Actions { - /// - /// object for storing unknown actions - /// - public class UnknownAction : BaseAction { - - private byte[] bytecode; - - /// - /// constructor - /// - /// action code - /// additional bytecode - public UnknownAction(byte code,byte[] bytes) : base((ActionCode)code) - { - bytecode = bytes; - } - - /// - public override int ByteCount { - get { - return bytecode.Length; - } - } - - /// - public override void Compile(BinaryWriter w) { - w.Write(bytecode); - } - - /// overriden ToString method - public override string ToString() { - return "UnkownAction"; - } - } + /// + /// object for storing unknown actions + /// + public class UnknownAction : BaseAction { + + private byte[] bytecode; + + /// + /// constructor + /// + /// action code + /// additional bytecode + public UnknownAction(byte code,byte[] bytes) : base((ActionCode)code) + { + bytecode = bytes; + } + + /// + public override int ByteCount { + get { + return bytecode.Length; + } + } + + /// + public override void Compile(BinaryWriter w) { + w.Write(bytecode); + } + + /// overriden ToString method + public override string ToString() { + return "UnkownAction"; + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Compiler.cs b/External/Tools/SwfOp/ByteCode/Compiler.cs index 12519c0907..ce2651c9d1 100644 --- a/External/Tools/SwfOp/ByteCode/Compiler.cs +++ b/External/Tools/SwfOp/ByteCode/Compiler.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -26,215 +26,215 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode { - /// - /// Compiler class, exposes one public method: . - /// - public class Compiler { - - /// - /// Collaps sequence of single push actions into one multiple-push action - /// - private void CollapsPushActions(ArrayList actionRecord) { + /// + /// Compiler class, exposes one public method: . + /// + public class Compiler { + + /// + /// Collaps sequence of single push actions into one multiple-push action + /// + private void CollapsPushActions(ArrayList actionRecord) { - int i = 0; - bool isPush; - - while (i<(actionRecord.Count-1)) { - - isPush = actionRecord[i] is ActionPush; - if (isPush) { - - int j = i; - int count = 1; - - do { - i++; - if (i1) { - ActionPush[] pushList = new ActionPush[count]; - actionRecord.CopyTo(j,pushList,0,count); - - actionRecord.RemoveRange(j,count); - ActionPushList pl = new ActionPushList(pushList); - actionRecord.Insert(j,pl); - - i=j+1; - } - - - } else { - - // recursively step through functions inner actions - ActionDefineFunction f = actionRecord[i] as ActionDefineFunction; - if (f!=null) CollapsPushActions(f.ActionRecord); - - // and function2 of course - ActionDefineFunction2 f2 = actionRecord[i] as ActionDefineFunction2; - if (f2!=null) CollapsPushActions(f2.ActionRecord); - i++; - } - } + int i = 0; + bool isPush; + + while (i<(actionRecord.Count-1)) { + + isPush = actionRecord[i] is ActionPush; + if (isPush) { + + int j = i; + int count = 1; + + do { + i++; + if (i1) { + ActionPush[] pushList = new ActionPush[count]; + actionRecord.CopyTo(j,pushList,0,count); + + actionRecord.RemoveRange(j,count); + ActionPushList pl = new ActionPushList(pushList); + actionRecord.Insert(j,pl); + + i=j+1; + } + + + } else { + + // recursively step through functions inner actions + ActionDefineFunction f = actionRecord[i] as ActionDefineFunction; + if (f!=null) CollapsPushActions(f.ActionRecord); + + // and function2 of course + ActionDefineFunction2 f2 = actionRecord[i] as ActionDefineFunction2; + if (f2!=null) CollapsPushActions(f2.ActionRecord); + i++; + } + } - } - - /// - /// Inner struct for storing branch data. - /// - struct JumpPos { + } + + /// + /// Inner struct for storing branch data. + /// + struct JumpPos { - public readonly int Position; - public readonly IJump Jump; - - public JumpPos(int pos,IJump j) { - Position = pos; - Jump = j; - } - } - - /// - /// Calculate branch offsets. - /// - private void CalcBranchOffsets(ArrayList actionRecord) { - - if (actionRecord.Count<1) return; - - ArrayList jumpList = new ArrayList(); - Hashtable labelPos = new Hashtable(); - - int pos = 0; - for (int i=0; i - /// Calculate size or offset for action blocks. - /// - private void CalcBlockOffsets(ArrayList actionRecord) { - - if (actionRecord.Count<1) return; - - for (int i=0; i=0)||(ca.Code==(int)ActionCode.PushList)) count++; - } while ( (ca as ActionEndWait) == null); - aWait.SkipCount = count; - } - - // action waitForFrame2 - ActionWaitForFrame2 aWait2 = a as ActionWaitForFrame2; - if (aWait2!=null) { + public readonly int Position; + public readonly IJump Jump; + + public JumpPos(int pos,IJump j) { + Position = pos; + Jump = j; + } + } + + /// + /// Calculate branch offsets. + /// + private void CalcBranchOffsets(ArrayList actionRecord) { + + if (actionRecord.Count<1) return; + + ArrayList jumpList = new ArrayList(); + Hashtable labelPos = new Hashtable(); + + int pos = 0; + for (int i=0; i + /// Calculate size or offset for action blocks. + /// + private void CalcBlockOffsets(ArrayList actionRecord) { + + if (actionRecord.Count<1) return; + + for (int i=0; i=0)||(ca.Code==(int)ActionCode.PushList)) count++; + } while ( (ca as ActionEndWait) == null); + aWait.SkipCount = count; + } + + // action waitForFrame2 + ActionWaitForFrame2 aWait2 = a as ActionWaitForFrame2; + if (aWait2!=null) { - int j=i; - int count = 0; - BaseAction ca; - do { - j++; - ca = (BaseAction)actionRecord[j]; - if ((ca.Code>=0)||(ca.Code==(int)ActionCode.PushList)) count++; - } while ( (ca as ActionEndWait) == null); - aWait2.SkipCount = count; - } - - // action function - ActionDefineFunction f = actionRecord[i] as ActionDefineFunction; - if (f!=null) CalcBlockOffsets(f.ActionRecord); - - // action function2 - ActionDefineFunction2 f2 = actionRecord[i] as ActionDefineFunction2; - if (f2!=null) CalcBlockOffsets(f2.ActionRecord); - } - - } - - /// - /// Compile list of Action objects to byte code. - /// - /// List of action objects - public byte[] Compile(ArrayList actionRecord) { - - // code blocks - CollapsPushActions(actionRecord); - CalcBranchOffsets(actionRecord); - CalcBlockOffsets(actionRecord); - - // compile action-by-action - foreach (object o in actionRecord) { - BaseAction action = (BaseAction) o; - action.Compile(binWriter); - } + int j=i; + int count = 0; + BaseAction ca; + do { + j++; + ca = (BaseAction)actionRecord[j]; + if ((ca.Code>=0)||(ca.Code==(int)ActionCode.PushList)) count++; + } while ( (ca as ActionEndWait) == null); + aWait2.SkipCount = count; + } + + // action function + ActionDefineFunction f = actionRecord[i] as ActionDefineFunction; + if (f!=null) CalcBlockOffsets(f.ActionRecord); + + // action function2 + ActionDefineFunction2 f2 = actionRecord[i] as ActionDefineFunction2; + if (f2!=null) CalcBlockOffsets(f2.ActionRecord); + } + + } + + /// + /// Compile list of Action objects to byte code. + /// + /// List of action objects + public byte[] Compile(ArrayList actionRecord) { + + // code blocks + CollapsPushActions(actionRecord); + CalcBranchOffsets(actionRecord); + CalcBlockOffsets(actionRecord); + + // compile action-by-action + foreach (object o in actionRecord) { + BaseAction action = (BaseAction) o; + action.Compile(binWriter); + } - return memStream.ToArray(); - } - - // writer - private BinaryWriter binWriter; - private MemoryStream memStream; - - /// - /// Constructor. - /// - public Compiler() { - memStream = new MemoryStream(); - binWriter = new BinaryWriter(memStream,System.Text.Encoding.Default); - } - } + return memStream.ToArray(); + } + + // writer + private BinaryWriter binWriter; + private MemoryStream memStream; + + /// + /// Constructor. + /// + public Compiler() { + memStream = new MemoryStream(); + binWriter = new BinaryWriter(memStream,System.Text.Encoding.Default); + } + } } diff --git a/External/Tools/SwfOp/ByteCode/Decompiler.cs b/External/Tools/SwfOp/ByteCode/Decompiler.cs index e6f80815cc..9b44f8b590 100644 --- a/External/Tools/SwfOp/ByteCode/Decompiler.cs +++ b/External/Tools/SwfOp/ByteCode/Decompiler.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -28,849 +28,849 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.ByteCode { - /// - /// Decompiler class. Compiles swf byte code to list of action objects. - /// - public class Decompiler { - - /// - /// Read if action from swf. - /// - private ActionIf ReadActionIf(BinaryReader br) { + /// + /// Decompiler class. Compiles swf byte code to list of action objects. + /// + public class Decompiler { + + /// + /// Read if action from swf. + /// + private ActionIf ReadActionIf(BinaryReader br) { - int len = Convert.ToInt32(br.ReadInt16()); - Int16 o = br.ReadInt16(); - ActionIf a = new ActionIf( 0 ); - a.Offset = Convert.ToInt32(o); - //a.ByteSize = len+3; - return a; - } - - /// - /// Read jump action from swf. - /// - private ActionJump ReadActionJump(BinaryReader br) { + int len = Convert.ToInt32(br.ReadInt16()); + Int16 o = br.ReadInt16(); + ActionIf a = new ActionIf( 0 ); + a.Offset = Convert.ToInt32(o); + //a.ByteSize = len+3; + return a; + } + + /// + /// Read jump action from swf. + /// + private ActionJump ReadActionJump(BinaryReader br) { - int len = Convert.ToInt32(br.ReadInt16()); - Int16 o = br.ReadInt16(); - ActionJump a = new ActionJump( 0 ); - a.Offset = Convert.ToInt32(o); - //a.ByteSize = len+3; - return a; - } - - /// - /// Read constant pool action from swf. the constant pool is not parsed. - /// - private ActionConstantPool ReadActionConstantPool(BinaryReader br) { - - // read block length - int len = Convert.ToInt32(br.ReadUInt16()); - - int constCount = Convert.ToInt32(br.ReadUInt16()); - string[] constantPool = new string[constCount]; - - for (int i=0; i - /// Read store register action from swf. - /// - private ActionStoreRegister ReadActionStoreRegister(BinaryReader br) { - int len = Convert.ToInt32(br.ReadUInt16()); - ActionStoreRegister a = new ActionStoreRegister( br.ReadByte()); - //a.ByteSize = len+3; - return a; - } - - /// - /// Read multiply push action action as ActionPushList from swf. - /// - private ActionPushList ReadActionPush(BinaryReader br) { - - // read block length - int len = Convert.ToInt32(br.ReadUInt16()); - int i = 0; - ArrayList pushList = new ArrayList(); - - while (i - /// Read ActionDefineFunction from swf. - /// including inner actions - /// - private ActionDefineFunction ReadActionDefineFunction(BinaryReader br) { - - int start = Convert.ToInt32(br.BaseStream.Position); - - // read block length - int len = Convert.ToInt32(br.ReadUInt16()); - - string name = BinaryStringRW.ReadString(br); - int numParams = Convert.ToInt32(br.ReadUInt16()); - string[] parameterList = new string[numParams]; - for (int i=0; i - /// Read ActionDefineFunction2 from swf. - /// including inner actions - /// - private ActionDefineFunction2 ReadActionDefineFunction2(BinaryReader br) { - - int start = Convert.ToInt32(br.BaseStream.Position); - // read block length - int len = Convert.ToInt32(br.ReadUInt16()); - - string name = BinaryStringRW.ReadString(br); - int numParams = Convert.ToInt32(br.ReadUInt16()); - int numRegs = Convert.ToInt32(br.ReadByte()); - byte flags1 = br.ReadByte(); - byte flags2 = br.ReadByte(); - - ActionDefineFunction2.VariableFlagSet f - = new ActionDefineFunction2.VariableFlagSet( - (flags1 & 0x80) == 0x80, - (flags1 & 0x40) == 0x40, - (flags1 & 0x20) == 0x20, - (flags1 & 0x10) == 0x10, - (flags1 & 0x08) == 0x08, - (flags1 & 0x04) == 0x04, - (flags1 & 0x02) == 0x02, - (flags1 & 0x01) == 0x01, - (flags2 & 0x01) == 0x01 - ); - - // read parameters - ActionDefineFunction2.RegParamPair[] paramList = new ActionDefineFunction2.RegParamPair[numParams]; - - for (int i=0; i - /// Read ActionSetTarget from swf. - /// - private ActionSetTarget ReadActionSetTarget(BinaryReader br) { - - int len = Convert.ToInt32(br.ReadUInt16()); - - ActionSetTarget a = new ActionSetTarget(BinaryStringRW.ReadString(br)); - //a.ByteSize = len+3; - - return a; - } - - /// - /// Read ActionGotoFrame from swf. - /// - private ActionGotoFrame ReadActionGotoFrame(BinaryReader br) { - - int len = Convert.ToInt32(br.ReadUInt16()); - short f = br.ReadInt16(); - - ActionGotoFrame a = new ActionGotoFrame(f); - //a.ByteSize = len+3; - - return a; - } - - /// - /// Read ActionGotoFrame2 from swf. - /// - private ActionGotoFrame2 ReadActionGotoFrame2(BinaryReader br) { - - int len = Convert.ToInt32(br.ReadUInt16()); - - byte[] b = br.ReadBytes(len); - - ActionGotoFrame2 a = new ActionGotoFrame2(b); - //a.ByteSize = len+3; - - return a; - } - - /// - /// Read ActionGotoLabel from swf. - /// - private ActionGotoLabel ReadActionGotoLabel(BinaryReader br) { - - int len = Convert.ToInt32(br.ReadUInt16()); - string label = BinaryStringRW.ReadString(br); - - ActionGotoLabel a = new ActionGotoLabel(label); - //a.ByteSize = len+3; - - return a; - } - - - /// - /// Read ActionGetUrl from swf. - /// - private ActionGetUrl ReadActionGetUrl(BinaryReader br) { - - int len = Convert.ToInt32(br.ReadUInt16()); - - string urlStr = BinaryStringRW.ReadString(br); - string targetStr = BinaryStringRW.ReadString(br); - - ActionGetUrl a = new ActionGetUrl(urlStr,targetStr); - //a.ByteSize = len+3; - - return a; - } - - /// - /// Read ActionGetUrl2 from swf. - /// - private ActionGetUrl2 ReadActionGetUrl2(BinaryReader br) { - - int len = Convert.ToInt32(br.ReadUInt16()); - ActionGetUrl2 a = new ActionGetUrl2(br.ReadByte()); - //a.ByteSize = len+3; - - return a; - } - - - /// - /// Read ActionWaitForFrame from swf. - /// - private ActionWaitForFrame ReadActionWaitForFrame(BinaryReader br) { - - int len = Convert.ToInt32(br.ReadUInt16()); - short frame = br.ReadInt16(); - byte skip = br.ReadByte(); - - ActionWaitForFrame a = new ActionWaitForFrame(frame,skip); - //a.ByteSize = len+3; - - return a; - } - - /// - /// Read ActionWaitForFrame2 from swf. - /// - private ActionWaitForFrame2 ReadActionWaitForFrame2(BinaryReader br) { + int len = Convert.ToInt32(br.ReadInt16()); + Int16 o = br.ReadInt16(); + ActionJump a = new ActionJump( 0 ); + a.Offset = Convert.ToInt32(o); + //a.ByteSize = len+3; + return a; + } + + /// + /// Read constant pool action from swf. the constant pool is not parsed. + /// + private ActionConstantPool ReadActionConstantPool(BinaryReader br) { + + // read block length + int len = Convert.ToInt32(br.ReadUInt16()); + + int constCount = Convert.ToInt32(br.ReadUInt16()); + string[] constantPool = new string[constCount]; + + for (int i=0; i + /// Read store register action from swf. + /// + private ActionStoreRegister ReadActionStoreRegister(BinaryReader br) { + int len = Convert.ToInt32(br.ReadUInt16()); + ActionStoreRegister a = new ActionStoreRegister( br.ReadByte()); + //a.ByteSize = len+3; + return a; + } + + /// + /// Read multiply push action action as ActionPushList from swf. + /// + private ActionPushList ReadActionPush(BinaryReader br) { + + // read block length + int len = Convert.ToInt32(br.ReadUInt16()); + int i = 0; + ArrayList pushList = new ArrayList(); + + while (i + /// Read ActionDefineFunction from swf. + /// including inner actions + /// + private ActionDefineFunction ReadActionDefineFunction(BinaryReader br) { + + int start = Convert.ToInt32(br.BaseStream.Position); + + // read block length + int len = Convert.ToInt32(br.ReadUInt16()); + + string name = BinaryStringRW.ReadString(br); + int numParams = Convert.ToInt32(br.ReadUInt16()); + string[] parameterList = new string[numParams]; + for (int i=0; i + /// Read ActionDefineFunction2 from swf. + /// including inner actions + /// + private ActionDefineFunction2 ReadActionDefineFunction2(BinaryReader br) { + + int start = Convert.ToInt32(br.BaseStream.Position); + // read block length + int len = Convert.ToInt32(br.ReadUInt16()); + + string name = BinaryStringRW.ReadString(br); + int numParams = Convert.ToInt32(br.ReadUInt16()); + int numRegs = Convert.ToInt32(br.ReadByte()); + byte flags1 = br.ReadByte(); + byte flags2 = br.ReadByte(); + + ActionDefineFunction2.VariableFlagSet f + = new ActionDefineFunction2.VariableFlagSet( + (flags1 & 0x80) == 0x80, + (flags1 & 0x40) == 0x40, + (flags1 & 0x20) == 0x20, + (flags1 & 0x10) == 0x10, + (flags1 & 0x08) == 0x08, + (flags1 & 0x04) == 0x04, + (flags1 & 0x02) == 0x02, + (flags1 & 0x01) == 0x01, + (flags2 & 0x01) == 0x01 + ); + + // read parameters + ActionDefineFunction2.RegParamPair[] paramList = new ActionDefineFunction2.RegParamPair[numParams]; + + for (int i=0; i + /// Read ActionSetTarget from swf. + /// + private ActionSetTarget ReadActionSetTarget(BinaryReader br) { + + int len = Convert.ToInt32(br.ReadUInt16()); + + ActionSetTarget a = new ActionSetTarget(BinaryStringRW.ReadString(br)); + //a.ByteSize = len+3; + + return a; + } + + /// + /// Read ActionGotoFrame from swf. + /// + private ActionGotoFrame ReadActionGotoFrame(BinaryReader br) { + + int len = Convert.ToInt32(br.ReadUInt16()); + short f = br.ReadInt16(); + + ActionGotoFrame a = new ActionGotoFrame(f); + //a.ByteSize = len+3; + + return a; + } + + /// + /// Read ActionGotoFrame2 from swf. + /// + private ActionGotoFrame2 ReadActionGotoFrame2(BinaryReader br) { + + int len = Convert.ToInt32(br.ReadUInt16()); + + byte[] b = br.ReadBytes(len); + + ActionGotoFrame2 a = new ActionGotoFrame2(b); + //a.ByteSize = len+3; + + return a; + } + + /// + /// Read ActionGotoLabel from swf. + /// + private ActionGotoLabel ReadActionGotoLabel(BinaryReader br) { + + int len = Convert.ToInt32(br.ReadUInt16()); + string label = BinaryStringRW.ReadString(br); + + ActionGotoLabel a = new ActionGotoLabel(label); + //a.ByteSize = len+3; + + return a; + } + + + /// + /// Read ActionGetUrl from swf. + /// + private ActionGetUrl ReadActionGetUrl(BinaryReader br) { + + int len = Convert.ToInt32(br.ReadUInt16()); + + string urlStr = BinaryStringRW.ReadString(br); + string targetStr = BinaryStringRW.ReadString(br); + + ActionGetUrl a = new ActionGetUrl(urlStr,targetStr); + //a.ByteSize = len+3; + + return a; + } + + /// + /// Read ActionGetUrl2 from swf. + /// + private ActionGetUrl2 ReadActionGetUrl2(BinaryReader br) { + + int len = Convert.ToInt32(br.ReadUInt16()); + ActionGetUrl2 a = new ActionGetUrl2(br.ReadByte()); + //a.ByteSize = len+3; + + return a; + } + + + /// + /// Read ActionWaitForFrame from swf. + /// + private ActionWaitForFrame ReadActionWaitForFrame(BinaryReader br) { + + int len = Convert.ToInt32(br.ReadUInt16()); + short frame = br.ReadInt16(); + byte skip = br.ReadByte(); + + ActionWaitForFrame a = new ActionWaitForFrame(frame,skip); + //a.ByteSize = len+3; + + return a; + } + + /// + /// Read ActionWaitForFrame2 from swf. + /// + private ActionWaitForFrame2 ReadActionWaitForFrame2(BinaryReader br) { - int len = Convert.ToInt32(br.ReadUInt16()); - byte skip = br.ReadByte(); + int len = Convert.ToInt32(br.ReadUInt16()); + byte skip = br.ReadByte(); - ActionWaitForFrame2 a = new ActionWaitForFrame2(skip); - //a.ByteSize = len+3; - - return a; - } - - - /// - /// Read ActionWith from swf. - /// - private ActionWith ReadActionWith(BinaryReader br) { - - int len = Convert.ToInt32(br.ReadUInt16()); - ushort block = br.ReadUInt16(); - - ActionWith a = new ActionWith(block); - //a.ByteSize = len+3; - - return a; - } - - - /// - /// Read try/catch block from swf and create corresponding - /// ActionTry, - /// ActionCatch, - /// ActionFinally, - /// ActionEndTryBlock - /// actions. - /// - private ActionTry ReadActionTry(BinaryReader br) { - - br.ReadUInt16(); - - long startStream = br.BaseStream.Position; - - byte flags = br.ReadByte(); - - bool catchInRegister = ((flags & 0x04) == 0x04); - bool finallyFlag = ((flags & 0x02) == 0x02); - bool catchFlag = ((flags & 0x01) == 0x01); - - ushort trySize = br.ReadUInt16(); - ushort catchSize = br.ReadUInt16(); - ushort finallySize = br.ReadUInt16(); - - string catchName = ""; - byte catchRegister = 0; - - if (catchInRegister) { - catchRegister = br.ReadByte(); - } else { - catchName = BinaryStringRW.ReadString(br); - } - - int len = Convert.ToInt32(br.BaseStream.Position-startStream); - - ActionTry a = new ActionTry(catchInRegister,finallyFlag,catchFlag, - trySize,catchSize,finallySize, - catchName,catchRegister); - - //a.ByteSize = len+3; - - return a; - } - + ActionWaitForFrame2 a = new ActionWaitForFrame2(skip); + //a.ByteSize = len+3; + + return a; + } + + + /// + /// Read ActionWith from swf. + /// + private ActionWith ReadActionWith(BinaryReader br) { + + int len = Convert.ToInt32(br.ReadUInt16()); + ushort block = br.ReadUInt16(); + + ActionWith a = new ActionWith(block); + //a.ByteSize = len+3; + + return a; + } + + + /// + /// Read try/catch block from swf and create corresponding + /// ActionTry, + /// ActionCatch, + /// ActionFinally, + /// ActionEndTryBlock + /// actions. + /// + private ActionTry ReadActionTry(BinaryReader br) { + + br.ReadUInt16(); + + long startStream = br.BaseStream.Position; + + byte flags = br.ReadByte(); + + bool catchInRegister = ((flags & 0x04) == 0x04); + bool finallyFlag = ((flags & 0x02) == 0x02); + bool catchFlag = ((flags & 0x01) == 0x01); + + ushort trySize = br.ReadUInt16(); + ushort catchSize = br.ReadUInt16(); + ushort finallySize = br.ReadUInt16(); + + string catchName = ""; + byte catchRegister = 0; + + if (catchInRegister) { + catchRegister = br.ReadByte(); + } else { + catchName = BinaryStringRW.ReadString(br); + } + + int len = Convert.ToInt32(br.BaseStream.Position-startStream); + + ActionTry a = new ActionTry(catchInRegister,finallyFlag,catchFlag, + trySize,catchSize,finallySize, + catchName,catchRegister); + + //a.ByteSize = len+3; + + return a; + } + - /// - /// Read unknown instruction as UnknownAction object - /// - private UnknownAction ReadUnknownAction(byte code,BinaryReader br) { - - byte[] bytecode; - - if (code<0x80) { - bytecode = new byte[1] {code}; - } else { - int len = Convert.ToInt32(br.ReadUInt16()); - br.BaseStream.Position-=3; - bytecode = br.ReadBytes(len+3); - } - - UnknownAction u = new UnknownAction(code,bytecode); - //u.ByteSize = bytecode.Length; - - return u; - } - - /// - /// Read actions according to action code in swf - /// - private BaseAction ReadAction(BinaryReader br) { - - byte bytecode = br.ReadByte(); - - switch ( (ActionCode) Convert.ToInt32(bytecode) ) { - - // singlebyte actions - case ActionCode.End: return new ActionEnd(); - case ActionCode.NextFrame: return new ActionNextFrame(); - case ActionCode.PreviousFrame: return new ActionPreviousFrame(); - case ActionCode.Play: return new ActionPlay(); - case ActionCode.Stop: return new ActionStop(); - case ActionCode.ToggleQuality: return new ActionToggleQuality(); - case ActionCode.StopSounds: return new ActionStopSounds(); - case ActionCode.Pop: return new ActionPop(); - case ActionCode.Add: return new ActionAdd(); - case ActionCode.Subtract: return new ActionSubtract(); - case ActionCode.Multiply: return new ActionMultiply(); - case ActionCode.Divide: return new ActionDivide(); - case ActionCode.Equals: return new ActionEquals(); - case ActionCode.Less: return new ActionLess(); - case ActionCode.And: return new ActionAnd(); - case ActionCode.Or: return new ActionOr(); - case ActionCode.Not: return new ActionNot(); - case ActionCode.StringAdd: return new ActionStringAdd(); - case ActionCode.StringEquals: return new ActionStringEquals(); - case ActionCode.StringExtract: return new ActionStringExtract(); - case ActionCode.StringLength: return new ActionStringLength(); - case ActionCode.StringLess: return new ActionStringLess(); - case ActionCode.MBStringExtract: return new ActionMBStringExtract(); - case ActionCode.MBStringLength: return new ActionMBStringLength(); - case ActionCode.AsciiToChar: return new ActionAsciiToChar(); - case ActionCode.CharToAscii: return new ActionCharToAscii(); - case ActionCode.ToInteger: return new ActionToInteger(); - case ActionCode.MBAsciiToChar: return new ActionMBAsciiToChar(); - case ActionCode.MBCharToAscii: return new ActionMBCharToAscii(); - case ActionCode.Call: return new ActionCall(); - case ActionCode.GetVariable: return new ActionGetVariable(); - case ActionCode.SetVariable: return new ActionSetVariable(); - case ActionCode.GetProperty: return new ActionGetProperty(); - case ActionCode.RemoveSprite: return new ActionRemoveSprite(); - case ActionCode.SetProperty: return new ActionSetProperty(); - case ActionCode.SetTarget2: return new ActionSetTarget2(); - case ActionCode.StartDrag: return new ActionStartDrag(); - case ActionCode.CloneSprite: return new ActionCloneSprite(); - case ActionCode.EndDrag: return new ActionEndDrag(); - case ActionCode.GetTime: return new ActionGetTime(); - case ActionCode.RandomNumber: return new ActionRandomNumber(); - case ActionCode.Trace: return new ActionTrace(); - case ActionCode.CallFunction: return new ActionCallFunction(); - case ActionCode.CallMethod: return new ActionCallMethod(); - case ActionCode.DefineLocal: return new ActionDefineLocal(); - case ActionCode.DefineLocal2: return new ActionDefineLocal2(); - case ActionCode.Delete: return new ActionDelete(); - case ActionCode.Delete2: return new ActionDelete2(); - case ActionCode.Enumerate: return new ActionEnumerate(); - case ActionCode.Equals2: return new ActionEquals2(); - case ActionCode.GetMember: return new ActionGetMember(); - case ActionCode.InitArray: return new ActionInitArray(); - case ActionCode.InitObject: return new ActionInitObject(); - case ActionCode.NewMethod: return new ActionNewMethod(); - case ActionCode.NewObject: return new ActionNewObject(); - case ActionCode.SetMember: return new ActionSetMember(); - case ActionCode.TargetPath: return new ActionTargetPath(); - case ActionCode.ToNumber: return new ActionToNumber(); - case ActionCode.ToString: return new ActionToString(); - case ActionCode.TypeOf: return new ActionTypeOf(); - case ActionCode.Add2: return new ActionAdd2(); - case ActionCode.Less2: return new ActionLess2(); - case ActionCode.Modulo: return new ActionModulo(); - case ActionCode.BitAnd: return new ActionBitAnd(); - case ActionCode.BitLShift: return new ActionBitLShift(); - case ActionCode.BitOr: return new ActionBitOr(); - case ActionCode.BitRShift: return new ActionBitRShift(); - case ActionCode.BitURShift: return new ActionBitURShift(); - case ActionCode.BitXor: return new ActionBitXor(); - case ActionCode.Decrement: return new ActionDecrement(); - case ActionCode.Increment: return new ActionIncrement(); - case ActionCode.PushDuplicate: return new ActionPushDuplicate(); - case ActionCode.Return: return new ActionReturn(); - case ActionCode.StackSwap: return new ActionStackSwap(); - case ActionCode.InstanceOf: return new ActionInstanceOf(); - case ActionCode.Enumerate2: return new ActionEnumerate2(); - case ActionCode.StrictEquals: return new ActionStrictEquals(); - case ActionCode.Greater: return new ActionGreater(); - case ActionCode.StringGreater: return new ActionStringGreater(); - case ActionCode.Extends: return new ActionExtends(); - case ActionCode.CastOp: return new ActionCastOp(); - case ActionCode.Implements: return new ActionImplements(); - case ActionCode.Throw: return new ActionThrow(); - - // multibyte actions - case ActionCode.ConstantPool: return ReadActionConstantPool(br); - case ActionCode.GetURL: return ReadActionGetUrl(br); - case ActionCode.GetURL2: return ReadActionGetUrl2(br); - case ActionCode.WaitForFrame: return ReadActionWaitForFrame(br); - case ActionCode.WaitForFrame2: return ReadActionWaitForFrame2(br); - case ActionCode.GotoFrame: return ReadActionGotoFrame(br); - case ActionCode.GotoFrame2: return ReadActionGotoFrame2(br); - case ActionCode.GoToLabel : return ReadActionGotoLabel(br); - case ActionCode.SetTarget : return ReadActionSetTarget(br); - case ActionCode.With: return ReadActionWith(br); - case ActionCode.Try: return ReadActionTry(br); - case ActionCode.Push: return ReadActionPush(br); - case ActionCode.StoreRegister: return ReadActionStoreRegister(br); - case ActionCode.Jump: return ReadActionJump(br); - case ActionCode.If: return ReadActionIf(br); - case ActionCode.DefineFunction: return ReadActionDefineFunction(br); - case ActionCode.DefineFunction2: return ReadActionDefineFunction2(br); - - } + /// + /// Read unknown instruction as UnknownAction object + /// + private UnknownAction ReadUnknownAction(byte code,BinaryReader br) { + + byte[] bytecode; + + if (code<0x80) { + bytecode = new byte[1] {code}; + } else { + int len = Convert.ToInt32(br.ReadUInt16()); + br.BaseStream.Position-=3; + bytecode = br.ReadBytes(len+3); + } + + UnknownAction u = new UnknownAction(code,bytecode); + //u.ByteSize = bytecode.Length; + + return u; + } + + /// + /// Read actions according to action code in swf + /// + private BaseAction ReadAction(BinaryReader br) { + + byte bytecode = br.ReadByte(); + + switch ( (ActionCode) Convert.ToInt32(bytecode) ) { + + // singlebyte actions + case ActionCode.End: return new ActionEnd(); + case ActionCode.NextFrame: return new ActionNextFrame(); + case ActionCode.PreviousFrame: return new ActionPreviousFrame(); + case ActionCode.Play: return new ActionPlay(); + case ActionCode.Stop: return new ActionStop(); + case ActionCode.ToggleQuality: return new ActionToggleQuality(); + case ActionCode.StopSounds: return new ActionStopSounds(); + case ActionCode.Pop: return new ActionPop(); + case ActionCode.Add: return new ActionAdd(); + case ActionCode.Subtract: return new ActionSubtract(); + case ActionCode.Multiply: return new ActionMultiply(); + case ActionCode.Divide: return new ActionDivide(); + case ActionCode.Equals: return new ActionEquals(); + case ActionCode.Less: return new ActionLess(); + case ActionCode.And: return new ActionAnd(); + case ActionCode.Or: return new ActionOr(); + case ActionCode.Not: return new ActionNot(); + case ActionCode.StringAdd: return new ActionStringAdd(); + case ActionCode.StringEquals: return new ActionStringEquals(); + case ActionCode.StringExtract: return new ActionStringExtract(); + case ActionCode.StringLength: return new ActionStringLength(); + case ActionCode.StringLess: return new ActionStringLess(); + case ActionCode.MBStringExtract: return new ActionMBStringExtract(); + case ActionCode.MBStringLength: return new ActionMBStringLength(); + case ActionCode.AsciiToChar: return new ActionAsciiToChar(); + case ActionCode.CharToAscii: return new ActionCharToAscii(); + case ActionCode.ToInteger: return new ActionToInteger(); + case ActionCode.MBAsciiToChar: return new ActionMBAsciiToChar(); + case ActionCode.MBCharToAscii: return new ActionMBCharToAscii(); + case ActionCode.Call: return new ActionCall(); + case ActionCode.GetVariable: return new ActionGetVariable(); + case ActionCode.SetVariable: return new ActionSetVariable(); + case ActionCode.GetProperty: return new ActionGetProperty(); + case ActionCode.RemoveSprite: return new ActionRemoveSprite(); + case ActionCode.SetProperty: return new ActionSetProperty(); + case ActionCode.SetTarget2: return new ActionSetTarget2(); + case ActionCode.StartDrag: return new ActionStartDrag(); + case ActionCode.CloneSprite: return new ActionCloneSprite(); + case ActionCode.EndDrag: return new ActionEndDrag(); + case ActionCode.GetTime: return new ActionGetTime(); + case ActionCode.RandomNumber: return new ActionRandomNumber(); + case ActionCode.Trace: return new ActionTrace(); + case ActionCode.CallFunction: return new ActionCallFunction(); + case ActionCode.CallMethod: return new ActionCallMethod(); + case ActionCode.DefineLocal: return new ActionDefineLocal(); + case ActionCode.DefineLocal2: return new ActionDefineLocal2(); + case ActionCode.Delete: return new ActionDelete(); + case ActionCode.Delete2: return new ActionDelete2(); + case ActionCode.Enumerate: return new ActionEnumerate(); + case ActionCode.Equals2: return new ActionEquals2(); + case ActionCode.GetMember: return new ActionGetMember(); + case ActionCode.InitArray: return new ActionInitArray(); + case ActionCode.InitObject: return new ActionInitObject(); + case ActionCode.NewMethod: return new ActionNewMethod(); + case ActionCode.NewObject: return new ActionNewObject(); + case ActionCode.SetMember: return new ActionSetMember(); + case ActionCode.TargetPath: return new ActionTargetPath(); + case ActionCode.ToNumber: return new ActionToNumber(); + case ActionCode.ToString: return new ActionToString(); + case ActionCode.TypeOf: return new ActionTypeOf(); + case ActionCode.Add2: return new ActionAdd2(); + case ActionCode.Less2: return new ActionLess2(); + case ActionCode.Modulo: return new ActionModulo(); + case ActionCode.BitAnd: return new ActionBitAnd(); + case ActionCode.BitLShift: return new ActionBitLShift(); + case ActionCode.BitOr: return new ActionBitOr(); + case ActionCode.BitRShift: return new ActionBitRShift(); + case ActionCode.BitURShift: return new ActionBitURShift(); + case ActionCode.BitXor: return new ActionBitXor(); + case ActionCode.Decrement: return new ActionDecrement(); + case ActionCode.Increment: return new ActionIncrement(); + case ActionCode.PushDuplicate: return new ActionPushDuplicate(); + case ActionCode.Return: return new ActionReturn(); + case ActionCode.StackSwap: return new ActionStackSwap(); + case ActionCode.InstanceOf: return new ActionInstanceOf(); + case ActionCode.Enumerate2: return new ActionEnumerate2(); + case ActionCode.StrictEquals: return new ActionStrictEquals(); + case ActionCode.Greater: return new ActionGreater(); + case ActionCode.StringGreater: return new ActionStringGreater(); + case ActionCode.Extends: return new ActionExtends(); + case ActionCode.CastOp: return new ActionCastOp(); + case ActionCode.Implements: return new ActionImplements(); + case ActionCode.Throw: return new ActionThrow(); + + // multibyte actions + case ActionCode.ConstantPool: return ReadActionConstantPool(br); + case ActionCode.GetURL: return ReadActionGetUrl(br); + case ActionCode.GetURL2: return ReadActionGetUrl2(br); + case ActionCode.WaitForFrame: return ReadActionWaitForFrame(br); + case ActionCode.WaitForFrame2: return ReadActionWaitForFrame2(br); + case ActionCode.GotoFrame: return ReadActionGotoFrame(br); + case ActionCode.GotoFrame2: return ReadActionGotoFrame2(br); + case ActionCode.GoToLabel : return ReadActionGotoLabel(br); + case ActionCode.SetTarget : return ReadActionSetTarget(br); + case ActionCode.With: return ReadActionWith(br); + case ActionCode.Try: return ReadActionTry(br); + case ActionCode.Push: return ReadActionPush(br); + case ActionCode.StoreRegister: return ReadActionStoreRegister(br); + case ActionCode.Jump: return ReadActionJump(br); + case ActionCode.If: return ReadActionIf(br); + case ActionCode.DefineFunction: return ReadActionDefineFunction(br); + case ActionCode.DefineFunction2: return ReadActionDefineFunction2(br); + + } - return ReadUnknownAction(bytecode,br); - } - - /// - /// Read bytecode actions from swf - /// - - private ArrayList ReadActions(byte[] codeblock) { - - ArrayList actionsRead = new ArrayList(); - - // create binary reader - MemoryStream stream = new MemoryStream(codeblock,false); - BinaryReader reader = new BinaryReader(stream,System.Text.Encoding.UTF8); - - // read bytecode sequenz - while (reader.PeekChar()!=-1) { - - // read - BaseAction a = ReadAction(reader); - - // define constant pool - actionsRead.Add(a); - } + return ReadUnknownAction(bytecode,br); + } + + /// + /// Read bytecode actions from swf + /// + + private ArrayList ReadActions(byte[] codeblock) { + + ArrayList actionsRead = new ArrayList(); + + // create binary reader + MemoryStream stream = new MemoryStream(codeblock,false); + BinaryReader reader = new BinaryReader(stream,System.Text.Encoding.UTF8); + + // read bytecode sequenz + while (reader.PeekChar()!=-1) { + + // read + BaseAction a = ReadAction(reader); + + // define constant pool + actionsRead.Add(a); + } - CreateBranchLabels(actionsRead); - CreatePseudoActions(actionsRead); - - return actionsRead; - } - - /// - /// convert push list to sequence of single push actions - /// - private void ExplodePushLists(ArrayList actionRecord) { - - for (int i=0; i - /// create ActionLabel pseudo actions for branch labels - /// - private void CreateBranchLabels(ArrayList actionRecord) { - - SortedList labelList = new SortedList(); - - int idx = 0; - while (idx + /// convert push list to sequence of single push actions + /// + private void ExplodePushLists(ArrayList actionRecord) { + + for (int i=0; i + /// create ActionLabel pseudo actions for branch labels + /// + private void CreateBranchLabels(ArrayList actionRecord) { + + SortedList labelList = new SortedList(); + + int idx = 0; + while (idx0 - do { - sidx++; - if (sidx>=actionRecord.Count) break; - - BaseAction ac = (BaseAction) actionRecord[sidx]; - offset-=ac.ByteCount; - - } while (offset>0); - sidx++; - if (!labelList.ContainsKey(sidx)) - { - this.LabelId ++; - labelList[sidx] = this.LabelId; - jump.LabelId = this.LabelId; - } else { - jump.LabelId = (int)labelList[sidx]; - } - - } - } - } + if (offset==0) { + sidx = idx+1; + if (!labelList.ContainsKey(sidx)) + { + this.LabelId ++; + labelList[sidx] = this.LabelId; + jump.LabelId = this.LabelId; + } else { + jump.LabelId = (int)labelList[sidx]; + } + } else { + // offset>0 + do { + sidx++; + if (sidx>=actionRecord.Count) break; + + BaseAction ac = (BaseAction) actionRecord[sidx]; + offset-=ac.ByteCount; + + } while (offset>0); + sidx++; + if (!labelList.ContainsKey(sidx)) + { + this.LabelId ++; + labelList[sidx] = this.LabelId; + jump.LabelId = this.LabelId; + } else { + jump.LabelId = (int)labelList[sidx]; + } + + } + } + } - idx++; - } - - ArrayList lines = new ArrayList(labelList.GetKeyList()); - - foreach (int line in lines) { - int label = (int)labelList[line]; - if (line - /// create other pseudo actions - /// - - private void CreatePseudoActions(ArrayList actionRecord) { - - for (int i=0; i0) { - BaseAction currentAction = (BaseAction)actionRecord[j]; - offset-=currentAction.ByteCount; - j++; - } - // skip catch - if (aTry.SizeCatch>0) { - actionRecord.Insert(j,new ActionCatch() ); - j++; - offset = aTry.SizeCatch; - while (offset>0) { - BaseAction currentAction = (BaseAction)actionRecord[j]; - offset-=currentAction.ByteCount; - j++; - } - } - // skip finally - if (aTry.SizeFinally>0) { - actionRecord.Insert(j,new ActionFinally() ); - j++; - offset = aTry.SizeFinally; - while (offset>0) { - BaseAction currentAction = (BaseAction)actionRecord[j]; - offset-=currentAction.ByteCount; - j++; - } - } - // end - actionRecord.Insert(j,new ActionEndTryBlock() ); - } - - // ----------------------- - // with - // ----------------------- - - ActionWith aWith = a as ActionWith; - - if (aWith!=null) { - int j=i+1; - int offset = aWith.BlockLength; - while (offset>0) { - BaseAction currentAction = (BaseAction)actionRecord[j]; - offset-=currentAction.ByteCount; - j++; - } - actionRecord.Insert(j,new ActionEndWith()); - } - - // ----------------------- - // wait for frame - // ----------------------- - - ActionWaitForFrame aWait = a as ActionWaitForFrame; - if (aWait!=null) { - int j=i+1; - int count = aWait.SkipCount; - while (count>0) { - if (((int)((BaseAction)actionRecord[j]).Code >= 0x00) - ||(((BaseAction)actionRecord[j]).Code==(int)ActionCode.PushList)) { - count--; - } - j++; - } - actionRecord.Insert(j,new ActionEndWait()); - } - ActionWaitForFrame2 aWait2 = a as ActionWaitForFrame2; - if (aWait2!=null) { - int j=i+1; - int count = aWait2.SkipCount; - while (count>0) { - if (((int)((BaseAction)actionRecord[j]).Code >= 0x00) - ||(((BaseAction)actionRecord[j]).Code==(int)ActionCode.PushList)) { - count--; - } - j++; - } - actionRecord.Insert(j,new ActionEndWait()); - } - } - } + idx++; + } + + ArrayList lines = new ArrayList(labelList.GetKeyList()); + + foreach (int line in lines) { + int label = (int)labelList[line]; + if (line + /// create other pseudo actions + /// + + private void CreatePseudoActions(ArrayList actionRecord) { + + for (int i=0; i0) { + BaseAction currentAction = (BaseAction)actionRecord[j]; + offset-=currentAction.ByteCount; + j++; + } + // skip catch + if (aTry.SizeCatch>0) { + actionRecord.Insert(j,new ActionCatch() ); + j++; + offset = aTry.SizeCatch; + while (offset>0) { + BaseAction currentAction = (BaseAction)actionRecord[j]; + offset-=currentAction.ByteCount; + j++; + } + } + // skip finally + if (aTry.SizeFinally>0) { + actionRecord.Insert(j,new ActionFinally() ); + j++; + offset = aTry.SizeFinally; + while (offset>0) { + BaseAction currentAction = (BaseAction)actionRecord[j]; + offset-=currentAction.ByteCount; + j++; + } + } + // end + actionRecord.Insert(j,new ActionEndTryBlock() ); + } + + // ----------------------- + // with + // ----------------------- + + ActionWith aWith = a as ActionWith; + + if (aWith!=null) { + int j=i+1; + int offset = aWith.BlockLength; + while (offset>0) { + BaseAction currentAction = (BaseAction)actionRecord[j]; + offset-=currentAction.ByteCount; + j++; + } + actionRecord.Insert(j,new ActionEndWith()); + } + + // ----------------------- + // wait for frame + // ----------------------- + + ActionWaitForFrame aWait = a as ActionWaitForFrame; + if (aWait!=null) { + int j=i+1; + int count = aWait.SkipCount; + while (count>0) { + if (((int)((BaseAction)actionRecord[j]).Code >= 0x00) + ||(((BaseAction)actionRecord[j]).Code==(int)ActionCode.PushList)) { + count--; + } + j++; + } + actionRecord.Insert(j,new ActionEndWait()); + } + ActionWaitForFrame2 aWait2 = a as ActionWaitForFrame2; + if (aWait2!=null) { + int j=i+1; + int count = aWait2.SkipCount; + while (count>0) { + if (((int)((BaseAction)actionRecord[j]).Code >= 0x00) + ||(((BaseAction)actionRecord[j]).Code==(int)ActionCode.PushList)) { + count--; + } + j++; + } + actionRecord.Insert(j,new ActionEndWait()); + } + } + } - private int LabelId; - - /// - /// decompile byte code to action objects - /// - public ArrayList Decompile(byte[] codeblock) { - - LabelId = 1; - ArrayList actionRec = ReadActions(codeblock); - ExplodePushLists(actionRec); - - // find argument count on stack - // e.g. for actions likecallFunction or initArray - CodeTraverser trav = new CodeTraverser(actionRec); - trav.Traverse(new InvocationExaminer()); - - return actionRec; - } - - // swf version info - private int version; - - /// - /// constructor. - /// - /// swf Version - public Decompiler(int version) { - this.version = version; - } - } + private int LabelId; + + /// + /// decompile byte code to action objects + /// + public ArrayList Decompile(byte[] codeblock) { + + LabelId = 1; + ArrayList actionRec = ReadActions(codeblock); + ExplodePushLists(actionRec); + + // find argument count on stack + // e.g. for actions likecallFunction or initArray + CodeTraverser trav = new CodeTraverser(actionRec); + trav.Traverse(new InvocationExaminer()); + + return actionRec; + } + + // swf version info + private int version; + + /// + /// constructor. + /// + /// swf Version + public Decompiler(int version) { + this.version = version; + } + } } diff --git a/External/Tools/SwfOp/CodeFlow/CodeTraverser.cs b/External/Tools/SwfOp/CodeFlow/CodeTraverser.cs index 2354ab00f2..ff9c0c8755 100644 --- a/External/Tools/SwfOp/CodeFlow/CodeTraverser.cs +++ b/External/Tools/SwfOp/CodeFlow/CodeTraverser.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -24,92 +24,92 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.ByteCode.Actions; namespace SwfOp.CodeFlow -{ - /// - /// The CodeTraverser provides a simple functionality for traversing Action lists - /// by stepping through action lists and following branches. In opposite to - /// each index is only visited once. Action objects are handled by the IActionExaminer - /// that is passed to the Traverse method. - /// CodeTraverser provides a unified base functionality for code-flow analysis. - /// - public class CodeTraverser { - - /// - /// ArrayList of action objects derived from . - /// - protected ArrayList actionRec; - private ArrayList visitedLabels; - private SortedList labelIndexTable; - - private void traverse(int index,IActionExaminer examiner) { - - while (index - /// Start traversing. - /// - /// IActionExaminer object - public virtual void Traverse(IActionExaminer examiner) { - - visitedLabels = new ArrayList(); - traverse(0,examiner); - } - - /// - /// Constructor - /// - /// ArrayList of action objects derived from BaseAction. - public CodeTraverser(ArrayList actions) { - - actionRec = actions; - labelIndexTable= new SortedList(); - - // fill labelIndexTable - for (int i=0; i + /// The CodeTraverser provides a simple functionality for traversing Action lists + /// by stepping through action lists and following branches. In opposite to + /// each index is only visited once. Action objects are handled by the IActionExaminer + /// that is passed to the Traverse method. + /// CodeTraverser provides a unified base functionality for code-flow analysis. + /// + public class CodeTraverser { + + /// + /// ArrayList of action objects derived from . + /// + protected ArrayList actionRec; + private ArrayList visitedLabels; + private SortedList labelIndexTable; + + private void traverse(int index,IActionExaminer examiner) { + + while (index + /// Start traversing. + /// + /// IActionExaminer object + public virtual void Traverse(IActionExaminer examiner) { + + visitedLabels = new ArrayList(); + traverse(0,examiner); + } + + /// + /// Constructor + /// + /// ArrayList of action objects derived from BaseAction. + public CodeTraverser(ArrayList actions) { + + actionRec = actions; + labelIndexTable= new SortedList(); + + // fill labelIndexTable + for (int i=0; i - /// The CodeWalker provides a simple functionality for traversing Action lists - /// by stepping through code and following branches. In opposite to - /// it doesn´t stop until a label is reached that has been visited before or a return - /// statement is found. Action objects are handled by the IActionExaminerer that is passed to - /// the Traverse method. - /// CodeWalker provide a base functionality for code analysis and simulation. - /// - public class CodeWalker { - - private ArrayList actionRec; - private SortedList labelIndexTable; - - private void Walk(int index,IActionExaminer examiner,ArrayList visitedLabels) { - - while (index - /// Start traversing at given index. - /// - /// IActionExaminer object - /// start index for code traversation. - public void Walk(IActionExaminer examiner,int index) { - - ArrayList visitedLabels = new ArrayList(); - Walk(index,examiner,visitedLabels); - } - - /// - /// Start traversing code flow at index 0. - /// - /// IActionExaminer object - public void Walk(IActionExaminer examiner) { - - ArrayList visitedLabels = new ArrayList(); - Walk(0,examiner,visitedLabels); - } - - /// - /// Constructor. - /// - /// ArrayList of BaseAction objects. - public CodeWalker (ArrayList actions) { - - actionRec = actions; - labelIndexTable= new SortedList(); - - // fill labelIndexTable - for (int i=0; i + /// The CodeWalker provides a simple functionality for traversing Action lists + /// by stepping through code and following branches. In opposite to + /// it doesn´t stop until a label is reached that has been visited before or a return + /// statement is found. Action objects are handled by the IActionExaminerer that is passed to + /// the Traverse method. + /// CodeWalker provide a base functionality for code analysis and simulation. + /// + public class CodeWalker { + + private ArrayList actionRec; + private SortedList labelIndexTable; + + private void Walk(int index,IActionExaminer examiner,ArrayList visitedLabels) { + + while (index + /// Start traversing at given index. + /// + /// IActionExaminer object + /// start index for code traversation. + public void Walk(IActionExaminer examiner,int index) { + + ArrayList visitedLabels = new ArrayList(); + Walk(index,examiner,visitedLabels); + } + + /// + /// Start traversing code flow at index 0. + /// + /// IActionExaminer object + public void Walk(IActionExaminer examiner) { + + ArrayList visitedLabels = new ArrayList(); + Walk(0,examiner,visitedLabels); + } + + /// + /// Constructor. + /// + /// ArrayList of BaseAction objects. + public CodeWalker (ArrayList actions) { + + actionRec = actions; + labelIndexTable= new SortedList(); + + // fill labelIndexTable + for (int i=0; iInterface for visitor-like objects passed to - /// or - /// - public interface IActionExaminer { - - /// Invoked by traverser for each visited action. - /// Examine action object found at given index. - /// - void Examine(int index,BaseAction action); - - /// Clone IActionExaminer object. Necessary for handling branches. - IActionExaminer Clone(); - } +{ + /// Interface for visitor-like objects passed to + /// or + /// + public interface IActionExaminer { + + /// Invoked by traverser for each visited action. + /// Examine action object found at given index. + /// + void Examine(int index,BaseAction action); + + /// Clone IActionExaminer object. Necessary for handling branches. + IActionExaminer Clone(); + } } diff --git a/External/Tools/SwfOp/CodeFlow/InvocationExaminer.cs b/External/Tools/SwfOp/CodeFlow/InvocationExaminer.cs index 7d0b48fbf2..ff22f3d7e0 100644 --- a/External/Tools/SwfOp/CodeFlow/InvocationExaminer.cs +++ b/External/Tools/SwfOp/CodeFlow/InvocationExaminer.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -27,203 +27,203 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.ByteCode.Actions; namespace SwfOp.CodeFlow -{ - /// - /// The InvocationExaminer class analyses method/function calls and object - /// initializations to find out how many values get pushed on or popped from stack. - /// It is passed to an instance of CodeTraverser by the decompiler. - /// - public class InvocationExaminer : IActionExaminer { - - private Stack stack; - - /// - /// Constructor. - /// - public InvocationExaminer() { - - stack = new Stack(); - - // we need to put some dummy values on stack - // in case values get popped from empty stack - for (int i=0; i<5; i++) stack.Push(null); - } - - /// - /// Clone method, necessary for handling branches. - /// - public IActionExaminer Clone() { - return new InvocationExaminer((Stack)stack.Clone()); - } +{ + /// + /// The InvocationExaminer class analyses method/function calls and object + /// initializations to find out how many values get pushed on or popped from stack. + /// It is passed to an instance of CodeTraverser by the decompiler. + /// + public class InvocationExaminer : IActionExaminer { + + private Stack stack; + + /// + /// Constructor. + /// + public InvocationExaminer() { + + stack = new Stack(); + + // we need to put some dummy values on stack + // in case values get popped from empty stack + for (int i=0; i<5; i++) stack.Push(null); + } + + /// + /// Clone method, necessary for handling branches. + /// + public IActionExaminer Clone() { + return new InvocationExaminer((Stack)stack.Clone()); + } - /// - /// Private constructor, used by Clone method. - /// - private InvocationExaminer(Stack s) { - stack = s; - } - - /// - /// Examine byte code action at index in action record. - /// - public void Examine(int index,BaseAction a) { - - ActionPush p; - int args; - CodeTraverser trav; - - switch ( a.Code ) { - - case (int)ActionCode.StackSwap: - object o1 = stack.Pop(); - object o2 = stack.Pop(); - stack.Push(o1); - stack.Push(o2); - break; - - case (int)ActionCode.PushDuplicate: - stack.Push(stack.Peek()); - break; - - case (int)ActionCode.Push: - stack.Push(a); - break; - - // -------------------------------------- - - case (int)ActionCode.CallMethod: - - ActionCallMethod cm = a as ActionCallMethod; - - stack.Pop(); // name - stack.Pop(); // script object - - p = stack.Pop() as ActionPush; - args = p.GetIntValue(); - for (int i=0; i-1) cm.NumArgs = args; - stack.Push(null); - break; - - case (int)ActionCode.CallFunction: - - ActionCallFunction cf = a as ActionCallFunction; - stack.Pop(); // name - p = stack.Pop() as ActionPush; - args = p.GetIntValue(); - for (int i=0; i-1) cf.NumArgs = args; - stack.Push(null); - break; - - // -------------------------------------- - - case (int)ActionCode.InitArray: - - ActionInitArray ia = a as ActionInitArray; - p = stack.Pop() as ActionPush; - args = p.GetIntValue(); - for (int i=0; i + /// Private constructor, used by Clone method. + /// + private InvocationExaminer(Stack s) { + stack = s; + } + + /// + /// Examine byte code action at index in action record. + /// + public void Examine(int index,BaseAction a) { + + ActionPush p; + int args; + CodeTraverser trav; + + switch ( a.Code ) { + + case (int)ActionCode.StackSwap: + object o1 = stack.Pop(); + object o2 = stack.Pop(); + stack.Push(o1); + stack.Push(o2); + break; + + case (int)ActionCode.PushDuplicate: + stack.Push(stack.Peek()); + break; + + case (int)ActionCode.Push: + stack.Push(a); + break; + + // -------------------------------------- + + case (int)ActionCode.CallMethod: + + ActionCallMethod cm = a as ActionCallMethod; + + stack.Pop(); // name + stack.Pop(); // script object + + p = stack.Pop() as ActionPush; + args = p.GetIntValue(); + for (int i=0; i-1) cm.NumArgs = args; + stack.Push(null); + break; + + case (int)ActionCode.CallFunction: + + ActionCallFunction cf = a as ActionCallFunction; + stack.Pop(); // name + p = stack.Pop() as ActionPush; + args = p.GetIntValue(); + for (int i=0; i-1) cf.NumArgs = args; + stack.Push(null); + break; + + // -------------------------------------- + + case (int)ActionCode.InitArray: + + ActionInitArray ia = a as ActionInitArray; + p = stack.Pop() as ActionPush; + args = p.GetIntValue(); + for (int i=0; i names; @@ -500,7 +503,7 @@ public class Abc internal long methodBodiesPosition; internal bool methodBodiesParsed; - internal Namespace publicNs = new Namespace(""); + internal Namespace publicNs = new Namespace(""); internal Namespace anyNs = new Namespace("*"); #endregion @@ -520,11 +523,11 @@ public Abc(BinaryReader br) const_values[11] = true; const_values[12] = null; - parseMethodInfos(br); - parseMetadataInfos(br); - parseInstanceInfos(br); - parseClassInfos(br); - parseScriptInfos(br); + parseMethodInfos(br); + parseMetadataInfos(br); + parseInstanceInfos(br); + parseClassInfos(br); + parseScriptInfos(br); // store read position for optional parseMethodBodies() call methodBodiesPosition = br.BaseStream.Position; @@ -563,73 +566,73 @@ static public string readUTFBytes(BinaryReader br) #region constants pool private void parseCpool(BinaryReader br) - { - long start = br.BaseStream.Position; + { + long start = br.BaseStream.Position; int n; - // ints - n = readU32(br); + // ints + n = readU32(br); ints = new int[n]; if (n > 0) ints[0] = 0; - for (int i=1; i < n; i++) - ints[i] = readU32(br); + for (int i=1; i < n; i++) + ints[i] = readU32(br); - // uints - n = readU32(br); + // uints + n = readU32(br); uints = new uint[n]; if (n > 0) uints[0] = 0; - for (int i=1; i < n; i++) - uints[i] = (uint)readU32(br); + for (int i=1; i < n; i++) + uints[i] = (uint)readU32(br); - // doubles - n = readU32(br); + // doubles + n = readU32(br); doubles = new double[n]; if (n > 0) doubles[0] = double.NaN; - for (int i=1; i < n; i++) - doubles[i] = br.ReadDouble(); + for (int i=1; i < n; i++) + doubles[i] = br.ReadDouble(); - // sb.append("Cpool numbers size "+(data.position-start)+" "+int(100*(data.position-start)/data.length)+" %") + // sb.append("Cpool numbers size "+(data.position-start)+" "+int(100*(data.position-start)/data.length)+" %") //Console.WriteLine("Cpool numbers size " + (br.BaseStream.Position - start) + " " + (int)(100 * (br.BaseStream.Position - start) / br.BaseStream.Length) + " %"); - start = br.BaseStream.Position; + start = br.BaseStream.Position; - // strings - n = readU32(br); + // strings + n = readU32(br); strings = new string[n]; if (n > 0) strings[0] = ""; for (int i = 1; i < n; i++) strings[i] = readUTFBytes(br); //br.ReadString() - // sb.append("Cpool strings count "+ n +" size "+(data.position-start)+" "+int(100*(data.position-start)/data.length)+" %") + // sb.append("Cpool strings count "+ n +" size "+(data.position-start)+" "+int(100*(data.position-start)/data.length)+" %") //Console.WriteLine("Cpool strings count " + n + " size " + (br.BaseStream.Position - start) + " " + (int)(100 * (br.BaseStream.Position - start) / br.BaseStream.Length) + " %"); - start = br.BaseStream.Position; + start = br.BaseStream.Position; - // namespaces - n = readU32(br); + // namespaces + n = readU32(br); namespaces = new Namespace[n]; if (n > 0) namespaces[0] = publicNs; - for (int i=1; i < n; i++) - switch ((ConstantKind)br.ReadSByte()) - { - case ConstantKind.Namespace: - case ConstantKind.PackageNs: - case ConstantKind.PackageInternalNs: - case ConstantKind.ProtectedNs: - case ConstantKind.StaticProtectedNs: - case ConstantKind.StaticProtectedNs2: - namespaces[i] = new Namespace((string)strings[readU32(br)]); - // todo mark kind of namespace. - break; - case ConstantKind.PrivateNs: - readU32(br); - namespaces[i] = new Namespace(null, "private"); - break; - } - - //Console.WriteLine("Cpool namespaces count "+ n +" size "+(br.BaseStream.Position-start)+" "+(int)(100*(br.BaseStream.Position-start)/br.BaseStream.Length)+" %"); + for (int i=1; i < n; i++) + switch ((ConstantKind)br.ReadSByte()) + { + case ConstantKind.Namespace: + case ConstantKind.PackageNs: + case ConstantKind.PackageInternalNs: + case ConstantKind.ProtectedNs: + case ConstantKind.StaticProtectedNs: + case ConstantKind.StaticProtectedNs2: + namespaces[i] = new Namespace((string)strings[readU32(br)]); + // todo mark kind of namespace. + break; + case ConstantKind.PrivateNs: + readU32(br); + namespaces[i] = new Namespace(null, "private"); + break; + } + + //Console.WriteLine("Cpool namespaces count "+ n +" size "+(br.BaseStream.Position-start)+" "+(int)(100*(br.BaseStream.Position-start)/br.BaseStream.Length)+" %"); start = br.BaseStream.Position; - // namespace sets - n = readU32(br); + // namespace sets + n = readU32(br); nssets = new Namespace[n][]; if (n > 0) nssets[0] = null; for (int i = 1; i < n; i++) @@ -641,15 +644,15 @@ private void parseCpool(BinaryReader br) nsset[j] = (Namespace)namespaces[readU32(br)]; } - //Console.WriteLine("Cpool nssets count "+ n +" size "+(br.BaseStream.Position-start)+" "+(int)(100*(br.BaseStream.Position-start)/br.BaseStream.Length)+" %"); + //Console.WriteLine("Cpool nssets count "+ n +" size "+(br.BaseStream.Position-start)+" "+(int)(100*(br.BaseStream.Position-start)/br.BaseStream.Length)+" %"); start = br.BaseStream.Position; - // multinames - n = readU32(br); + // multinames + n = readU32(br); names = new QName[n]; if (n > 0) names[0] = null; - namespaces[0] = anyNs; - strings[0] = "*"; + namespaces[0] = anyNs; + strings[0] = "*"; for (int i = 1; i < n; i++) { switch ((ConstantKind)br.ReadSByte()) @@ -706,8 +709,8 @@ private void parseCpool(BinaryReader br) //Console.WriteLine("Cpool names count " + n + " size " + (br.BaseStream.Position - start) + " " + (int)(100 * (br.BaseStream.Position - start) / br.BaseStream.Length) + " %"); - namespaces[0] = publicNs; - strings[0] = "*"; + namespaces[0] = publicNs; + strings[0] = "*"; } #endregion @@ -716,20 +719,20 @@ private void parseCpool(BinaryReader br) private void parseMethodInfos(BinaryReader br) { long start = br.BaseStream.Position; - names[0] = new QName(publicNs,"*"); - int method_count = readU32(br); - methods = new MethodInfo[method_count]; + names[0] = new QName(publicNs,"*"); + int method_count = readU32(br); + methods = new MethodInfo[method_count]; - for (int i=0; i < method_count; i++) - { - MethodInfo m = new MethodInfo(); + for (int i=0; i < method_count; i++) + { + MethodInfo m = new MethodInfo(); methods[i] = m; - int param_count = readU32(br); - m.returnType = (QName)names[readU32(br)]; + int param_count = readU32(br); + m.returnType = (QName)names[readU32(br)]; m.paramTypes = new QName[param_count]; - for (int j=0; j < param_count; j++) + for (int j=0; j < param_count; j++) m.paramTypes[j] = (QName)names[readU32(br)]; - m.debugName = (string)strings[readU32(br)]; + m.debugName = (string)strings[readU32(br)]; m.flags = (MethodFlags)br.ReadSByte(); if ((m.flags & MethodFlags.NeedRest) > 0) @@ -739,47 +742,47 @@ private void parseMethodInfos(BinaryReader br) temp.CopyTo(m.paramTypes, 0); m.paramTypes[param_count] = new QName("Array"); } - if ((m.flags & MethodFlags.HasOptional) > 0) - { - // has_optional - int optional_count = readU32(br); + if ((m.flags & MethodFlags.HasOptional) > 0) + { + // has_optional + int optional_count = readU32(br); if ((m.flags & MethodFlags.NeedRest) > 0) { m.optionalValues = new object[optional_count + 1]; m.optionalValues[optional_count] = null; } else m.optionalValues = new object[optional_count]; - for(int k = 0; k < optional_count; k++) - { - int index = readU32(br); // optional value index - ConstantKind kind = (ConstantKind)br.ReadSByte(); // kind byte for each default value - if (index == 0) - { - // kind is ignored, default value is based on type - m.optionalValues[k] = null; - } - else m.optionalValues[k] = getDefaultValue(kind, index); - } - } - if ((m.flags & MethodFlags.HasParamNames) > 0) - { - // has_paramnames + for(int k = 0; k < optional_count; k++) + { + int index = readU32(br); // optional value index + ConstantKind kind = (ConstantKind)br.ReadSByte(); // kind byte for each default value + if (index == 0) + { + // kind is ignored, default value is based on type + m.optionalValues[k] = null; + } + else m.optionalValues[k] = getDefaultValue(kind, index); + } + } + if ((m.flags & MethodFlags.HasParamNames) > 0) + { + // has_paramnames if ((m.flags & MethodFlags.NeedRest) > 0) { m.paramNames = new string[param_count + 1]; m.paramNames[param_count] = "...rest"; } else m.paramNames = new string[param_count]; - for(int k = 0; k < param_count; k++)//++k) + for(int k = 0; k < param_count; k++)//++k) { int index = readU32(br); if (index < strings.Length && strings[index] != null) m.paramNames[k] = (string)strings[index]; } } - } - //Console.WriteLine("MethodInfo count " +method_count+ " size "+(br.BaseStream.Position-start)+" "+(int)(100*(br.BaseStream.Position-start)/br.BaseStream.Length)+" %"); - } + } + //Console.WriteLine("MethodInfo count " +method_count+ " size "+(br.BaseStream.Position-start)+" "+(int)(100*(br.BaseStream.Position-start)/br.BaseStream.Length)+" %"); + } private object getDefaultValue(ConstantKind kind, int index) { @@ -806,43 +809,43 @@ private object getDefaultValue(ConstantKind kind, int index) } private void parseMetadataInfos(BinaryReader br) - { - int count = readU32(br); - metadata = new MetaData[count]; - - for (int i=0; i < count; i++) - { - // MetadataInfo - MetaData m = new MetaData(); + { + int count = readU32(br); + metadata = new MetaData[count]; + + for (int i=0; i < count; i++) + { + // MetadataInfo + MetaData m = new MetaData(); metadata[i] = m; - m.name = (string)strings[readU32(br)]; + m.name = (string)strings[readU32(br)]; - int values_count = readU32(br); - string[] names = new string[values_count]; - for(int q = 0; q < values_count; ++q) - names[q] = (string)strings[readU32(br)]; // name + int values_count = readU32(br); + string[] names = new string[values_count]; + for(int q = 0; q < values_count; ++q) + names[q] = (string)strings[readU32(br)]; // name for (int q = 0; q < values_count; ++q) m.Add(names[q], (string)strings[readU32(br)]); // value - } - } + } + } private void parseInstanceInfos(BinaryReader br) - { - long start = br.BaseStream.Position; - int count = readU32(br); - instances = new Traits[count]; - - for (int i=0; i < count; i++) - { - Traits t = new Traits(); + { + long start = br.BaseStream.Position; + int count = readU32(br); + instances = new Traits[count]; + + for (int i=0; i < count; i++) + { + Traits t = new Traits(); instances[i] = t; - t.name = (QName)names[readU32(br)]; + t.name = (QName)names[readU32(br)]; t.baseName = (QName)names[readU32(br)]; - t.flags = (TraitMember)br.ReadByte(); - if ((t.flags & TraitMember.HasProtectedNS) > 0) - t.protectedNs = (Namespace)namespaces[readU32(br)]; + t.flags = (TraitFlag)br.ReadByte(); + if ((t.flags & TraitFlag.HasProtectedNS) > 0) + t.protectedNs = (Namespace)namespaces[readU32(br)]; - int interface_count = readU32(br); + int interface_count = readU32(br); t.interfaces = new QName[interface_count]; for (int j = 0; j < interface_count; j++) { @@ -850,104 +853,104 @@ private void parseInstanceInfos(BinaryReader br) t.interfaces[j] = (QName)names[index]; } - MethodInfo m = t.init = (MethodInfo)methods[readU32(br)]; - m.name = t.name; - m.kind = TraitMember.Method; - m.id = -1; + MethodInfo m = t.init = (MethodInfo)methods[readU32(br)]; + m.name = t.name; + m.kind = TraitMember.Method; + m.id = -1; - parseTraits(br, t); - } + parseTraits(br, t); + } //Console.WriteLine("InstanceInfo size " + (br.BaseStream.Position - start) + " " + (int)(100 * (br.BaseStream.Position - start) / br.BaseStream.Length) + " %"); - } + } private void parseTraits(BinaryReader br, Traits t) - { - int namecount = readU32(br); - for (int i=0; i < namecount; i++) - { + { + int namecount = readU32(br); + for (int i=0; i < namecount; i++) + { QName name = (QName)names[readU32(br)]; byte tag = br.ReadByte(); - TraitMember kind = (TraitMember)((byte)tag & 0xf); - MemberInfo member = null; - switch (kind) + TraitMember kind = (TraitMember)((byte)tag & 0xf); + MemberInfo member = null; + switch (kind) { - case TraitMember.Slot: - case TraitMember.Const: - case TraitMember.Class: - SlotInfo slot = new SlotInfo(); + case TraitMember.Slot: + case TraitMember.Const: + case TraitMember.Class: + SlotInfo slot = new SlotInfo(); member = slot as MemberInfo; - slot.id = readU32(br); + slot.id = readU32(br); t.slots.Add(slot); - //t.slots[slot.id] = slot - if (kind == TraitMember.Slot || kind == TraitMember.Const) - { + //t.slots[slot.id] = slot + if (kind == TraitMember.Slot || kind == TraitMember.Const) + { slot.type = (QName)names[readU32(br)]; - int index = readU32(br); - if (index > 0) - slot.value = getDefaultValue((ConstantKind)br.ReadByte(), index); - } - else // (kind == TraitMember.Class) - { + int index = readU32(br); + if (index > 0) + slot.value = getDefaultValue((ConstantKind)br.ReadByte(), index); + } + else // (kind == TraitMember.Class) + { slot.value = classes[readU32(br)]; - } - break; - case TraitMember.Method: - case TraitMember.Getter: - case TraitMember.Setter: - int disp_id = readU32(br); + } + break; + case TraitMember.Method: + case TraitMember.Getter: + case TraitMember.Setter: + int disp_id = readU32(br); MethodInfo method = methods[readU32(br)]; member = method as MemberInfo; - //t.methods[disp_id] = method; + //t.methods[disp_id] = method; t.methods.Add(method); - method.id = disp_id; + method.id = disp_id; //Console.WriteLine("\t" + kind + " " + name + " " + disp_id + " " + method); - break; - } + break; + } - if (member == null) - Console.WriteLine("-- Error trait kind "+kind+"\n"); - member.kind = kind; - member.name = name; + if (member == null) + Console.WriteLine("-- Error trait kind "+kind+"\n"); + member.kind = kind; + member.name = name; //t.members[i] = member; t.members.Add(member); - t.names[name] = member; + t.names[name] = member; Attribute attr = (Attribute)(tag >> 4); if ((attr & Attribute.Metadata) > 0) { - member.metadata = new List(); + member.metadata = new List(); int mdCount = readU32(br); - for(int j=0; j < mdCount; ++j) - member.metadata.Add((MetaData)metadata[readU32(br)]); - } - } - } + for(int j=0; j < mdCount; ++j) + member.metadata.Add((MetaData)metadata[readU32(br)]); + } + } + } private void parseClassInfos(BinaryReader br) - { - long start = br.BaseStream.Position; - int count = instances.Length; + { + long start = br.BaseStream.Position; + int count = instances.Length; classes = new Traits[count]; - for (int i=0; i < count; i++) - { - Traits t = new Traits(); + for (int i=0; i < count; i++) + { + Traits t = new Traits(); classes[i] = t; - t.init = (MethodInfo)methods[readU32(br)]; - t.baseName = new QName("Class"); - t.itraits = instances[i]; - t.name = new QName(t.itraits.name.localName + "$"); - t.init.name = new QName(t.itraits.name.localName + "$cinit"); - t.init.kind = TraitMember.Method; - - parseTraits(br, t); - } + t.init = (MethodInfo)methods[readU32(br)]; + t.baseName = new QName("Class"); + t.itraits = instances[i]; + t.name = new QName(t.itraits.name.localName + "$"); + t.init.name = new QName(t.itraits.name.localName + "$cinit"); + t.init.kind = TraitMember.Method; + + parseTraits(br, t); + } //Console.WriteLine("ClassInfo size " + (br.BaseStream.Position - start) + " " + (int)(100 * (br.BaseStream.Position - start) / br.BaseStream.Length) + "%"); - } + } private void parseScriptInfos(BinaryReader br) - { - long start = br.BaseStream.Position; - int count = readU32(br); + { + long start = br.BaseStream.Position; + int count = readU32(br); scripts = new Traits[count]; for (int i = 0; i < count; i++) { @@ -962,7 +965,7 @@ private void parseScriptInfos(BinaryReader br) parseTraits(br, t); } //Console.WriteLine("ScriptInfo size " + (br.BaseStream.Position - start) + " " + (int)(100 * (br.BaseStream.Position - start) / br.BaseStream.Length) + " %"); - } + } /// /// Call this method to extract the methods information & bytecode diff --git a/External/Tools/SwfOp/Data/ClipActionRec.cs b/External/Tools/SwfOp/Data/ClipActionRec.cs index f3efc48831..8dcdb7c58f 100644 --- a/External/Tools/SwfOp/Data/ClipActionRec.cs +++ b/External/Tools/SwfOp/Data/ClipActionRec.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,60 +25,60 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.Data { - /// - /// The ClipActionRecord class. - /// - public class ClipActionRec { - - private byte[] header; - private int keyCode = -1; - private byte[] actionRec; - - /// - /// Property for accessing raw bytecode block. - /// - public byte[] ActionRecord { - get { - return actionRec; - } - set { - actionRec = value; - } - } - - /// - /// Constructor. - /// - /// Data preceding bytecode block that doesn´t need to get parsed. - /// Key code. - /// Raw bytecode. - public ClipActionRec(byte[] header, int key, byte[] actionRec) { - - this.header = header; - this.keyCode = key; - this.actionRec = actionRec; - - } - - /// - /// Get binary data of ClipAction Record for swf compilation. - /// - public byte[] GetData(byte version) { - - int offset = actionRec.Length; - if (keyCode>-1) offset++; - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); - - w.Write(header); - w.Write(offset); - - if (keyCode>-1) w.Write(Convert.ToByte(keyCode)); - - w.Write(actionRec); - - return m.ToArray(); - } - } + /// + /// The ClipActionRecord class. + /// + public class ClipActionRec { + + private byte[] header; + private int keyCode = -1; + private byte[] actionRec; + + /// + /// Property for accessing raw bytecode block. + /// + public byte[] ActionRecord { + get { + return actionRec; + } + set { + actionRec = value; + } + } + + /// + /// Constructor. + /// + /// Data preceding bytecode block that doesn´t need to get parsed. + /// Key code. + /// Raw bytecode. + public ClipActionRec(byte[] header, int key, byte[] actionRec) { + + this.header = header; + this.keyCode = key; + this.actionRec = actionRec; + + } + + /// + /// Get binary data of ClipAction Record for swf compilation. + /// + public byte[] GetData(byte version) { + + int offset = actionRec.Length; + if (keyCode>-1) offset++; + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); + + w.Write(header); + w.Write(offset); + + if (keyCode>-1) w.Write(Convert.ToByte(keyCode)); + + w.Write(actionRec); + + return m.ToArray(); + } + } } diff --git a/External/Tools/SwfOp/Data/RecordHeader.cs b/External/Tools/SwfOp/Data/RecordHeader.cs index 0a719f619c..16bdb2295c 100644 --- a/External/Tools/SwfOp/Data/RecordHeader.cs +++ b/External/Tools/SwfOp/Data/RecordHeader.cs @@ -1,88 +1,88 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.IO; -namespace SwfOp.Data { - - /// - /// RecordHeader class representing swf tag headers. - /// - public class RecordHeader { - - private int tagCode; - private int tagLength; - private bool longTag; - - /// - /// Constructor. - /// - public RecordHeader(int tag,int length,bool longT) { - - tagCode = tag; - tagLength = length; - longTag = longT; - } - - /// - /// Tag code property. - /// - public int TagCode { - get { - return tagCode; - } - } - - /// - /// Tag length property. - /// - public int TagLength { - get { - return tagLength; - } - } - - /// - /// Writes binary data to given BinaryWriter. - /// - public void WriteTo(BinaryWriter w) { - - if ( longTag || (tagLength>0x3e) ) { - - byte[] b = BitConverter.GetBytes( - Convert.ToUInt16( (Convert.ToUInt16(tagCode) << 6) + 0x3F ) - ); - w.Write( b ); - - UInt32 len = Convert.ToUInt32(tagLength); - b = BitConverter.GetBytes(len); - w.Write( b ); - - } else { - byte[] b = BitConverter.GetBytes( - Convert.ToUInt16( (Convert.ToUInt16(tagCode) << 6) + Convert.ToUInt16(tagLength) ) - ); - w.Write( b ); - } - } - } +namespace SwfOp.Data { + + /// + /// RecordHeader class representing swf tag headers. + /// + public class RecordHeader { + + private int tagCode; + private int tagLength; + private bool longTag; + + /// + /// Constructor. + /// + public RecordHeader(int tag,int length,bool longT) { + + tagCode = tag; + tagLength = length; + longTag = longT; + } + + /// + /// Tag code property. + /// + public int TagCode { + get { + return tagCode; + } + } + + /// + /// Tag length property. + /// + public int TagLength { + get { + return tagLength; + } + } + + /// + /// Writes binary data to given BinaryWriter. + /// + public void WriteTo(BinaryWriter w) { + + if ( longTag || (tagLength>0x3e) ) { + + byte[] b = BitConverter.GetBytes( + Convert.ToUInt16( (Convert.ToUInt16(tagCode) << 6) + 0x3F ) + ); + w.Write( b ); + + UInt32 len = Convert.ToUInt32(tagLength); + b = BitConverter.GetBytes(len); + w.Write( b ); + + } else { + byte[] b = BitConverter.GetBytes( + Convert.ToUInt16( (Convert.ToUInt16(tagCode) << 6) + Convert.ToUInt16(tagLength) ) + ); + w.Write( b ); + } + } + } } diff --git a/External/Tools/SwfOp/Data/Swf.cs b/External/Tools/SwfOp/Data/Swf.cs index bf1b1daeb7..0cde6e0a40 100644 --- a/External/Tools/SwfOp/Data/Swf.cs +++ b/External/Tools/SwfOp/Data/Swf.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,130 +25,130 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Data.Tags; namespace SwfOp.Data { - - /// - /// The Swf class is basically a data structure for swf data, containing header and a collection of swf tags. - /// - public class Swf : IEnumerable { - - /// - /// An array that contains BaseTag objects. - /// - private BaseTag[] tagList; - - /// - /// The total number of bytecode blocks within all tags. - /// - private int _actionCount; - - /// - /// Swf header. - /// - public SwfHeader Header; - - /// - /// Constructor. - /// - public Swf(SwfHeader header,BaseTag[] tagList) { - - this.Header = header; - this.tagList = tagList; - - // count actions - _actionCount = 0; - foreach (BaseTag b in tagList) { - _actionCount+=b.ActionRecCount; - } - } - - /// - /// Get enumerator for iterating over tag collection - /// - public IEnumerator GetEnumerator() { - return (IEnumerator) new TagEnumerator(this.tagList); - } - - // taglist iterator - internal class TagEnumerator : IEnumerator { - - private int index = -1; - private BaseTag[] tagList; - - public TagEnumerator(BaseTag[] tagList) { - this.tagList = tagList; - this.index = -1; - } - - public void Reset() { - index = -1; - } - - public bool MoveNext() { - index++; - return (index - /// Swf version property. - /// - public byte Version { - get { - return Header.Version; - } - set { - Header.Version = value; - } - } - - /// - /// Uncompressed swf byte count. - /// - public int ByteCount { - - get { - int len = 0; - foreach (BaseTag tag in tagList) { - len += tag.Data.Length; - } + + /// + /// The Swf class is basically a data structure for swf data, containing header and a collection of swf tags. + /// + public class Swf : IEnumerable { + + /// + /// An array that contains BaseTag objects. + /// + private BaseTag[] tagList; + + /// + /// The total number of bytecode blocks within all tags. + /// + private int _actionCount; + + /// + /// Swf header. + /// + public SwfHeader Header; + + /// + /// Constructor. + /// + public Swf(SwfHeader header,BaseTag[] tagList) { + + this.Header = header; + this.tagList = tagList; + + // count actions + _actionCount = 0; + foreach (BaseTag b in tagList) { + _actionCount+=b.ActionRecCount; + } + } + + /// + /// Get enumerator for iterating over tag collection + /// + public IEnumerator GetEnumerator() { + return (IEnumerator) new TagEnumerator(this.tagList); + } + + // taglist iterator + internal class TagEnumerator : IEnumerator { + + private int index = -1; + private BaseTag[] tagList; + + public TagEnumerator(BaseTag[] tagList) { + this.tagList = tagList; + this.index = -1; + } + + public void Reset() { + index = -1; + } + + public bool MoveNext() { + index++; + return (index + /// Swf version property. + /// + public byte Version { + get { + return Header.Version; + } + set { + Header.Version = value; + } + } + + /// + /// Uncompressed swf byte count. + /// + public int ByteCount { + + get { + int len = 0; + foreach (BaseTag tag in tagList) { + len += tag.Data.Length; + } - return 12+Header.Rect.Length+len; - } - } - - /// - /// Accessor for total count of swf bytecode blocks. - /// - public int ActionCount { - get { - return _actionCount; - } - } - - /// - /// Re-calc swf binary data. - /// - public void UpdateData() { - - foreach (BaseTag tag in tagList) { - tag.UpdateData(Header.Version); - } - } - - } + return 12+Header.Rect.Length+len; + } + } + + /// + /// Accessor for total count of swf bytecode blocks. + /// + public int ActionCount { + get { + return _actionCount; + } + } + + /// + /// Re-calc swf binary data. + /// + public void UpdateData() { + + foreach (BaseTag tag in tagList) { + tag.UpdateData(Header.Version); + } + } + + } } diff --git a/External/Tools/SwfOp/Data/SwfHeader.cs b/External/Tools/SwfOp/Data/SwfHeader.cs index 174d356df9..c13285e5e6 100644 --- a/External/Tools/SwfOp/Data/SwfHeader.cs +++ b/External/Tools/SwfOp/Data/SwfHeader.cs @@ -1,60 +1,60 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ -namespace SwfOp.Data { +namespace SwfOp.Data { - /// - /// Swf header structur. - /// - public struct SwfHeader { - - /// Signature property ('FWS' or 'CWS'). - public char[] Signature; - - /// Version. - public byte Version; - - /// FileSize. - public uint FileSize; - - /// Bytecode of rect data containing swf dimensions. - public byte[] Rect; - - /// Frames per second. - public ushort Fps; - - /// Total number of frames. - public ushort Frames; - - /// - /// Constructor. - /// - public SwfHeader (char[] sig,byte v,uint fs,byte[] ms,ushort fps,ushort fr) { - - Signature = sig; - Version = v; - FileSize = fs; - Rect = ms; - Fps = fps; - Frames = fr; - } - } + /// + /// Swf header structur. + /// + public struct SwfHeader { + + /// Signature property ('FWS' or 'CWS'). + public char[] Signature; + + /// Version. + public byte Version; + + /// FileSize. + public uint FileSize; + + /// Bytecode of rect data containing swf dimensions. + public byte[] Rect; + + /// Frames per second. + public ushort Fps; + + /// Total number of frames. + public ushort Frames; + + /// + /// Constructor. + /// + public SwfHeader (char[] sig,byte v,uint fs,byte[] ms,ushort fps,ushort fr) { + + Signature = sig; + Version = v; + FileSize = fs; + Rect = ms; + Fps = fps; + Frames = fr; + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/BaseTag.cs b/External/Tools/SwfOp/Data/Tags/BaseTag.cs index ab562b1e9b..f32292d0b2 100644 --- a/External/Tools/SwfOp/Data/Tags/BaseTag.cs +++ b/External/Tools/SwfOp/Data/Tags/BaseTag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,38 +25,38 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Data.Tags; namespace SwfOp.Data.Tags { - - /// - /// base class for swf tag objects - /// - public class BaseTag : IEnumerable { - - /// - /// raw tag data - /// - protected byte[] _data; - - /// - /// swf tag code - /// - protected int _tagCode = -1; - - /// - /// swf tag code property - /// - public int TagCode { - get { - return _tagCode; - } - } - - /// - /// raw tag data property - /// - public byte[] Data { - get { - return _data; - } + + /// + /// base class for swf tag objects + /// + public class BaseTag : IEnumerable { + + /// + /// raw tag data + /// + protected byte[] _data; + + /// + /// swf tag code + /// + protected int _tagCode = -1; + + /// + /// swf tag code property + /// + public int TagCode { + get { + return _tagCode; + } + } + + /// + /// raw tag data property + /// + public byte[] Data { + get { + return _data; + } } /// @@ -79,151 +79,151 @@ public BaseTag(byte[] data, int tagCode) _tagCode = tagCode; bytecodeHolder = new BytecodeHolder(this); } - - /// - /// constructor - /// - /// raw tag data - public BaseTag (byte[] data) { - _data = data; - bytecodeHolder = new BytecodeHolder(this); - } - - /// - /// constructor - /// - public BaseTag () { - _data = new byte[0]; - bytecodeHolder = new BytecodeHolder(this); - } - - /// - /// count of action records / raw bytecode blocks in tag - /// - public virtual int ActionRecCount { - get { - return 0; - } - } - - /// - /// rebuild tag data for swf compilation - /// - public virtual void UpdateData(byte version) { - } - - /// - /// indexer for accessing bytecode blocks - /// - public virtual byte[] this[int index] { - get { - return null; - } - set { - - } - } - - /// - /// get swf bytecode block enumerator for foreach-loops - /// - public virtual IEnumerator GetEnumerator() { - return (IEnumerator) new BytecodeEnumerator(this); - } - - private BytecodeHolder bytecodeHolder; - - /// - /// alias for the bytecode block indexer - /// - public BytecodeHolder Bytecode { - get { - return bytecodeHolder; - } - } - - /// - /// inner class for bytecode block collection - /// - public class BytecodeHolder { - - /// - /// bytecode block indexer - /// - public byte[] this[int index] { - get { - return tag[index]; - } - } - - /// - /// bytecode count - /// - public int Count { - get { - return tag.ActionRecCount; - } - } - - private BaseTag tag; - - /// - /// constructor. internal, since only used by BaseTag class - /// - /// the BaseTag, who´s bytecode is being held - internal BytecodeHolder(BaseTag t) { - tag = t; - } - } - - /// - /// inner class, swf bytecode block enumerator for 'foreach' loops - /// - public class BytecodeEnumerator : IEnumerator { - - private int index = -1; - private BaseTag tag; - - /// - /// constructor. internal, since only used by BaseTag class - /// - /// the BaseTag, who´s bytecode is being held - internal BytecodeEnumerator(BaseTag tag) { - this.tag = tag; - this.index = -1; - } - - /// - /// satisfy IEnumerator interface - /// - public void Reset() { - index = -1; - } - - /// - /// satisfy IEnumerator interface - /// - public bool MoveNext() { - if (index>tag.ActionRecCount) throw new InvalidOperationException(); - return ++index < tag.ActionRecCount; - } - - /// - /// typed access to current object - /// - public byte[] Current { - get { - if (index>=tag.ActionRecCount) throw new InvalidOperationException(); - return (tag[index]); - } - } - - /// - /// satisfy IEnumerator interface - /// - object IEnumerator.Current { - get { return this.Current; } - } - } - } + + /// + /// constructor + /// + /// raw tag data + public BaseTag (byte[] data) { + _data = data; + bytecodeHolder = new BytecodeHolder(this); + } + + /// + /// constructor + /// + public BaseTag () { + _data = new byte[0]; + bytecodeHolder = new BytecodeHolder(this); + } + + /// + /// count of action records / raw bytecode blocks in tag + /// + public virtual int ActionRecCount { + get { + return 0; + } + } + + /// + /// rebuild tag data for swf compilation + /// + public virtual void UpdateData(byte version) { + } + + /// + /// indexer for accessing bytecode blocks + /// + public virtual byte[] this[int index] { + get { + return null; + } + set { + + } + } + + /// + /// get swf bytecode block enumerator for foreach-loops + /// + public virtual IEnumerator GetEnumerator() { + return (IEnumerator) new BytecodeEnumerator(this); + } + + private BytecodeHolder bytecodeHolder; + + /// + /// alias for the bytecode block indexer + /// + public BytecodeHolder Bytecode { + get { + return bytecodeHolder; + } + } + + /// + /// inner class for bytecode block collection + /// + public class BytecodeHolder { + + /// + /// bytecode block indexer + /// + public byte[] this[int index] { + get { + return tag[index]; + } + } + + /// + /// bytecode count + /// + public int Count { + get { + return tag.ActionRecCount; + } + } + + private BaseTag tag; + + /// + /// constructor. internal, since only used by BaseTag class + /// + /// the BaseTag, who´s bytecode is being held + internal BytecodeHolder(BaseTag t) { + tag = t; + } + } + + /// + /// inner class, swf bytecode block enumerator for 'foreach' loops + /// + public class BytecodeEnumerator : IEnumerator { + + private int index = -1; + private BaseTag tag; + + /// + /// constructor. internal, since only used by BaseTag class + /// + /// the BaseTag, who´s bytecode is being held + internal BytecodeEnumerator(BaseTag tag) { + this.tag = tag; + this.index = -1; + } + + /// + /// satisfy IEnumerator interface + /// + public void Reset() { + index = -1; + } + + /// + /// satisfy IEnumerator interface + /// + public bool MoveNext() { + if (index>tag.ActionRecCount) throw new InvalidOperationException(); + return ++index < tag.ActionRecCount; + } + + /// + /// typed access to current object + /// + public byte[] Current { + get { + if (index>=tag.ActionRecCount) throw new InvalidOperationException(); + return (tag[index]); + } + } + + /// + /// satisfy IEnumerator interface + /// + object IEnumerator.Current { + get { return this.Current; } + } + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/DefineBitsJepg2Tag.cs b/External/Tools/SwfOp/Data/Tags/DefineBitsJepg2Tag.cs index e478db5f7c..400fdf0612 100644 --- a/External/Tools/SwfOp/Data/Tags/DefineBitsJepg2Tag.cs +++ b/External/Tools/SwfOp/Data/Tags/DefineBitsJepg2Tag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -24,22 +24,22 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Data.Tags; namespace SwfOp.Data.Tags { - - - /// - /// DefineBits tag for Jpeg images in swf - /// + + + /// + /// DefineBits tag for Jpeg images in swf + /// public class DefineBitsJpeg2Tag : DefineBitsTag { - /// - /// constructor - /// + /// + /// constructor + /// public DefineBitsJpeg2Tag(ushort id, byte[] image) : base(id, image) { } - - } + + } } diff --git a/External/Tools/SwfOp/Data/Tags/DefineBitsJpeg3Tag.cs b/External/Tools/SwfOp/Data/Tags/DefineBitsJpeg3Tag.cs index 543a309f78..bb4d0ed86a 100644 --- a/External/Tools/SwfOp/Data/Tags/DefineBitsJpeg3Tag.cs +++ b/External/Tools/SwfOp/Data/Tags/DefineBitsJpeg3Tag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -24,54 +24,54 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Data.Tags; namespace SwfOp.Data.Tags { - - - /// - /// DefineBits tag for Jpeg images in swf - /// - public class DefineBitsJpeg3Tag : DefineBitsTag { - - private byte[] alphaData; - - /// - /// constructor - /// - public DefineBitsJpeg3Tag(ushort id,byte[] image,byte[] alpha) + + + /// + /// DefineBits tag for Jpeg images in swf + /// + public class DefineBitsJpeg3Tag : DefineBitsTag { + + private byte[] alphaData; + + /// + /// constructor + /// + public DefineBitsJpeg3Tag(ushort id,byte[] image,byte[] alpha) : base(id, image) { - alphaData = alpha; - } - - /// - /// alpha Data - /// - public byte[] AlphaData { - get { - return alphaData; - } - set { - alphaData = value; - } - } - - /// - /// see base class - /// - public override void UpdateData(byte version) { - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); + alphaData = alpha; + } + + /// + /// alpha Data + /// + public byte[] AlphaData { + get { + return alphaData; + } + set { + alphaData = value; + } + } + + /// + /// see base class + /// + public override void UpdateData(byte version) { + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); RecordHeader rh = new RecordHeader(TagCode, 6 + mediaData.Length + alphaData.Length, true); - - rh.WriteTo(w); - w.Write(characterId); + + rh.WriteTo(w); + w.Write(characterId); w.Write(Convert.ToUInt32(mediaData.Length)); w.Write(mediaData); - w.Write(alphaData); - - // write to data array - _data = m.ToArray(); - } - } + w.Write(alphaData); + + // write to data array + _data = m.ToArray(); + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/DefineBitsTag.cs b/External/Tools/SwfOp/Data/Tags/DefineBitsTag.cs index b7bc7891ab..15daaf15de 100644 --- a/External/Tools/SwfOp/Data/Tags/DefineBitsTag.cs +++ b/External/Tools/SwfOp/Data/Tags/DefineBitsTag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash ActionScript bytecode. - Copyright (C) 2004 Florian Krsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash ActionScript bytecode. + Copyright (C) 2004 Florian Krsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -24,54 +24,54 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Data.Tags; namespace SwfOp.Data.Tags { - - - /// - /// DefineBits tag for Jpeg images in swf - /// - public class DefineBitsTag : SwfOp.Data.Tags.BaseTag { - - protected byte[] mediaData; + + + /// + /// DefineBits tag for Jpeg images in swf + /// + public class DefineBitsTag : SwfOp.Data.Tags.BaseTag { + + protected byte[] mediaData; protected ushort characterId; - - /// - /// constructor - /// - public DefineBitsTag(ushort id, byte[] image) { - characterId = id; - mediaData = image; - } + + /// + /// constructor + /// + public DefineBitsTag(ushort id, byte[] image) { + characterId = id; + mediaData = image; + } public ushort Id { get { return characterId; } } - - /// - /// JPEG Data - /// - public byte[] MediaData { - get { + + /// + /// JPEG Data + /// + public byte[] MediaData { + get { return mediaData; - } - set { + } + set { mediaData = value; - } - } - - /// - /// see base class - /// - public override void UpdateData(byte version) { - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); - - RecordHeader rh = new RecordHeader(TagCode, 2 + mediaData.Length ,true); - - rh.WriteTo(w); - w.Write(characterId); - w.Write(mediaData); - - // write to data array - _data = m.ToArray(); - } - } + } + } + + /// + /// see base class + /// + public override void UpdateData(byte version) { + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); + + RecordHeader rh = new RecordHeader(TagCode, 2 + mediaData.Length ,true); + + rh.WriteTo(w); + w.Write(characterId); + w.Write(mediaData); + + // write to data array + _data = m.ToArray(); + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/DefineSoundTag.cs b/External/Tools/SwfOp/Data/Tags/DefineSoundTag.cs index 487352085e..16dfb66387 100644 --- a/External/Tools/SwfOp/Data/Tags/DefineSoundTag.cs +++ b/External/Tools/SwfOp/Data/Tags/DefineSoundTag.cs @@ -7,8 +7,8 @@ namespace SwfOp.Data.Tags public class DefineSoundTag:DefineBitsTag { /// - /// constructor - /// + /// constructor + /// public DefineSoundTag(ushort id, byte[] sound) : base(id, sound) { diff --git a/External/Tools/SwfOp/Data/Tags/DefineSpriteTag.cs b/External/Tools/SwfOp/Data/Tags/DefineSpriteTag.cs index 22e040d0a0..2eaed29b8a 100644 --- a/External/Tools/SwfOp/Data/Tags/DefineSpriteTag.cs +++ b/External/Tools/SwfOp/Data/Tags/DefineSpriteTag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,36 +25,36 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Data.Tags; namespace SwfOp.Data.Tags { - - /// - /// DefineSprite tag object - /// - public class DefineSpriteTag : BaseTag { - - /// - /// raw header data - /// - private byte[] header; - - /// - /// inner tags - /// - private BaseTag[] tagList; - - /// - /// action count including inner tags´ actions - /// - private int _actionCount; - - /// - /// tag index for action block index - /// - private int[] tagForAction; - - /// - /// contains action block counts for inner tags - /// - private int[] tagOffset; + + /// + /// DefineSprite tag object + /// + public class DefineSpriteTag : BaseTag { + + /// + /// raw header data + /// + private byte[] header; + + /// + /// inner tags + /// + private BaseTag[] tagList; + + /// + /// action count including inner tags´ actions + /// + private int _actionCount; + + /// + /// tag index for action block index + /// + private int[] tagForAction; + + /// + /// contains action block counts for inner tags + /// + private int[] tagOffset; /// /// total size of the sprite (including children) @@ -65,41 +65,41 @@ public class DefineSpriteTag : BaseTag { /// symbol id /// private ushort id = ushort.MaxValue; - - /// - /// constructor. - /// - /// header data - /// list of inner tags - public DefineSpriteTag(byte[] header, BaseTag[] tags, long size) { - - this.header = header; - this.tagList = tags; + + /// + /// constructor. + /// + /// header data + /// list of inner tags + public DefineSpriteTag(byte[] header, BaseTag[] tags, long size) { + + this.header = header; + this.tagList = tags; this.size = size; - - _tagCode = (int)TagCodeEnum.DefineSprite; - - _actionCount = 0; - foreach (BaseTag b in tagList) { - _actionCount += b.ActionRecCount; - } - - tagForAction = new int[_actionCount]; - tagOffset = new int[tagList.Length]; - - int actionIdx = 0; - for (int i=0; i0) { - for (int j=0; j0) { + for (int j=0; j /// Sprite ID @@ -122,63 +122,63 @@ public ushort Id /// total size of the sprite (including children) /// public override long Size { get { return size; } } - - /// - /// see base class - /// - public override int ActionRecCount { - get { - return _actionCount; - } - } - - /// - /// see base class - /// - public override byte[] this[int index] { - - get { - if ((index<0) || (index>=ActionRecCount)) return null; - - int offset = index-tagOffset[tagForAction[index]]; - return tagList[tagForAction[index]] [offset]; - } - - set { - if ((index>-1) && (index - /// see base class - /// - public override void UpdateData(byte version) { - - // update inner tags - int len = 0; - for (int i=0; i + /// see base class + /// + public override int ActionRecCount { + get { + return _actionCount; + } + } + + /// + /// see base class + /// + public override byte[] this[int index] { + + get { + if ((index<0) || (index>=ActionRecCount)) return null; + + int offset = index-tagOffset[tagForAction[index]]; + return tagList[tagForAction[index]] [offset]; + } + + set { + if ((index>-1) && (index + /// see base class + /// + public override void UpdateData(byte version) { + + // update inner tags + int len = 0; + for (int i=0; i - /// DoAction tag object - /// - public class DoActionTag : BaseTag { - - /// - /// bytecode block - /// - private byte[] actionRecord; - - /// - /// constructor - /// - /// swf bytecode action block - public DoActionTag(byte[] actionRecord) { - this.actionRecord = actionRecord; - _tagCode = (int)TagCodeEnum.DoAction; - } - - /// - /// see base class - /// - public override int ActionRecCount { - get { - return 1; - } - } - - /// - /// see base class - /// - public override byte[] this[int index] { - get { - return actionRecord; - } - set { - actionRecord = value; - } - } - - /// - /// see base class - /// - public override void UpdateData(byte version) { - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); - - RecordHeader rh = new RecordHeader(TagCode,actionRecord.Length,true); - - rh.WriteTo(w); - w.Write(actionRecord); - - // write to data array - _data = m.ToArray(); - } - } + /// + /// DoAction tag object + /// + public class DoActionTag : BaseTag { + + /// + /// bytecode block + /// + private byte[] actionRecord; + + /// + /// constructor + /// + /// swf bytecode action block + public DoActionTag(byte[] actionRecord) { + this.actionRecord = actionRecord; + _tagCode = (int)TagCodeEnum.DoAction; + } + + /// + /// see base class + /// + public override int ActionRecCount { + get { + return 1; + } + } + + /// + /// see base class + /// + public override byte[] this[int index] { + get { + return actionRecord; + } + set { + actionRecord = value; + } + } + + /// + /// see base class + /// + public override void UpdateData(byte version) { + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); + + RecordHeader rh = new RecordHeader(TagCode,actionRecord.Length,true); + + rh.WriteTo(w); + w.Write(actionRecord); + + // write to data array + _data = m.ToArray(); + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/ExportTag.cs b/External/Tools/SwfOp/Data/Tags/ExportTag.cs index 17d2f5117b..c94d5a1a27 100644 --- a/External/Tools/SwfOp/Data/Tags/ExportTag.cs +++ b/External/Tools/SwfOp/Data/Tags/ExportTag.cs @@ -12,57 +12,57 @@ namespace SwfOp.Data.Tags { - /// - /// Description of ExportTag. - /// - public class ExportTag : BaseTag - { - private ArrayList _names; - private ArrayList _ids; - - public ExportTag(ArrayList ids, ArrayList names) - { - _tagCode = (int)TagCodeEnum.ExportAssets; - _names = names; - _ids = ids; + /// + /// Description of ExportTag. + /// + public class ExportTag : BaseTag + { + private ArrayList _names; + private ArrayList _ids; + + public ExportTag(ArrayList ids, ArrayList names) + { + _tagCode = (int)TagCodeEnum.ExportAssets; + _names = names; + _ids = ids; } public ArrayList Ids { get { return _ids; } } - - public ArrayList Names - { - get { return _names; } - } - - /// - /// see base class - /// - public override void UpdateData(byte version) { - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); - - int size = _ids.Count*2; - foreach(string name in _names) - size += name.Length+1; - - RecordHeader rh = new RecordHeader(TagCode, 2 + size,true); - - rh.WriteTo(w); - w.Write((ushort)_names.Count); - - for(int i=0; i<_names.Count; i++) - { - w.Write((ushort)_ids[i]); - w.Write((string)_names[i]); - w.Write((byte)0); - } - - // write to data array - _data = m.ToArray(); - } - } + + public ArrayList Names + { + get { return _names; } + } + + /// + /// see base class + /// + public override void UpdateData(byte version) { + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); + + int size = _ids.Count*2; + foreach(string name in _names) + size += name.Length+1; + + RecordHeader rh = new RecordHeader(TagCode, 2 + size,true); + + rh.WriteTo(w); + w.Write((ushort)_names.Count); + + for(int i=0; i<_names.Count; i++) + { + w.Write((ushort)_ids[i]); + w.Write((string)_names[i]); + w.Write((byte)0); + } + + // write to data array + _data = m.ToArray(); + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/InitActionTag.cs b/External/Tools/SwfOp/Data/Tags/InitActionTag.cs index cd037fcfd6..057465c2cc 100644 --- a/External/Tools/SwfOp/Data/Tags/InitActionTag.cs +++ b/External/Tools/SwfOp/Data/Tags/InitActionTag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,68 +25,68 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Data.Tags; namespace SwfOp.Data.Tags { - - /// - /// InitAction tag object - /// - public class InitActionTag : BaseTag { - - /// sprite id - private ushort spriteId; - - /// bytecode block - private byte[] actionRecord; - - /// - /// constructor - /// - /// see swf docs - /// byte code block - public InitActionTag(ushort spriteId,byte[] actionRecord) { - - this.spriteId = spriteId; - this.actionRecord = actionRecord; - - _tagCode = (int)TagCodeEnum.InitAction; - } - - /// - /// see base class - /// - public override int ActionRecCount { - get { - return 1; - } - } - - /// - /// see base class - /// - public override byte[] this[int index] { - get { - return actionRecord; - } - set { - actionRecord = value; - } - } - - /// - /// see base class - /// - public override void UpdateData(byte version) { - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); - - RecordHeader rh = new RecordHeader(TagCode, 2 + actionRecord.Length ,true); - - rh.WriteTo(w); - w.Write(spriteId); - w.Write(actionRecord); - - // write to data array - _data = m.ToArray(); - } - } + + /// + /// InitAction tag object + /// + public class InitActionTag : BaseTag { + + /// sprite id + private ushort spriteId; + + /// bytecode block + private byte[] actionRecord; + + /// + /// constructor + /// + /// see swf docs + /// byte code block + public InitActionTag(ushort spriteId,byte[] actionRecord) { + + this.spriteId = spriteId; + this.actionRecord = actionRecord; + + _tagCode = (int)TagCodeEnum.InitAction; + } + + /// + /// see base class + /// + public override int ActionRecCount { + get { + return 1; + } + } + + /// + /// see base class + /// + public override byte[] this[int index] { + get { + return actionRecord; + } + set { + actionRecord = value; + } + } + + /// + /// see base class + /// + public override void UpdateData(byte version) { + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); + + RecordHeader rh = new RecordHeader(TagCode, 2 + actionRecord.Length ,true); + + rh.WriteTo(w); + w.Write(spriteId); + w.Write(actionRecord); + + // write to data array + _data = m.ToArray(); + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/JpegTable.cs b/External/Tools/SwfOp/Data/Tags/JpegTable.cs index 9ed2f26f54..3935be3815 100644 --- a/External/Tools/SwfOp/Data/Tags/JpegTable.cs +++ b/External/Tools/SwfOp/Data/Tags/JpegTable.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch - see Licence.cs for LGPL full text - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch + see Licence.cs for LGPL full text + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -24,48 +24,48 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.Data.Tags { - /// - /// Description of JPEGTableTag. - /// - public class JpegTableTag : BaseTag - { - /// - /// constructor. - /// - public JpegTableTag(byte[] jpeg) - { - jpegData = jpeg; - } - - private byte[] jpegData; - - /// - /// JPEG Data - /// - public byte[] JpegData { - get { - return jpegData; - } - set { - jpegData = value; - } - } - - /// - /// see base class - /// - public override void UpdateData(byte version) { - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); - - RecordHeader rh = new RecordHeader(TagCode, jpegData.Length ,true); - - rh.WriteTo(w); - w.Write(jpegData); - - // write to data array - _data = m.ToArray(); - } - } + /// + /// Description of JPEGTableTag. + /// + public class JpegTableTag : BaseTag + { + /// + /// constructor. + /// + public JpegTableTag(byte[] jpeg) + { + jpegData = jpeg; + } + + private byte[] jpegData; + + /// + /// JPEG Data + /// + public byte[] JpegData { + get { + return jpegData; + } + set { + jpegData = value; + } + } + + /// + /// see base class + /// + public override void UpdateData(byte version) { + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); + + RecordHeader rh = new RecordHeader(TagCode, jpegData.Length ,true); + + rh.WriteTo(w); + w.Write(jpegData); + + // write to data array + _data = m.ToArray(); + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/MetaDataTag.cs b/External/Tools/SwfOp/Data/Tags/MetaDataTag.cs index 7b55f8a309..d59afa1662 100644 --- a/External/Tools/SwfOp/Data/Tags/MetaDataTag.cs +++ b/External/Tools/SwfOp/Data/Tags/MetaDataTag.cs @@ -15,8 +15,8 @@ public MetaDataTag(string meta) } /// - /// see base class - /// + /// see base class + /// public override void UpdateData(byte version) { throw new NotImplementedException(); diff --git a/External/Tools/SwfOp/Data/Tags/PlaceObject2Tag.cs b/External/Tools/SwfOp/Data/Tags/PlaceObject2Tag.cs index 557c166c35..f1be9ee779 100644 --- a/External/Tools/SwfOp/Data/Tags/PlaceObject2Tag.cs +++ b/External/Tools/SwfOp/Data/Tags/PlaceObject2Tag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,84 +25,84 @@ You should have received a copy of the GNU Lesser General Public using SwfOp.Data.Tags; namespace SwfOp.Data.Tags { - - /// - /// PlaceObject2 tag object - /// - public class PlaceObject2Tag : BaseTag { - - private byte[] header; - private ClipActionRec[] clipActions; - - /// - /// constructor - /// - /// header data - /// swf action blocks (clip actions) - public PlaceObject2Tag(byte[] h,ClipActionRec[] clp) { - - header = h; - clipActions = clp; - - _tagCode = (int)TagCodeEnum.PlaceObject2; - } - - /// - /// see base class - /// - public override int ActionRecCount { - get { - return clipActions.Length; - } - } - - /// - /// see base class - /// - public override byte[] this[int index] { - get { - return clipActions[index].ActionRecord; - } - set { - clipActions[index].ActionRecord = value; - } - } - - /// - /// see base class - /// - public override void UpdateData(byte version) { - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); - - w.Write(header); - - // ClipActionRecords - foreach (ClipActionRec clpA in clipActions) { - w.Write(clpA.GetData(version)); - } - // ClipActionRecords end - if (version>=6) { - w.Write((int)0); - } else { - w.Write((short)0); - } - - // data to byte array - byte[] d = m.ToArray(); - - // writer - m = new MemoryStream(); - w = new BinaryWriter(m); - - // add header - RecordHeader rh = new RecordHeader(TagCode,d.Length,true); - rh.WriteTo( w ); - w.Write (d ); - - // write to data array - _data = m.ToArray(); - } - } + + /// + /// PlaceObject2 tag object + /// + public class PlaceObject2Tag : BaseTag { + + private byte[] header; + private ClipActionRec[] clipActions; + + /// + /// constructor + /// + /// header data + /// swf action blocks (clip actions) + public PlaceObject2Tag(byte[] h,ClipActionRec[] clp) { + + header = h; + clipActions = clp; + + _tagCode = (int)TagCodeEnum.PlaceObject2; + } + + /// + /// see base class + /// + public override int ActionRecCount { + get { + return clipActions.Length; + } + } + + /// + /// see base class + /// + public override byte[] this[int index] { + get { + return clipActions[index].ActionRecord; + } + set { + clipActions[index].ActionRecord = value; + } + } + + /// + /// see base class + /// + public override void UpdateData(byte version) { + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); + + w.Write(header); + + // ClipActionRecords + foreach (ClipActionRec clpA in clipActions) { + w.Write(clpA.GetData(version)); + } + // ClipActionRecords end + if (version>=6) { + w.Write((int)0); + } else { + w.Write((short)0); + } + + // data to byte array + byte[] d = m.ToArray(); + + // writer + m = new MemoryStream(); + w = new BinaryWriter(m); + + // add header + RecordHeader rh = new RecordHeader(TagCode,d.Length,true); + rh.WriteTo( w ); + w.Write (d ); + + // write to data array + _data = m.ToArray(); + } + } } diff --git a/External/Tools/SwfOp/Data/Tags/ScriptLimitTag.cs b/External/Tools/SwfOp/Data/Tags/ScriptLimitTag.cs index a4a43daec6..69305e5a4a 100644 --- a/External/Tools/SwfOp/Data/Tags/ScriptLimitTag.cs +++ b/External/Tools/SwfOp/Data/Tags/ScriptLimitTag.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -26,77 +26,77 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.Data.Tags { - /// - /// ScriptLimit tag - /// - public class ScriptLimitTag : BaseTag { - - private ushort _recursion; - private ushort _timeout; - - /// - /// constructor - /// - /// recursion depth - /// specified timeout - public ScriptLimitTag(ushort recursion,ushort timeout) { - - _recursion = recursion; - _timeout = timeout; - - _tagCode = (int)TagCodeEnum.ScriptLimit; - } - - /// - /// recursion property - /// - public int Recursion { - get { - return Convert.ToInt32(_recursion); - } - set { - _recursion = Convert.ToUInt16(value); - } - } - - /// - /// timeout property - /// - public int TimeOut { - get { - return Convert.ToInt32(_timeout); - } - set { - _timeout = Convert.ToUInt16(value); - } - } - - /// - /// see base class - /// - public override int ActionRecCount { - get { - return 0; - } - } - - /// - /// see base class - /// - public override void UpdateData(byte version) { - - MemoryStream m = new MemoryStream(); - BinaryWriter w = new BinaryWriter(m); - - RecordHeader rh = new RecordHeader(TagCode,4,false); - - rh.WriteTo(w); - w.Write(_recursion); - w.Write(_timeout); - - // write to data array - _data = m.ToArray(); - } - - } + /// + /// ScriptLimit tag + /// + public class ScriptLimitTag : BaseTag { + + private ushort _recursion; + private ushort _timeout; + + /// + /// constructor + /// + /// recursion depth + /// specified timeout + public ScriptLimitTag(ushort recursion,ushort timeout) { + + _recursion = recursion; + _timeout = timeout; + + _tagCode = (int)TagCodeEnum.ScriptLimit; + } + + /// + /// recursion property + /// + public int Recursion { + get { + return Convert.ToInt32(_recursion); + } + set { + _recursion = Convert.ToUInt16(value); + } + } + + /// + /// timeout property + /// + public int TimeOut { + get { + return Convert.ToInt32(_timeout); + } + set { + _timeout = Convert.ToUInt16(value); + } + } + + /// + /// see base class + /// + public override int ActionRecCount { + get { + return 0; + } + } + + /// + /// see base class + /// + public override void UpdateData(byte version) { + + MemoryStream m = new MemoryStream(); + BinaryWriter w = new BinaryWriter(m); + + RecordHeader rh = new RecordHeader(TagCode,4,false); + + rh.WriteTo(w); + w.Write(_recursion); + w.Write(_timeout); + + // write to data array + _data = m.ToArray(); + } + + } } diff --git a/External/Tools/SwfOp/Data/Tags/TagCodeEnum.cs b/External/Tools/SwfOp/Data/Tags/TagCodeEnum.cs index aa106f4f02..a2f2e2829d 100644 --- a/External/Tools/SwfOp/Data/Tags/TagCodeEnum.cs +++ b/External/Tools/SwfOp/Data/Tags/TagCodeEnum.cs @@ -1,40 +1,40 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krsch. - see Licence.cs for LGPL full text! + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krsch. + see Licence.cs for LGPL full text! - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. - This library 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 - Lesser General Public License for more details. + This library 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 + Lesser General Public License for more details. - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace SwfOp.Data.Tags { - // action tags: - // 12: DoAction - // 26: PlaceObject2 - // 39: DefineSprite - // 59: InitAction + // action tags: + // 12: DoAction + // 26: PlaceObject2 + // 39: DefineSprite + // 59: InitAction - // button tags, not implemented - // 7: DefineButton - // 34: DefineButton2 + // button tags, not implemented + // 7: DefineButton + // 34: DefineButton2 - /// - /// enumeration of tag codes of tags containing bytecode - /// - public enum TagCodeEnum { + /// + /// enumeration of tag codes of tags containing bytecode + /// + public enum TagCodeEnum { End = 00, ShowFrame = 01, DefineShape = 02, @@ -120,5 +120,5 @@ public enum TagCodeEnum { DefineSceneAndFrameData = 86, DefineBinaryData = 87, DefineFontName = 88 - } + } } diff --git a/External/Tools/SwfOp/IO/InvalidTagLengthException.cs b/External/Tools/SwfOp/IO/InvalidTagLengthException.cs index ce7aa3e041..c4cbdbe544 100644 --- a/External/Tools/SwfOp/IO/InvalidTagLengthException.cs +++ b/External/Tools/SwfOp/IO/InvalidTagLengthException.cs @@ -1,36 +1,36 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; namespace SwfOp.IO { - /// - /// invalid tag length exception - /// - public sealed class InvalidTagLengthException : ApplicationException { - - /// - /// constructor - /// - public InvalidTagLengthException() : base("InvalidTagLengthException") { - } - } + /// + /// invalid tag length exception + /// + public sealed class InvalidTagLengthException : ApplicationException { + + /// + /// constructor + /// + public InvalidTagLengthException() : base("InvalidTagLengthException") { + } + } } diff --git a/External/Tools/SwfOp/IO/SwfExportTagReader.cs b/External/Tools/SwfOp/IO/SwfExportTagReader.cs index e614472314..1e8ae7171f 100644 --- a/External/Tools/SwfOp/IO/SwfExportTagReader.cs +++ b/External/Tools/SwfOp/IO/SwfExportTagReader.cs @@ -14,31 +14,31 @@ namespace SwfOp.IO { - /// - /// Specialized SWF parser to extract some specific tags - /// - public class SwfExportTagReader: SwfReader - { - public SwfExportTagReader(Stream stream): base(stream) - { - } - - override protected BaseTag ReadTag() - { - long posBefore = br.BaseStream.Position; - RecordHeader rh = ReadRecordHeader(); - int offset = (int)(br.BaseStream.Position-posBefore); - br.BaseStream.Position = posBefore; + /// + /// Specialized SWF parser to extract some specific tags + /// + public class SwfExportTagReader: SwfReader + { + public SwfExportTagReader(Stream stream): base(stream) + { + } + + override protected BaseTag ReadTag() + { + long posBefore = br.BaseStream.Position; + RecordHeader rh = ReadRecordHeader(); + int offset = (int)(br.BaseStream.Position-posBefore); + br.BaseStream.Position = posBefore; TagCodeEnum tag = (TagCodeEnum)rh.TagCode; //if (tag != TagCodeEnum.End) Console.WriteLine("Tag: " + (TagCodeEnum)rh.TagCode); switch (tag) { - //-- Parse sub-clips - case TagCodeEnum.DefineSprite: + //-- Parse sub-clips + case TagCodeEnum.DefineSprite: return ReadDefineSpriteTag(); - - case TagCodeEnum.ExportAssets: + + case TagCodeEnum.ExportAssets: case TagCodeEnum.SymbolClass: return ReadExportTag(offset); @@ -47,7 +47,7 @@ override protected BaseTag ReadTag() case TagCodeEnum.DoABC: return new AbcTag(br.ReadBytes(rh.TagLength + offset), offset, false); - + case TagCodeEnum.FrameLabel: return ReadFrameTag(offset); @@ -71,7 +71,7 @@ override protected BaseTag ReadTag() br.BaseStream.Position = posBefore; return new BaseTag(br.ReadBytes(rh.TagLength + offset), rh.TagCode);*/ - default: + default: // Dump tag /*br.BaseStream.Position += offset; byte b; @@ -84,9 +84,9 @@ override protected BaseTag ReadTag() Console.WriteLine(); br.BaseStream.Position = posBefore;*/ return new BaseTag(br.ReadBytes(rh.TagLength+offset), rh.TagCode); - } - - } + } + + } BaseTag ReadMetaDataTag(int offset) { @@ -101,5 +101,5 @@ BaseTag ReadFrameTag(int offset) string name = ReadString(); return new FrameTag(name); } - } + } } diff --git a/External/Tools/SwfOp/IO/SwfReader.cs b/External/Tools/SwfOp/IO/SwfReader.cs index 7a292f150c..d98c0e1910 100644 --- a/External/Tools/SwfOp/IO/SwfReader.cs +++ b/External/Tools/SwfOp/IO/SwfReader.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -29,464 +29,464 @@ You should have received a copy of the GNU Lesser General Public using System.Text; namespace SwfOp.IO { - - /// - /// The SwfReader class reads and parses an swf from a stream. All swf data structures that might contain actions - /// or are in the way of accessing bytecode-actions are de-coded here. It doesnt decompile bytecode, though. - /// This is handled by SwfOp.ByteCode.Decompiler - /// - public class SwfReader { - - protected byte version = 0; - protected BinaryReader br; + + /// + /// The SwfReader class reads and parses an swf from a stream. All swf data structures that might contain actions + /// or are in the way of accessing bytecode-actions are de-coded here. It doesnt decompile bytecode, though. + /// This is handled by SwfOp.ByteCode.Decompiler + /// + public class SwfReader { + + protected byte version = 0; + protected BinaryReader br; protected long streamEnd; - - /// - /// Read only property; returns Flash version of the read swf. - /// - public byte Version { - get { - return version; - } - } - - /// - /// Reads RectData from swf into a byte-array. - /// - /// - /// Since were only interested in bytecode actions, theres no need to parse this data. - /// - protected byte[] ReadRectData() { - - byte[] b = br.ReadBytes(17); // max. byte size of rect record - BitArray ba = BitParser.GetBitValues(b); - - int Nbits = (int)BitParser.ReadUInt32(ba,5); - int bitcount=5+Nbits*4; - int bytecount = Convert.ToInt32(Math.Ceiling((double)bitcount/8.0)); - - byte[] rect = new byte[bytecount]; - for (int i=0; i - /// Reads RectData from swf into a byte-array - /// - /// - /// Since were only interested in bytecode actions, theres no need to parse this data. - /// - protected byte[] ReadCXFormWithAlphaData() { - - byte[] b = br.ReadBytes(17); // max. byte size of transform record - BitArray ba = BitParser.GetBitValues(b); - - bool hasAdd = ba[0]; - bool hasMult = ba[1]; - - int Nbits = (int)BitParser.ReadUInt32(ba,2,4); - int bitcount = 6 + ( hasAdd ? Nbits*4 : 0) + ( hasMult ? Nbits*4 : 0); - - int bytecount = Convert.ToInt32(Math.Ceiling((double)bitcount/8.0)); - byte[] cfa = new byte[bytecount]; - for (int i=0; i - /// Reads MatrixData from swf into a byte-array - /// - /// - /// Since were only interested in bytecode actions, theres no need to parse this data. - /// - protected byte[] ReadMatrixData() { - - byte[] b = br.ReadBytes(27); // max. byte size of matrix record - BitArray ba = BitParser.GetBitValues(b); - - int bitcount = 1; - int Nbits; - - if (ba[bitcount-1]) { - Nbits = (int)BitParser.ReadUInt32(ba,bitcount,5); - bitcount+=5+Nbits*2; - } - bitcount+=1; - if (ba[bitcount-1]) { - Nbits = (int)BitParser.ReadUInt32(ba,bitcount,5); - bitcount+=5+Nbits*2; - } - Nbits = (int)BitParser.ReadUInt32(ba,bitcount,5); - bitcount+=5+Nbits*2; - int bytecount = Convert.ToInt32(Math.Ceiling((double)bitcount/8.0)); - byte[] matrix = new byte[bytecount]; - for (int i=0; i - /// Reads and parses swf header information into an instance of SwfHeader - /// - protected SwfHeader ReadHeader() { - - SwfHeader h = new SwfHeader( - br.ReadChars(3), - br.ReadByte(), - br.ReadUInt32(), - this.ReadRectData(), - br.ReadUInt16(), - br.ReadUInt16() - ); - - this.version = h.Version; - - return h; - } - - /// - /// Reads and parses tag header as RecordHeader - /// - protected RecordHeader ReadRecordHeader() { + + /// + /// Read only property; returns Flash version of the read swf. + /// + public byte Version { + get { + return version; + } + } + + /// + /// Reads RectData from swf into a byte-array. + /// + /// + /// Since were only interested in bytecode actions, theres no need to parse this data. + /// + protected byte[] ReadRectData() { + + byte[] b = br.ReadBytes(17); // max. byte size of rect record + BitArray ba = BitParser.GetBitValues(b); + + int Nbits = (int)BitParser.ReadUInt32(ba,5); + int bitcount=5+Nbits*4; + int bytecount = Convert.ToInt32(Math.Ceiling((double)bitcount/8.0)); + + byte[] rect = new byte[bytecount]; + for (int i=0; i + /// Reads RectData from swf into a byte-array + /// + /// + /// Since were only interested in bytecode actions, theres no need to parse this data. + /// + protected byte[] ReadCXFormWithAlphaData() { + + byte[] b = br.ReadBytes(17); // max. byte size of transform record + BitArray ba = BitParser.GetBitValues(b); + + bool hasAdd = ba[0]; + bool hasMult = ba[1]; + + int Nbits = (int)BitParser.ReadUInt32(ba,2,4); + int bitcount = 6 + ( hasAdd ? Nbits*4 : 0) + ( hasMult ? Nbits*4 : 0); + + int bytecount = Convert.ToInt32(Math.Ceiling((double)bitcount/8.0)); + byte[] cfa = new byte[bytecount]; + for (int i=0; i + /// Reads MatrixData from swf into a byte-array + /// + /// + /// Since were only interested in bytecode actions, theres no need to parse this data. + /// + protected byte[] ReadMatrixData() { + + byte[] b = br.ReadBytes(27); // max. byte size of matrix record + BitArray ba = BitParser.GetBitValues(b); + + int bitcount = 1; + int Nbits; + + if (ba[bitcount-1]) { + Nbits = (int)BitParser.ReadUInt32(ba,bitcount,5); + bitcount+=5+Nbits*2; + } + bitcount+=1; + if (ba[bitcount-1]) { + Nbits = (int)BitParser.ReadUInt32(ba,bitcount,5); + bitcount+=5+Nbits*2; + } + Nbits = (int)BitParser.ReadUInt32(ba,bitcount,5); + bitcount+=5+Nbits*2; + int bytecount = Convert.ToInt32(Math.Ceiling((double)bitcount/8.0)); + byte[] matrix = new byte[bytecount]; + for (int i=0; i + /// Reads and parses swf header information into an instance of SwfHeader + /// + protected SwfHeader ReadHeader() { + + SwfHeader h = new SwfHeader( + br.ReadChars(3), + br.ReadByte(), + br.ReadUInt32(), + this.ReadRectData(), + br.ReadUInt16(), + br.ReadUInt16() + ); + + this.version = h.Version; + + return h; + } + + /// + /// Reads and parses tag header as RecordHeader + /// + protected RecordHeader ReadRecordHeader() { if (br.BaseStream.Position >= streamEnd-2) return new RecordHeader(0, 2, false); - UInt16 tagCL = br.ReadUInt16(); - UInt16 tagCode = Convert.ToUInt16(tagCL>>6); - int tagLength = Convert.ToInt32(tagCL - (tagCode<<6)); - - bool longTag; - - if (tagLength == 0x3F) { - uint len = br.ReadUInt32(); - tagLength = Convert.ToInt32(len); - longTag = (tagLength <= 127); - } else { - longTag = false; - } - - if (tagLength>br.BaseStream.Length){ - throw new InvalidTagLengthException(); - } - - return new RecordHeader(tagCode,tagLength,longTag); - } - - /// - /// Reads and parses a ClipActionRec - /// - protected ClipActionRec ReadClipActionRec() { - - // different behaviour for Flash 5 and Flash 6+ - if (version>=6) { - if (br.ReadInt32()==0) { - return null; - } - br.BaseStream.Position -= 4; - } else { - if (br.ReadInt16()==0) { - return null; - } - br.BaseStream.Position -= 2; - } - - byte[] flags; - int size; - int keyCode; - byte[] actions; - - // different behaviour for Flash 5 and Flash 6+ - if (version>=6) { - - flags = br.ReadBytes(4); - - // swf events - byte f6Events = flags[2]; - bool hasKeyPress = ( (f6Events & 0x02) != 0); - bool hasConstruct = ( (f6Events & 0x04) != 0); // Flash 7 + - - size = br.ReadInt32(); - - if (hasKeyPress) { - keyCode = Convert.ToInt32(br.ReadByte()); - size--; - } else { keyCode = -1; } - - actions = br.ReadBytes(size); - - } else { - - flags = br.ReadBytes(2); - size = br.ReadInt32(); - keyCode = -1; - actions = br.ReadBytes(size); - } - - return new ClipActionRec(flags,keyCode,actions); - } - - /************************************************** - Read SWF Tags - **************************************************/ - - /// - /// Read and parse PlaceObject2Tag, leave non-bytecode data as raw byte-array - /// - protected PlaceObject2Tag ReadPlaceObject2Tag() { - - ReadRecordHeader(); - - // get flags - byte byte0 = br.ReadByte(); - BitArray flags = new BitArray(new byte[1]{byte0}); - BitParser.BytewiseReverse(flags); - - byte[] depth = br.ReadBytes(2); - byte[] chId; - byte[] matrix; - byte[] ctf; - byte[] ratio; - byte[] name; - byte[] clpd; - - bool hasActions; // even if length is 0 - byte[] actionHead; - - // contains byte code data - ClipActionRec[] clipActions; - - // read data, depending on flag settings - if (flags[6]) { - chId = br.ReadBytes(2); - } else { - chId = new byte[0]; - } - - if (flags[5]) { - matrix = ReadMatrixData(); - } else { - matrix = new byte[0]; - } - - if (flags[4]) { - ctf = ReadCXFormWithAlphaData(); - } else { - ctf = new byte[0]; - } - - if (flags[3]) { - ratio = br.ReadBytes(2); - } else { - ratio = new byte[0]; - } - - if (flags[2]) { - - // save stream position - long startStream = br.BaseStream.Position; - - // read characters - byte ch; - do { - ch=br.ReadByte(); - } while (ch!=0); - - // block length - int len = Convert.ToInt32(br.BaseStream.Position - startStream); - - // reset stream position - br.BaseStream.Position = startStream; - // read name - name = br.ReadBytes(len); - - } else { - name = new byte[0]; - } - - // clip id - if ( flags[1] ) { - clpd = br.ReadBytes(2); - } else { - clpd = new byte[0]; - } - - hasActions = flags[0]; - - // get bytecode actions - if (hasActions) { - - // different behaviour for Flash 6+ - actionHead = (version>=6) ? br.ReadBytes(6) : br.ReadBytes(4); - - // read clip action records to list - ArrayList clpAc = new ArrayList(); - - ClipActionRec a; - do { - a = ReadClipActionRec(); - if (a!=null) clpAc.Add(a); - - } while (a!=null); - - // copy list to array - clipActions = new ClipActionRec[clpAc.Count]; - clpAc.CopyTo(clipActions,0); - - } else { - // no actions -> null - return null; - } - - // tag-header (non-bytecode data before clipActionRec in tag) size varies with flags - int size = 3 // flags - +chId.Length - +matrix.Length - +ctf.Length - +ratio.Length - +name.Length - +clpd.Length - +actionHead.Length; - - byte[] header = new byte[size]; - int pos = 1; - - // copy all data to our tag-header array - header[0] = byte0; - depth.CopyTo(header,1); pos += depth.Length; - chId.CopyTo(header,pos); pos += chId.Length; - matrix.CopyTo(header,pos); pos += matrix.Length; - ctf.CopyTo(header,pos); pos += ctf.Length; - ratio.CopyTo(header,pos); pos += ratio.Length; - name.CopyTo(header,pos); pos += name.Length; - clpd.CopyTo(header,pos); pos += clpd.Length; - actionHead.CopyTo(header,pos); - - // return tag - return new PlaceObject2Tag(header,clipActions); - } - - /// - /// Read and parse DefineSpriteTag, into inner tags and raw byte-array header data - /// - protected DefineSpriteTag ReadDefineSpriteTag() { - - RecordHeader rh = ReadRecordHeader(); - - // inner tags - ArrayList tagList = new ArrayList(); + UInt16 tagCL = br.ReadUInt16(); + UInt16 tagCode = Convert.ToUInt16(tagCL>>6); + int tagLength = Convert.ToInt32(tagCL - (tagCode<<6)); + + bool longTag; + + if (tagLength == 0x3F) { + uint len = br.ReadUInt32(); + tagLength = Convert.ToInt32(len); + longTag = (tagLength <= 127); + } else { + longTag = false; + } + + if (tagLength>br.BaseStream.Length){ + throw new InvalidTagLengthException(); + } + + return new RecordHeader(tagCode,tagLength,longTag); + } + + /// + /// Reads and parses a ClipActionRec + /// + protected ClipActionRec ReadClipActionRec() { + + // different behaviour for Flash 5 and Flash 6+ + if (version>=6) { + if (br.ReadInt32()==0) { + return null; + } + br.BaseStream.Position -= 4; + } else { + if (br.ReadInt16()==0) { + return null; + } + br.BaseStream.Position -= 2; + } + + byte[] flags; + int size; + int keyCode; + byte[] actions; + + // different behaviour for Flash 5 and Flash 6+ + if (version>=6) { + + flags = br.ReadBytes(4); + + // swf events + byte f6Events = flags[2]; + bool hasKeyPress = ( (f6Events & 0x02) != 0); + bool hasConstruct = ( (f6Events & 0x04) != 0); // Flash 7 + + + size = br.ReadInt32(); + + if (hasKeyPress) { + keyCode = Convert.ToInt32(br.ReadByte()); + size--; + } else { keyCode = -1; } + + actions = br.ReadBytes(size); + + } else { + + flags = br.ReadBytes(2); + size = br.ReadInt32(); + keyCode = -1; + actions = br.ReadBytes(size); + } + + return new ClipActionRec(flags,keyCode,actions); + } + + /************************************************** + Read SWF Tags + **************************************************/ + + /// + /// Read and parse PlaceObject2Tag, leave non-bytecode data as raw byte-array + /// + protected PlaceObject2Tag ReadPlaceObject2Tag() { + + ReadRecordHeader(); + + // get flags + byte byte0 = br.ReadByte(); + BitArray flags = new BitArray(new byte[1]{byte0}); + BitParser.BytewiseReverse(flags); + + byte[] depth = br.ReadBytes(2); + byte[] chId; + byte[] matrix; + byte[] ctf; + byte[] ratio; + byte[] name; + byte[] clpd; + + bool hasActions; // even if length is 0 + byte[] actionHead; + + // contains byte code data + ClipActionRec[] clipActions; + + // read data, depending on flag settings + if (flags[6]) { + chId = br.ReadBytes(2); + } else { + chId = new byte[0]; + } + + if (flags[5]) { + matrix = ReadMatrixData(); + } else { + matrix = new byte[0]; + } + + if (flags[4]) { + ctf = ReadCXFormWithAlphaData(); + } else { + ctf = new byte[0]; + } + + if (flags[3]) { + ratio = br.ReadBytes(2); + } else { + ratio = new byte[0]; + } + + if (flags[2]) { + + // save stream position + long startStream = br.BaseStream.Position; + + // read characters + byte ch; + do { + ch=br.ReadByte(); + } while (ch!=0); + + // block length + int len = Convert.ToInt32(br.BaseStream.Position - startStream); + + // reset stream position + br.BaseStream.Position = startStream; + // read name + name = br.ReadBytes(len); + + } else { + name = new byte[0]; + } + + // clip id + if ( flags[1] ) { + clpd = br.ReadBytes(2); + } else { + clpd = new byte[0]; + } + + hasActions = flags[0]; + + // get bytecode actions + if (hasActions) { + + // different behaviour for Flash 6+ + actionHead = (version>=6) ? br.ReadBytes(6) : br.ReadBytes(4); + + // read clip action records to list + ArrayList clpAc = new ArrayList(); + + ClipActionRec a; + do { + a = ReadClipActionRec(); + if (a!=null) clpAc.Add(a); + + } while (a!=null); + + // copy list to array + clipActions = new ClipActionRec[clpAc.Count]; + clpAc.CopyTo(clipActions,0); + + } else { + // no actions -> null + return null; + } + + // tag-header (non-bytecode data before clipActionRec in tag) size varies with flags + int size = 3 // flags + +chId.Length + +matrix.Length + +ctf.Length + +ratio.Length + +name.Length + +clpd.Length + +actionHead.Length; + + byte[] header = new byte[size]; + int pos = 1; + + // copy all data to our tag-header array + header[0] = byte0; + depth.CopyTo(header,1); pos += depth.Length; + chId.CopyTo(header,pos); pos += chId.Length; + matrix.CopyTo(header,pos); pos += matrix.Length; + ctf.CopyTo(header,pos); pos += ctf.Length; + ratio.CopyTo(header,pos); pos += ratio.Length; + name.CopyTo(header,pos); pos += name.Length; + clpd.CopyTo(header,pos); pos += clpd.Length; + actionHead.CopyTo(header,pos); + + // return tag + return new PlaceObject2Tag(header,clipActions); + } + + /// + /// Read and parse DefineSpriteTag, into inner tags and raw byte-array header data + /// + protected DefineSpriteTag ReadDefineSpriteTag() { + + RecordHeader rh = ReadRecordHeader(); + + // inner tags + ArrayList tagList = new ArrayList(); long endPos = br.BaseStream.Position + rh.TagLength; - // stuff before inner tags, just read it and dont look any further + // stuff before inner tags, just read it and dont look any further byte[] header = br.ReadBytes(4); - - while (br.BaseStream.Position - /// Read and parse InitActionTag, containing sprite ID and bytecode - /// - protected InitActionTag ReadInitActionTag() { - - RecordHeader rh = ReadRecordHeader(); - - ushort spriteId = br.ReadUInt16(); - byte[] actionList = br.ReadBytes(rh.TagLength-2); - - return new InitActionTag(spriteId,actionList); - } - - /// - /// Read and parse DoActionTag, contains only bytecode - /// - protected DoActionTag ReadDoActionTag() { - - RecordHeader rh = ReadRecordHeader(); - - byte[] actionList = br.ReadBytes(rh.TagLength); - - return new DoActionTag(actionList); - } - - /// - /// Read and parse ScriptLimitTag - /// - protected ScriptLimitTag ReadScriptLimitTag() { - - RecordHeader rh = ReadRecordHeader(); - - ushort maxRecursionDepth = br.ReadUInt16(); - ushort scriptTimeOut = br.ReadUInt16(); - - return new ScriptLimitTag(maxRecursionDepth,scriptTimeOut); - } - - /// - /// Read and parse JpegTableTag - /// - protected JpegTableTag ReadJpegTableTag() { - - RecordHeader rh = ReadRecordHeader(); - int tl = rh.TagLength; - byte[] data = br.ReadBytes(tl); - - return new JpegTableTag(data); - } - - /// - /// Read and parse DefineBitsTag - /// - protected DefineBitsTag ReadDefineBitsTag() { - - RecordHeader rh = ReadRecordHeader(); - int tl = rh.TagLength; - ushort id = br.ReadUInt16(); - byte[] data = br.ReadBytes(tl-2); - return new DefineBitsTag(id,data); - } - - /// - /// Read and parse DefineBitsJpeg2Tag - /// - protected DefineBitsJpeg2Tag ReadDefineBitsJpeg2Tag() { - - RecordHeader rh = ReadRecordHeader(); - int tl = rh.TagLength; - ushort id = br.ReadUInt16(); - byte[] data = br.ReadBytes(tl-2); - return new DefineBitsJpeg2Tag(id,data); - } - - /// - /// Read and parse DefineBitsJpeg3Tag - /// - protected DefineBitsJpeg3Tag ReadDefineBitsJpeg3Tag() { - - RecordHeader rh = ReadRecordHeader(); - int tl = rh.TagLength; - ushort id = br.ReadUInt16(); - int imgLen = Convert.ToInt32(br.ReadUInt32()); - byte[] img = br.ReadBytes(imgLen); - byte[] alpha = br.ReadBytes(tl-6-imgLen); - - return new DefineBitsJpeg3Tag(id,img,alpha); + } + + /// + /// Read and parse InitActionTag, containing sprite ID and bytecode + /// + protected InitActionTag ReadInitActionTag() { + + RecordHeader rh = ReadRecordHeader(); + + ushort spriteId = br.ReadUInt16(); + byte[] actionList = br.ReadBytes(rh.TagLength-2); + + return new InitActionTag(spriteId,actionList); + } + + /// + /// Read and parse DoActionTag, contains only bytecode + /// + protected DoActionTag ReadDoActionTag() { + + RecordHeader rh = ReadRecordHeader(); + + byte[] actionList = br.ReadBytes(rh.TagLength); + + return new DoActionTag(actionList); + } + + /// + /// Read and parse ScriptLimitTag + /// + protected ScriptLimitTag ReadScriptLimitTag() { + + RecordHeader rh = ReadRecordHeader(); + + ushort maxRecursionDepth = br.ReadUInt16(); + ushort scriptTimeOut = br.ReadUInt16(); + + return new ScriptLimitTag(maxRecursionDepth,scriptTimeOut); + } + + /// + /// Read and parse JpegTableTag + /// + protected JpegTableTag ReadJpegTableTag() { + + RecordHeader rh = ReadRecordHeader(); + int tl = rh.TagLength; + byte[] data = br.ReadBytes(tl); + + return new JpegTableTag(data); + } + + /// + /// Read and parse DefineBitsTag + /// + protected DefineBitsTag ReadDefineBitsTag() { + + RecordHeader rh = ReadRecordHeader(); + int tl = rh.TagLength; + ushort id = br.ReadUInt16(); + byte[] data = br.ReadBytes(tl-2); + return new DefineBitsTag(id,data); + } + + /// + /// Read and parse DefineBitsJpeg2Tag + /// + protected DefineBitsJpeg2Tag ReadDefineBitsJpeg2Tag() { + + RecordHeader rh = ReadRecordHeader(); + int tl = rh.TagLength; + ushort id = br.ReadUInt16(); + byte[] data = br.ReadBytes(tl-2); + return new DefineBitsJpeg2Tag(id,data); + } + + /// + /// Read and parse DefineBitsJpeg3Tag + /// + protected DefineBitsJpeg3Tag ReadDefineBitsJpeg3Tag() { + + RecordHeader rh = ReadRecordHeader(); + int tl = rh.TagLength; + ushort id = br.ReadUInt16(); + int imgLen = Convert.ToInt32(br.ReadUInt32()); + byte[] img = br.ReadBytes(imgLen); + byte[] alpha = br.ReadBytes(tl-6-imgLen); + + return new DefineBitsJpeg3Tag(id,img,alpha); } /// @@ -500,7 +500,7 @@ protected DefineSoundTag ReadDefineSoundTag() byte[] data = br.ReadBytes(tl - 2); return new DefineSoundTag(id, data); } - + protected BaseTag ReadExportTag(int offset) { @@ -530,34 +530,34 @@ protected string ReadString() return sb.ToString(); } - /// - /// Read tag from swf input stream, non-bytecode tags are reads into base tags and wont get parsed - /// - virtual protected BaseTag ReadTag() { - - long posBefore = br.BaseStream.Position; - RecordHeader rh = ReadRecordHeader(); - int offset = (int)(br.BaseStream.Position-posBefore); - br.BaseStream.Position = posBefore; - switch (rh.TagCode) { - - case (int)TagCodeEnum.DefineSprite: return this.ReadDefineSpriteTag(); - - case (int)TagCodeEnum.DoAction: return this.ReadDoActionTag(); - - case (int)TagCodeEnum.InitAction: return this.ReadInitActionTag(); - - case (int)TagCodeEnum.ScriptLimit: return this.ReadScriptLimitTag(); - - case (int)TagCodeEnum.PlaceObject2: - - PlaceObject2Tag p = this.ReadPlaceObject2Tag(); - if (p==null) { - br.BaseStream.Position = posBefore; - return new BaseTag(br.ReadBytes(rh.TagLength+offset)); - } else { - return p; - } + /// + /// Read tag from swf input stream, non-bytecode tags are reads into base tags and wont get parsed + /// + virtual protected BaseTag ReadTag() { + + long posBefore = br.BaseStream.Position; + RecordHeader rh = ReadRecordHeader(); + int offset = (int)(br.BaseStream.Position-posBefore); + br.BaseStream.Position = posBefore; + switch (rh.TagCode) { + + case (int)TagCodeEnum.DefineSprite: return this.ReadDefineSpriteTag(); + + case (int)TagCodeEnum.DoAction: return this.ReadDoActionTag(); + + case (int)TagCodeEnum.InitAction: return this.ReadInitActionTag(); + + case (int)TagCodeEnum.ScriptLimit: return this.ReadScriptLimitTag(); + + case (int)TagCodeEnum.PlaceObject2: + + PlaceObject2Tag p = this.ReadPlaceObject2Tag(); + if (p==null) { + br.BaseStream.Position = posBefore; + return new BaseTag(br.ReadBytes(rh.TagLength+offset)); + } else { + return p; + } case (int)TagCodeEnum.DefineBits: case (int)TagCodeEnum.DefineBitsLossless: @@ -592,89 +592,89 @@ virtual protected BaseTag ReadTag() { } br.BaseStream.Position = posBefore; return new BaseTag(br.ReadBytes(rh.TagLength + offset));*/ - - default: + + default: return new BaseTag(br.ReadBytes(rh.TagLength + offset), rh.TagCode); - } - - } - - /// - /// Inflate compressed swf - /// - protected void inflate() - { - - // read size - br.BaseStream.Position = 4; // skip signature - int size = Convert.ToInt32(br.ReadUInt32()); - - // read swf head - byte[] uncompressed = new byte[size]; - br.BaseStream.Position = 0; - br.Read(uncompressed, 0, 8); // header data is not compre - - // un-zip - byte[] compressed = br.ReadBytes(size); - Inflater zipInflator = new Inflater(); - zipInflator.SetInput(compressed); - zipInflator.Inflate(uncompressed, 8, size - 8); - - // new memory stream for uncompressed swf - MemoryStream m = new MemoryStream(uncompressed); - br = new BinaryReader(m); - br.BaseStream.Position = 0; - } - - /// - /// Uncompress LZMA compressed swf - /// - protected void inflateLZMA() - { - - // read size - br.BaseStream.Position = 4; // skip signature - int size = Convert.ToInt32(br.ReadUInt32()); // uncompressed size - int compressedSize = Convert.ToInt32(br.ReadUInt32()); // compressed size - - // read swf head - byte[] uncompressed = new byte[size]; - br.BaseStream.Position = 0; - br.Read(uncompressed, 0, 8); // header data (signature and uncompressed size) is not compressed - br.BaseStream.Position = 12; // skip compressed size - - byte[] properties = br.ReadBytes(5); - byte[] compressed = br.ReadBytes(compressedSize); - - SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); - decoder.SetDecoderProperties(properties); - // new memory stream for uncompressed swf - MemoryStream m = new MemoryStream(uncompressed); - - m.Position = 8; - decoder.Code(new MemoryStream(compressed), m, compressedSize, size-8, null); - - br = new BinaryReader(m); - br.BaseStream.Position = 0; - } - - /// - /// Read swf (header and tags), this is the only public method of SwfReader - /// - public Swf ReadSwf() { - - // compressed swf? - if (br.PeekChar()=='C') { - inflate(); - } - else if (br.PeekChar() == 'Z') { - inflateLZMA(); - } - - SwfHeader header = ReadHeader(); - this.version = header.Version; - - ArrayList tagList = new ArrayList(); + } + + } + + /// + /// Inflate compressed swf + /// + protected void inflate() + { + + // read size + br.BaseStream.Position = 4; // skip signature + int size = Convert.ToInt32(br.ReadUInt32()); + + // read swf head + byte[] uncompressed = new byte[size]; + br.BaseStream.Position = 0; + br.Read(uncompressed, 0, 8); // header data is not compre + + // un-zip + byte[] compressed = br.ReadBytes(size); + Inflater zipInflator = new Inflater(); + zipInflator.SetInput(compressed); + zipInflator.Inflate(uncompressed, 8, size - 8); + + // new memory stream for uncompressed swf + MemoryStream m = new MemoryStream(uncompressed); + br = new BinaryReader(m); + br.BaseStream.Position = 0; + } + + /// + /// Uncompress LZMA compressed swf + /// + protected void inflateLZMA() + { + + // read size + br.BaseStream.Position = 4; // skip signature + int size = Convert.ToInt32(br.ReadUInt32()); // uncompressed size + int compressedSize = Convert.ToInt32(br.ReadUInt32()); // compressed size + + // read swf head + byte[] uncompressed = new byte[size]; + br.BaseStream.Position = 0; + br.Read(uncompressed, 0, 8); // header data (signature and uncompressed size) is not compressed + br.BaseStream.Position = 12; // skip compressed size + + byte[] properties = br.ReadBytes(5); + byte[] compressed = br.ReadBytes(compressedSize); + + SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); + decoder.SetDecoderProperties(properties); + // new memory stream for uncompressed swf + MemoryStream m = new MemoryStream(uncompressed); + + m.Position = 8; + decoder.Code(new MemoryStream(compressed), m, compressedSize, size-8, null); + + br = new BinaryReader(m); + br.BaseStream.Position = 0; + } + + /// + /// Read swf (header and tags), this is the only public method of SwfReader + /// + public Swf ReadSwf() { + + // compressed swf? + if (br.PeekChar()=='C') { + inflate(); + } + else if (br.PeekChar() == 'Z') { + inflateLZMA(); + } + + SwfHeader header = ReadHeader(); + this.version = header.Version; + + ArrayList tagList = new ArrayList(); try { @@ -689,20 +689,20 @@ public Swf ReadSwf() { { Console.WriteLine("-- Error: Tag reader error: [" + eos.Message + "]"); } - - BaseTag[] tags = new BaseTag[tagList.Count]; - tagList.CopyTo(tags,0); - br.Close(); - - return new Swf(header,tags); - } - - /// - /// Swf Reader class, takes an input stream as single argument - /// - /// Stream to read swf from, must allow random access - public SwfReader(Stream stream) { - this.br = new BinaryReader(stream); - } - } + + BaseTag[] tags = new BaseTag[tagList.Count]; + tagList.CopyTo(tags,0); + br.Close(); + + return new Swf(header,tags); + } + + /// + /// Swf Reader class, takes an input stream as single argument + /// + /// Stream to read swf from, must allow random access + public SwfReader(Stream stream) { + this.br = new BinaryReader(stream); + } + } } diff --git a/External/Tools/SwfOp/IO/SwfWriter.cs b/External/Tools/SwfOp/IO/SwfWriter.cs index ad813454b8..f7a6a228b7 100644 --- a/External/Tools/SwfOp/IO/SwfWriter.cs +++ b/External/Tools/SwfOp/IO/SwfWriter.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -27,63 +27,63 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.IO { - /// - /// SwfWriter writes an swf to a stream using the Write method. - /// - public class SwfWriter { - - /// - /// BaseStream where swf gets written to using Write(..) - /// - private Stream baseStream; - - /// - /// Writes the (compressed or uncompressed) swf data to a stream. - /// The stream gets flushed and closed afterwards. - /// - public void Write(Swf swf) { - - swf.UpdateData(); // update tag lengths to adapt to bytecode length - SwfHeader header = swf.Header; + /// + /// SwfWriter writes an swf to a stream using the Write method. + /// + public class SwfWriter { + + /// + /// BaseStream where swf gets written to using Write(..) + /// + private Stream baseStream; + + /// + /// Writes the (compressed or uncompressed) swf data to a stream. + /// The stream gets flushed and closed afterwards. + /// + public void Write(Swf swf) { + + swf.UpdateData(); // update tag lengths to adapt to bytecode length + SwfHeader header = swf.Header; - BinaryWriter writer = new BinaryWriter(baseStream,System.Text.Encoding.GetEncoding("ascii")); // ASCII seems to be ok for Flash 5 and 6+ as well - BinaryWriter dataWriter = writer; + BinaryWriter writer = new BinaryWriter(baseStream,System.Text.Encoding.GetEncoding("ascii")); // ASCII seems to be ok for Flash 5 and 6+ as well + BinaryWriter dataWriter = writer; - bool isCompressed = (header.Signature[0]=='C'); - - if (isCompressed) { - // SharpZipLib makes it easy for us, simply chain a Deflater into the stream - DeflaterOutputStream def = new DeflaterOutputStream(baseStream); - dataWriter = new BinaryWriter(def); - } - - // writer header data, always uncompressed - writer.Write(header.Signature); - writer.Write(swf.Version); - writer.Write(swf.ByteCount); - writer.Flush(); - - // write header data pt.2, using either original stream or deflater stream - dataWriter.Write(header.Rect); - dataWriter.Write(header.Fps); - dataWriter.Write(header.Frames); - - // write tag data - foreach (BaseTag tag in swf) { - dataWriter.Write(tag.Data); - } - - // flush + close - dataWriter.Flush(); - dataWriter.Close(); - } - - /// - /// constructor. - /// - /// Stream, the swf shall be written to. - public SwfWriter(Stream stream) { - baseStream = stream; - } - } + bool isCompressed = (header.Signature[0]=='C'); + + if (isCompressed) { + // SharpZipLib makes it easy for us, simply chain a Deflater into the stream + DeflaterOutputStream def = new DeflaterOutputStream(baseStream); + dataWriter = new BinaryWriter(def); + } + + // writer header data, always uncompressed + writer.Write(header.Signature); + writer.Write(swf.Version); + writer.Write(swf.ByteCount); + writer.Flush(); + + // write header data pt.2, using either original stream or deflater stream + dataWriter.Write(header.Rect); + dataWriter.Write(header.Fps); + dataWriter.Write(header.Frames); + + // write tag data + foreach (BaseTag tag in swf) { + dataWriter.Write(tag.Data); + } + + // flush + close + dataWriter.Flush(); + dataWriter.Close(); + } + + /// + /// constructor. + /// + /// Stream, the swf shall be written to. + public SwfWriter(Stream stream) { + baseStream = stream; + } + } } diff --git a/External/Tools/SwfOp/License.cs b/External/Tools/SwfOp/License.cs index 1481ec865a..e903562066 100644 --- a/External/Tools/SwfOp/License.cs +++ b/External/Tools/SwfOp/License.cs @@ -1,6 +1,6 @@ /* - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA @@ -11,7 +11,7 @@ [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] - Preamble + Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public @@ -113,7 +113,7 @@ modification follow. Pay close attention to the difference between a former contains code derived from the library, whereas the latter must be combined with the library in order to run. - GNU LESSER GENERAL PUBLIC LICENSE + GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other @@ -433,7 +433,7 @@ decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - NO WARRANTY + NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. @@ -456,5 +456,5 @@ RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - END OF TERMS AND CONDITIONS + END OF TERMS AND CONDITIONS */ \ No newline at end of file diff --git a/External/Tools/SwfOp/PokeSwf.cs b/External/Tools/SwfOp/PokeSwf.cs index 382e705705..8b01538b86 100644 --- a/External/Tools/SwfOp/PokeSwf.cs +++ b/External/Tools/SwfOp/PokeSwf.cs @@ -17,31 +17,31 @@ namespace SwfOp { - /// - /// C:\as3\projets\MonProjet\deploy\App.swf + /// + /// C:\as3\projets\MonProjet\deploy\App.swf /// C:\as3\projets\MonProjet\App2.swf /// C:\flex_sdk_2\frameworks\libs\framework.swc /// C:\flex_sdk_2\frameworks\libs\playerglobal.swc /// C:\as3\library\ImageProcessing.swc /// C:\as3\corelib\bin\corelib.swc - /// - public class PokeSwf - { + /// + public class PokeSwf + { static string operation; - public static void Main(string[] args) - { - if (args.Length < 1) - { - Console.WriteLine("SwfOp : list all library symbols of the SWF"); + public static void Main(string[] args) + { + if (args.Length < 1) + { + Console.WriteLine("SwfOp : list all library symbols of the SWF"); return; - } + } string filename = args[args.Length-1]; operation = (args.Length > 1) ? args[0] : "-list"; - - // read SWF - try - { + + // read SWF + try + { Stream filestream = File.OpenRead(filename); // SWC file: extract 'library.swf' file @@ -72,17 +72,17 @@ public static void Main(string[] args) } // regular SWF else ExploreSWF(new BufferedStream(filestream)); - } - catch(FileNotFoundException) - { - Console.WriteLine("-- SwfOp Error: File not found"); - } - catch(Exception ex) - { - Console.WriteLine("-- SwfOp Error: "+ex.Message); - } + } + catch(FileNotFoundException) + { + Console.WriteLine("-- SwfOp Error: File not found"); + } + catch(Exception ex) + { + Console.WriteLine("-- SwfOp Error: "+ex.Message); + } Console.ReadLine(); - } + } private static byte[] UnzipFile(ZipFile zfile, ZipEntry entry) { @@ -93,9 +93,9 @@ private static byte[] UnzipFile(ZipFile zfile, ZipEntry entry) throw new Exception("Corrupted archive"); return data; } - - static void ExploreSWF(Stream stream) - { + + static void ExploreSWF(Stream stream) + { if (stream == null) return; SwfReader reader = new SwfReader(stream); //SwfExportTagReader reader = new SwfExportTagReader(stream); @@ -139,7 +139,7 @@ static void ExploreSWF(Stream stream) { Console.WriteLine("-- Swf error: " + ex.Message); } - } + } private static BaseTag FindObject(Swf swf, ushort id) { @@ -152,5 +152,5 @@ private static BaseTag FindObject(Swf swf, ushort id) } return null; } - } + } } diff --git a/External/Tools/SwfOp/SwfOp.csproj b/External/Tools/SwfOp/SwfOp.csproj index b3df105aa2..5a4d3c8908 100644 --- a/External/Tools/SwfOp/SwfOp.csproj +++ b/External/Tools/SwfOp/SwfOp.csproj @@ -1,10 +1,8 @@  - + Debug AnyCPU - 9.0.21022 - 2.0 {DFFCFF12-CB60-4748-8F23-0C36F140F44C} Library Properties @@ -14,8 +12,11 @@ - 3.5 - v2.0 + net48 + true + false + false + false false @@ -33,6 +34,7 @@ 1.0.0.%2a false true + false @@ -67,14 +69,6 @@ x86 prompt - - diff --git a/External/Tools/SwfOp/SwfOp.sln b/External/Tools/SwfOp/SwfOp.sln index c83a24f92e..aaab551fcb 100644 --- a/External/Tools/SwfOp/SwfOp.sln +++ b/External/Tools/SwfOp/SwfOp.sln @@ -1,6 +1,8 @@  -Microsoft Visual Studio Solution File, Format Version 10.00 -# Visual C# Express 2008 +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 14 +VisualStudioVersion = 14.0.23107.0 +MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SwfOp", "SwfOp.csproj", "{DFFCFF12-CB60-4748-8F23-0C36F140F44C}" EndProject Global diff --git a/External/Tools/SwfOp/Utils/BinaryStringRW.cs b/External/Tools/SwfOp/Utils/BinaryStringRW.cs index ce39079c40..b328eca6fa 100644 --- a/External/Tools/SwfOp/Utils/BinaryStringRW.cs +++ b/External/Tools/SwfOp/Utils/BinaryStringRW.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System.IO; @@ -25,39 +25,39 @@ You should have received a copy of the GNU Lesser General Public namespace SwfOp.Utils { - /// - /// A helper class for reading/writing zero-byte terminated strings - /// - public class BinaryStringRW { + /// + /// A helper class for reading/writing zero-byte terminated strings + /// + public class BinaryStringRW { - /// - /// Read zero-byte terminated string with a BinaryReader - /// - public static string ReadString(BinaryReader br) { - - StringBuilder sb = new StringBuilder(""); - byte b = br.ReadByte(); - while (b>0){ - sb.Append(Convert.ToChar(b)); - b = br.ReadByte(); - }; - return sb.ToString(); - } + /// + /// Read zero-byte terminated string with a BinaryReader + /// + public static string ReadString(BinaryReader br) { + + StringBuilder sb = new StringBuilder(""); + byte b = br.ReadByte(); + while (b>0){ + sb.Append(Convert.ToChar(b)); + b = br.ReadByte(); + }; + return sb.ToString(); + } - /// - /// Write zero-byte terminated string with a BinaryWriter - /// - public static void WriteString(BinaryWriter w,string str) { - - char[] ch = new char[str.Length]; - str.CopyTo(0,ch,0,str.Length); - w.Write(ch); - w.Write((byte)0); - } + /// + /// Write zero-byte terminated string with a BinaryWriter + /// + public static void WriteString(BinaryWriter w,string str) { + + char[] ch = new char[str.Length]; + str.CopyTo(0,ch,0,str.Length); + w.Write(ch); + w.Write((byte)0); + } - /// - /// Hidden constructor, class is only used in static context. - /// - private BinaryStringRW() {} - } + /// + /// Hidden constructor, class is only used in static context. + /// + private BinaryStringRW() {} + } } diff --git a/External/Tools/SwfOp/Utils/BitParser.cs b/External/Tools/SwfOp/Utils/BitParser.cs index 31d1bfe3c6..779723240a 100644 --- a/External/Tools/SwfOp/Utils/BitParser.cs +++ b/External/Tools/SwfOp/Utils/BitParser.cs @@ -1,22 +1,22 @@ /* - swfOP is an open source library for manipulation and examination of - Macromedia Flash (SWF) ActionScript bytecode. - Copyright (C) 2004 Florian Krüsch. - see Licence.cs for LGPL full text! - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library 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 - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + swfOP is an open source library for manipulation and examination of + Macromedia Flash (SWF) ActionScript bytecode. + Copyright (C) 2004 Florian Krüsch. + see Licence.cs for LGPL full text! + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; @@ -25,130 +25,130 @@ You should have received a copy of the GNU Lesser General Public using System.Collections.Specialized; namespace SwfOp.Utils { - - /// - /// A helper class with static methods for bit-parsing swf data - /// - public class BitParser { - - /// - /// List of int values for each bit; for fast access to BitVector32 sections - /// - private static int[] bitValueList = new int[32]; - - /// - /// Static constructor: initialize bitValueList - /// - static BitParser() { - - bitValueList[0] = BitVector32.CreateMask(); - - for (int i=1; i<32; i++) { - bitValueList[i] = BitVector32.CreateMask(bitValueList[i-1]); - } - } - - /// - /// Reverse bit order in each byte (8 bits) of a BitArray - /// (change endian bit order) - /// - public static void BytewiseReverse(BitArray bitArr) { - int byteCount = bitArr.Length/8; - for (int i=0; i - /// Prepare read bytes for bit parsing - /// - /// - /// Byte sequence read from swf by aBinaryReader - /// - public static BitArray GetBitValues(byte[] byteSequence) { - BitArray ba = new BitArray(byteSequence); - BytewiseReverse(ba); - return ba; - } - - /// - /// Overloaded static method - /// Converts part of a BitArray to a signed int32 - /// - /// source BitArray - /// start index - /// bit count - public static int ReadInt32(BitArray bitArr,int index,int length) { - - BitVector32 bitVec = new BitVector32(0); - for (int i=0; i - /// starts at index 0 - /// - /// source BitArray - /// bit count - public static int ReadInt32(BitArray bitArr,int length) { - return ReadInt32(bitArr,0,length); - } + + /// + /// A helper class with static methods for bit-parsing swf data + /// + public class BitParser { + + /// + /// List of int values for each bit; for fast access to BitVector32 sections + /// + private static int[] bitValueList = new int[32]; + + /// + /// Static constructor: initialize bitValueList + /// + static BitParser() { + + bitValueList[0] = BitVector32.CreateMask(); + + for (int i=1; i<32; i++) { + bitValueList[i] = BitVector32.CreateMask(bitValueList[i-1]); + } + } + + /// + /// Reverse bit order in each byte (8 bits) of a BitArray + /// (change endian bit order) + /// + public static void BytewiseReverse(BitArray bitArr) { + int byteCount = bitArr.Length/8; + for (int i=0; i + /// Prepare read bytes for bit parsing + /// + /// + /// Byte sequence read from swf by aBinaryReader + /// + public static BitArray GetBitValues(byte[] byteSequence) { + BitArray ba = new BitArray(byteSequence); + BytewiseReverse(ba); + return ba; + } + + /// + /// Overloaded static method + /// Converts part of a BitArray to a signed int32 + /// + /// source BitArray + /// start index + /// bit count + public static int ReadInt32(BitArray bitArr,int index,int length) { + + BitVector32 bitVec = new BitVector32(0); + for (int i=0; i + /// starts at index 0 + /// + /// source BitArray + /// bit count + public static int ReadInt32(BitArray bitArr,int length) { + return ReadInt32(bitArr,0,length); + } - /// - /// convert total BitArray - /// - /// source BitArray - public static int ReadInt32(BitArray bitArr) { - return ReadInt32(bitArr,0,bitArr.Length); - } - - /// - /// convert part of a BitArray to a unsigned integer (uint32) - /// - /// source BitArray - /// start index - /// bit count - public static int ReadUInt32(BitArray bitArr,int index,int length) { - - if (length>31) throw new ArgumentOutOfRangeException(); - - BitVector32 bitVec = new BitVector32(0); - for (int i=0; i - /// start at index 0 - /// - /// source BitArray - /// bit count - public static int ReadUInt32(BitArray bitArr,int length) { - return ReadUInt32(bitArr,0,length); - } + /// + /// convert total BitArray + /// + /// source BitArray + public static int ReadInt32(BitArray bitArr) { + return ReadInt32(bitArr,0,bitArr.Length); + } + + /// + /// convert part of a BitArray to a unsigned integer (uint32) + /// + /// source BitArray + /// start index + /// bit count + public static int ReadUInt32(BitArray bitArr,int index,int length) { + + if (length>31) throw new ArgumentOutOfRangeException(); + + BitVector32 bitVec = new BitVector32(0); + for (int i=0; i + /// start at index 0 + /// + /// source BitArray + /// bit count + public static int ReadUInt32(BitArray bitArr,int length) { + return ReadUInt32(bitArr,0,length); + } - /// - /// convert total BitArray - /// - /// source BitArray - public static int ReadUInt32(BitArray bitArr) { - return ReadUInt32(bitArr,0,bitArr.Length); - } - - /// - /// no public constructor, class is only used in static context - /// - private BitParser() {} - } - + /// + /// convert total BitArray + /// + /// source BitArray + public static int ReadUInt32(BitArray bitArr) { + return ReadUInt32(bitArr,0,bitArr.Length); + } + + /// + /// no public constructor, class is only used in static context + /// + private BitParser() {} + } + } diff --git a/FlashDevelop.sln b/FlashDevelop.sln index be7b815505..1bae82d463 100644 --- a/FlashDevelop.sln +++ b/FlashDevelop.sln @@ -1,345 +1,1082 @@  -Microsoft Visual Studio Solution File, Format Version 11.00 -# Visual C# Express 2010 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlashDevelop", "FlashDevelop\FlashDevelop.csproj", "{EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}" +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29021.104 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlashDevelop", "FlashDevelop\FlashDevelop.csproj", "{EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}" ProjectSection(ProjectDependencies) = postProject {61885F70-B4DC-4B44-852D-5D6D03F2A734} = {61885F70-B4DC-4B44-852D-5D6D03F2A734} EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PluginCore", "PluginCore\PluginCore.csproj", "{61885F70-B4DC-4B44-852D-5D6D03F2A734}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginCore", "PluginCore\PluginCore.csproj", "{61885F70-B4DC-4B44-852D-5D6D03F2A734}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FileExplorer", "External\Plugins\FileExplorer\FileExplorer.csproj", "{C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FileExplorer", "External\Plugins\FileExplorer\FileExplorer.csproj", "{C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlashConnect", "External\Plugins\FlashConnect\FlashConnect.csproj", "{D6AAF434-F4DF-4376-863D-109A8762CECA}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlashConnect", "External\Plugins\FlashConnect\FlashConnect.csproj", "{D6AAF434-F4DF-4376-863D-109A8762CECA}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlashViewer", "External\Plugins\FlashViewer\FlashViewer.csproj", "{3E8B5548-D3AB-44CD-8C1D-D828540D49C9}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlashViewer", "External\Plugins\FlashViewer\FlashViewer.csproj", "{3E8B5548-D3AB-44CD-8C1D-D828540D49C9}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OutputPanel", "External\Plugins\OutputPanel\OutputPanel.csproj", "{EF8EE44C-62B2-4744-85CB-278E1F37D418}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OutputPanel", "External\Plugins\OutputPanel\OutputPanel.csproj", "{EF8EE44C-62B2-4744-85CB-278E1F37D418}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResultsPanel", "External\Plugins\ResultsPanel\ResultsPanel.csproj", "{8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ResultsPanel", "External\Plugins\ResultsPanel\ResultsPanel.csproj", "{8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "XMLCompletion", "External\Plugins\XMLCompletion\XMLCompletion.csproj", "{556F43A0-C288-471A-8CD8-A787FC7ACA34}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "XMLCompletion", "External\Plugins\XMLCompletion\XMLCompletion.csproj", "{556F43A0-C288-471A-8CD8-A787FC7ACA34}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ASCompletion", "External\Plugins\ASCompletion\ASCompletion.csproj", "{4EBF2653-9654-4E40-880E-0046B3D6210E}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASCompletion", "External\Plugins\ASCompletion\ASCompletion.csproj", "{4EBF2653-9654-4E40-880E-0046B3D6210E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AS2Context", "External\Plugins\AS2Context\AS2Context.csproj", "{74AD0487-CEF9-43FE-9283-BC6F79539ADE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AS2Context", "External\Plugins\AS2Context\AS2Context.csproj", "{74AD0487-CEF9-43FE-9283-BC6F79539ADE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ProjectManager", "External\Plugins\ProjectManager\ProjectManager.csproj", "{78101C01-E186-4954-B1DD-DEBB7905FAD8}" - ProjectSection(ProjectDependencies) = postProject - {61885F70-B4DC-4B44-852D-5D6D03F2A734} = {61885F70-B4DC-4B44-852D-5D6D03F2A734} - EndProjectSection +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectManager", "External\Plugins\ProjectManager\ProjectManager.csproj", "{78101C01-E186-4954-B1DD-DEBB7905FAD8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LayoutManager", "External\Plugins\LayoutManager\LayoutManager.csproj", "{BD6AFBEA-DB64-432A-80F7-4672A7FF283E}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LayoutManager", "External\Plugins\LayoutManager\LayoutManager.csproj", "{BD6AFBEA-DB64-432A-80F7-4672A7FF283E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataEncoder", "External\Plugins\DataEncoder\DataEncoder.csproj", "{285FADFC-E221-4575-B9DD-42E452B4381F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DataEncoder", "External\Plugins\DataEncoder\DataEncoder.csproj", "{285FADFC-E221-4575-B9DD-42E452B4381F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AS3Context", "External\Plugins\AS3Context\AS3Context.csproj", "{0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}" - ProjectSection(ProjectDependencies) = postProject - {61885F70-B4DC-4B44-852D-5D6D03F2A734} = {61885F70-B4DC-4B44-852D-5D6D03F2A734} - EndProjectSection +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AS3Context", "External\Plugins\AS3Context\AS3Context.csproj", "{0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HaXeContext", "External\Plugins\HaXeContext\HaXeContext.csproj", "{5B4E9515-994A-4DA7-9916-CDA8FD874701}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HaXeContext", "External\Plugins\HaXeContext\HaXeContext.csproj", "{5B4E9515-994A-4DA7-9916-CDA8FD874701}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StartPage", "External\Plugins\StartPage\StartPage.csproj", "{DCEEBF26-BB93-45EE-8B00-32927A687761}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StartPage", "External\Plugins\StartPage\StartPage.csproj", "{DCEEBF26-BB93-45EE-8B00-32927A687761}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TaskListPanel", "External\Plugins\TaskListPanel\TaskListPanel.csproj", "{40FEAC2B-A68A-498E-AD78-52A8268EFA45}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TaskListPanel", "External\Plugins\TaskListPanel\TaskListPanel.csproj", "{40FEAC2B-A68A-498E-AD78-52A8268EFA45}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BookmarkPanel", "External\Plugins\BookmarkPanel\BookmarkPanel.csproj", "{FDF347DB-0577-43DD-A819-16C7F30B49A7}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BookmarkPanel", "External\Plugins\BookmarkPanel\BookmarkPanel.csproj", "{FDF347DB-0577-43DD-A819-16C7F30B49A7}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlashLogViewer", "External\Plugins\FlashLogViewer\FlashLogViewer.csproj", "{21912919-338F-431D-945B-F3C104A96B8E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlashLogViewer", "External\Plugins\FlashLogViewer\FlashLogViewer.csproj", "{21912919-338F-431D-945B-F3C104A96B8E}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MacroManager", "External\Plugins\MacroManager\MacroManager.csproj", "{E462A275-2DAF-411C-95ED-C6A35FEC29D8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MacroManager", "External\Plugins\MacroManager\MacroManager.csproj", "{E462A275-2DAF-411C-95ED-C6A35FEC29D8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASClassWizard", "External\Plugins\ASClassWizard\ASClassWizard.csproj", "{A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ASClassWizard", "External\Plugins\ASClassWizard\ASClassWizard.csproj", "{A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeRefactor", "External\Plugins\CodeRefactor\CodeRefactor.csproj", "{1F6DF858-6011-4CAC-B33E-7000EE90FFBE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeRefactor", "External\Plugins\CodeRefactor\CodeRefactor.csproj", "{1F6DF858-6011-4CAC-B33E-7000EE90FFBE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeAnalyzer", "External\Plugins\CodeAnalyzer\CodeAnalyzer.csproj", "{E4504497-89BF-4ED5-A0CC-6F02E96C2652}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeAnalyzer", "External\Plugins\CodeAnalyzer\CodeAnalyzer.csproj", "{E4504497-89BF-4ED5-A0CC-6F02E96C2652}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SourceControl", "External\Plugins\SourceControl\SourceControl.csproj", "{CDB62A9F-0887-43AE-815D-4593A8E35E44}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SourceControl", "External\Plugins\SourceControl\SourceControl.csproj", "{CDB62A9F-0887-43AE-815D-4593A8E35E44}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AirProperties", "External\Plugins\AirProperties\AirProperties.csproj", "{F2CED639-1DA7-489D-9DBB-909F7B590C3D}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AirProperties", "External\Plugins\AirProperties\AirProperties.csproj", "{F2CED639-1DA7-489D-9DBB-909F7B590C3D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeFormatter", "External\Plugins\CodeFormatter\CodeFormatter.csproj", "{B97FEDD3-8F61-4006-ACCD-AD735069B0CA}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CodeFormatter", "External\Plugins\CodeFormatter\CodeFormatter.csproj", "{B97FEDD3-8F61-4006-ACCD-AD735069B0CA}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BridgeSettings", "External\Plugins\BridgeSettings\BridgeSettings.csproj", "{3074D447-A469-4CA2-A7E5-FE53DB45CB11}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BridgeSettings", "External\Plugins\BridgeSettings\BridgeSettings.csproj", "{3074D447-A469-4CA2-A7E5-FE53DB45CB11}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PHPContext", "External\Plugins\PHPContext\PHPContext.csproj", "{2F93393B-9629-470E-B7B8-0D8CFA25315A}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PHPContext", "External\Plugins\PHPContext\PHPContext.csproj", "{2F93393B-9629-470E-B7B8-0D8CFA25315A}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlashDebugger", "External\Plugins\FlashDebugger\FlashDebugger.csproj", "{194B58C9-9D2B-4D5E-9256-773FD3222582}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BasicCompletion", "External\Plugins\BasicCompletion\BasicCompletion.csproj", "{DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CssCompletion", "External\Plugins\CssCompletion\CssCompletion.csproj", "{DCA7613E-7BC3-4610-A95E-73C0D64C5B98}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FDBuild", "External\Tools\FDBuild\FDBuild.csproj", "{FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}" + ProjectSection(ProjectDependencies) = postProject + {61885F70-B4DC-4B44-852D-5D6D03F2A734} = {61885F70-B4DC-4B44-852D-5D6D03F2A734} + EndProjectSection EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FlashDebugger", "External\Plugins\FlashDebugger\FlashDebugger.csproj", "{194B58C9-9D2B-4D5E-9256-773FD3222582}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ASCompletion.Tests", "Tests\External\Plugins\ASCompletion.Tests\ASCompletion.Tests.csproj", "{ABC71D26-295C-4C6C-B6DE-320AD49EEF79}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BasicCompletion", "External\Plugins\BasicCompletion\BasicCompletion.csproj", "{DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CodeRefactor.Tests", "Tests\External\Plugins\CodeRefactor.Tests\CodeRefactor.Tests.csproj", "{19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CssCompletion", "External\Plugins\CssCompletion\CssCompletion.csproj", "{DCA7613E-7BC3-4610-A95E-73C0D64C5B98}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PluginCore.Tests", "Tests\PluginCore\PluginCore.Tests\PluginCore.Tests.csproj", "{F44D3125-12E8-4143-B250-84C5D89D253C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LoomContext", "External\Plugins\LoomContext\LoomContext.csproj", "{92BBB3B6-E318-4B12-8378-6D46E69AB938}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LintingHelper", "External\Plugins\LintingHelper\LintingHelper.csproj", "{8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectManager.Tests", "Tests\External\Plugins\ProjectManager.Test\ProjectManager.Tests.csproj", "{F616101E-6103-4788-9382-964D0A1D0A09}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HaxeContext.Tests", "Tests\External\Plugins\HaxeContext.Tests\HaxeContext.Tests.csproj", "{B7E7E6B5-F1B1-4A44-9966-89AAA7579514}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AS3Context.Tests", "Tests\External\Plugins\AS3Context.Tests\AS3Context.Tests.csproj", "{536FDE15-CA93-4F84-B1FF-08126C3C443A}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HaxeTypeWizard", "External\Plugins\HaxeTypeWizard\HaxeTypeWizard.csproj", "{BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C714C81C-C491-42D7-AF9B-55A6E1F972FB}" + ProjectSection(SolutionItems) = preProject + .editorconfig = .editorconfig + appman.xml = appman.xml + EndProjectSection +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Settings", "Settings", "{9549C61A-B51B-4837-B113-0602354608B4}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Languages", "Languages", "{43B75BC7-8B9A-4211-BD98-B4B2DA9E4A25}" + ProjectSection(SolutionItems) = preProject + FlashDevelop\Bin\Debug\Settings\Languages\Haxe.xml = FlashDevelop\Bin\Debug\Settings\Languages\Haxe.xml + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "PreviousEdit", "External\Plugins\PreviousEdit\PreviousEdit.csproj", "{12FA6A8C-FDEB-41AC-BCB8-9269106105C8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 + Debug+Tests|Any CPU = Debug+Tests|Any CPU + Debug+Tests|x64 = Debug+Tests|x64 + Debug+Tests|x86 = Debug+Tests|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 Release|x86 = Release|x86 + Release+Tests|Any CPU = Release+Tests|Any CPU + Release+Tests|x64 = Release+Tests|x64 + Release+Tests|x86 = Release+Tests|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug|x64.ActiveCfg = Debug|x64 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug|x64.Build.0 = Debug|x64 {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug|x86.ActiveCfg = Debug|x86 {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug|x86.Build.0 = Debug|x86 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug+Tests|x64.ActiveCfg = Debug|x64 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug+Tests|x64.Build.0 = Debug|x64 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug+Tests|x86.ActiveCfg = Debug|x86 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Debug+Tests|x86.Build.0 = Debug|x86 {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release|Any CPU.ActiveCfg = Release|Any CPU {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release|Any CPU.Build.0 = Release|Any CPU + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release|x64.ActiveCfg = Release|x64 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release|x64.Build.0 = Release|x64 {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release|x86.ActiveCfg = Release|x86 {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release|x86.Build.0 = Release|x86 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release+Tests|x64.ActiveCfg = Release|x64 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release+Tests|x64.Build.0 = Release|x64 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release+Tests|x86.ActiveCfg = Release|x86 + {EFD07485-9A64-4EEC-94E7-ACBD4DA5CA93}.Release+Tests|x86.Build.0 = Release|x86 {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug|Any CPU.Build.0 = Debug|Any CPU - {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug|x86.ActiveCfg = Debug|x86 - {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug|x86.Build.0 = Debug|x86 + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug|x64.ActiveCfg = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug|x64.Build.0 = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug|x86.ActiveCfg = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug|x86.Build.0 = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Debug+Tests|x86.Build.0 = Debug|Any CPU {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release|Any CPU.ActiveCfg = Release|Any CPU {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release|Any CPU.Build.0 = Release|Any CPU - {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release|x86.ActiveCfg = Release|x86 - {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release|x86.Build.0 = Release|x86 + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release|x64.ActiveCfg = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release|x64.Build.0 = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release|x86.ActiveCfg = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release|x86.Build.0 = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release+Tests|x64.Build.0 = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {61885F70-B4DC-4B44-852D-5D6D03F2A734}.Release+Tests|x86.Build.0 = Release|Any CPU {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug|x86.ActiveCfg = Debug|x86 - {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug|x86.Build.0 = Debug|x86 + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug|x64.ActiveCfg = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug|x64.Build.0 = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug|x86.ActiveCfg = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug|x86.Build.0 = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Debug+Tests|x86.Build.0 = Debug|Any CPU {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release|Any CPU.ActiveCfg = Release|Any CPU {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release|Any CPU.Build.0 = Release|Any CPU - {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release|x86.ActiveCfg = Release|x86 - {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release|x86.Build.0 = Release|x86 + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release|x64.ActiveCfg = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release|x64.Build.0 = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release|x86.ActiveCfg = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release|x86.Build.0 = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release+Tests|x64.Build.0 = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {C1AEDDBD-7D3C-4C09-9C88-1644D796FD9A}.Release+Tests|x86.Build.0 = Release|Any CPU {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug|x86.ActiveCfg = Debug|x86 - {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug|x86.Build.0 = Debug|x86 + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug|x64.ActiveCfg = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug|x64.Build.0 = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug|x86.ActiveCfg = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug|x86.Build.0 = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Debug+Tests|x86.Build.0 = Debug|Any CPU {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release|Any CPU.ActiveCfg = Release|Any CPU {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release|Any CPU.Build.0 = Release|Any CPU - {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release|x86.ActiveCfg = Release|x86 - {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release|x86.Build.0 = Release|x86 + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release|x64.ActiveCfg = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release|x64.Build.0 = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release|x86.ActiveCfg = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release|x86.Build.0 = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release+Tests|x64.Build.0 = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {D6AAF434-F4DF-4376-863D-109A8762CECA}.Release+Tests|x86.Build.0 = Release|Any CPU {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug|x86.ActiveCfg = Debug|x86 - {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug|x86.Build.0 = Debug|x86 + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug|x64.ActiveCfg = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug|x64.Build.0 = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug|x86.ActiveCfg = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug|x86.Build.0 = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Debug+Tests|x86.Build.0 = Debug|Any CPU {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release|Any CPU.ActiveCfg = Release|Any CPU {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release|Any CPU.Build.0 = Release|Any CPU - {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release|x86.ActiveCfg = Release|x86 - {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release|x86.Build.0 = Release|x86 + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release|x64.ActiveCfg = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release|x64.Build.0 = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release|x86.ActiveCfg = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release|x86.Build.0 = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release+Tests|x64.Build.0 = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {3E8B5548-D3AB-44CD-8C1D-D828540D49C9}.Release+Tests|x86.Build.0 = Release|Any CPU {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug|Any CPU.Build.0 = Debug|Any CPU - {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug|x86.ActiveCfg = Debug|x86 - {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug|x86.Build.0 = Debug|x86 + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug|x64.ActiveCfg = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug|x64.Build.0 = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug|x86.ActiveCfg = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug|x86.Build.0 = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Debug+Tests|x86.Build.0 = Debug|Any CPU {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release|Any CPU.ActiveCfg = Release|Any CPU {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release|Any CPU.Build.0 = Release|Any CPU - {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release|x86.ActiveCfg = Release|x86 - {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release|x86.Build.0 = Release|x86 + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release|x64.ActiveCfg = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release|x64.Build.0 = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release|x86.ActiveCfg = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release|x86.Build.0 = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release+Tests|x64.Build.0 = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {EF8EE44C-62B2-4744-85CB-278E1F37D418}.Release+Tests|x86.Build.0 = Release|Any CPU {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug|x86.ActiveCfg = Debug|x86 - {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug|x86.Build.0 = Debug|x86 + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug|x64.ActiveCfg = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug|x64.Build.0 = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug|x86.ActiveCfg = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug|x86.Build.0 = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Debug+Tests|x86.Build.0 = Debug|Any CPU {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release|Any CPU.ActiveCfg = Release|Any CPU {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release|Any CPU.Build.0 = Release|Any CPU - {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release|x86.ActiveCfg = Release|x86 - {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release|x86.Build.0 = Release|x86 + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release|x64.ActiveCfg = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release|x64.Build.0 = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release|x86.ActiveCfg = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release|x86.Build.0 = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release+Tests|x64.Build.0 = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {8B33C830-34CF-42E5-AF2F-E8D9A4AF49D1}.Release+Tests|x86.Build.0 = Release|Any CPU {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug|Any CPU.Build.0 = Debug|Any CPU - {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug|x86.ActiveCfg = Debug|x86 - {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug|x86.Build.0 = Debug|x86 + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug|x64.ActiveCfg = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug|x64.Build.0 = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug|x86.ActiveCfg = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug|x86.Build.0 = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Debug+Tests|x86.Build.0 = Debug|Any CPU {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release|Any CPU.ActiveCfg = Release|Any CPU {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release|Any CPU.Build.0 = Release|Any CPU - {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release|x86.ActiveCfg = Release|x86 - {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release|x86.Build.0 = Release|x86 + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release|x64.ActiveCfg = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release|x64.Build.0 = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release|x86.ActiveCfg = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release|x86.Build.0 = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release+Tests|x64.Build.0 = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {556F43A0-C288-471A-8CD8-A787FC7ACA34}.Release+Tests|x86.Build.0 = Release|Any CPU {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug|x86.ActiveCfg = Debug|x86 - {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug|x86.Build.0 = Debug|x86 + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug|x64.ActiveCfg = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug|x64.Build.0 = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug|x86.ActiveCfg = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug|x86.Build.0 = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Debug+Tests|x86.Build.0 = Debug|Any CPU {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release|Any CPU.ActiveCfg = Release|Any CPU {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release|Any CPU.Build.0 = Release|Any CPU - {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release|x86.ActiveCfg = Release|x86 - {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release|x86.Build.0 = Release|x86 + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release|x64.ActiveCfg = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release|x64.Build.0 = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release|x86.ActiveCfg = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release|x86.Build.0 = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release+Tests|x64.Build.0 = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {4EBF2653-9654-4E40-880E-0046B3D6210E}.Release+Tests|x86.Build.0 = Release|Any CPU {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug|x86.ActiveCfg = Debug|x86 - {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug|x86.Build.0 = Debug|x86 + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug|x64.ActiveCfg = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug|x64.Build.0 = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug|x86.ActiveCfg = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug|x86.Build.0 = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Debug+Tests|x86.Build.0 = Debug|Any CPU {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release|Any CPU.ActiveCfg = Release|Any CPU {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release|Any CPU.Build.0 = Release|Any CPU - {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release|x86.ActiveCfg = Release|x86 - {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release|x86.Build.0 = Release|x86 + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release|x64.ActiveCfg = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release|x64.Build.0 = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release|x86.ActiveCfg = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release|x86.Build.0 = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release+Tests|x64.Build.0 = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {74AD0487-CEF9-43FE-9283-BC6F79539ADE}.Release+Tests|x86.Build.0 = Release|Any CPU {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug|x86.ActiveCfg = Debug|x86 - {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug|x86.Build.0 = Debug|x86 + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug|x64.ActiveCfg = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug|x64.Build.0 = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug|x86.ActiveCfg = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug|x86.Build.0 = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Debug+Tests|x86.Build.0 = Debug|Any CPU {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release|Any CPU.ActiveCfg = Release|Any CPU {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release|Any CPU.Build.0 = Release|Any CPU - {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release|x86.ActiveCfg = Release|x86 - {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release|x86.Build.0 = Release|x86 + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release|x64.ActiveCfg = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release|x64.Build.0 = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release|x86.ActiveCfg = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release|x86.Build.0 = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release+Tests|x64.Build.0 = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {78101C01-E186-4954-B1DD-DEBB7905FAD8}.Release+Tests|x86.Build.0 = Release|Any CPU {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug|x86.ActiveCfg = Debug|x86 - {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug|x86.Build.0 = Debug|x86 + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug|x64.ActiveCfg = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug|x64.Build.0 = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug|x86.ActiveCfg = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug|x86.Build.0 = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Debug+Tests|x86.Build.0 = Debug|Any CPU {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release|Any CPU.ActiveCfg = Release|Any CPU {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release|Any CPU.Build.0 = Release|Any CPU - {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release|x86.ActiveCfg = Release|x86 - {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release|x86.Build.0 = Release|x86 + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release|x64.ActiveCfg = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release|x64.Build.0 = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release|x86.ActiveCfg = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release|x86.Build.0 = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release+Tests|x64.Build.0 = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {BD6AFBEA-DB64-432A-80F7-4672A7FF283E}.Release+Tests|x86.Build.0 = Release|Any CPU {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug|Any CPU.Build.0 = Debug|Any CPU - {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug|x86.ActiveCfg = Debug|x86 - {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug|x86.Build.0 = Debug|x86 + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug|x64.ActiveCfg = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug|x64.Build.0 = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug|x86.ActiveCfg = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug|x86.Build.0 = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Debug+Tests|x86.Build.0 = Debug|Any CPU {285FADFC-E221-4575-B9DD-42E452B4381F}.Release|Any CPU.ActiveCfg = Release|Any CPU {285FADFC-E221-4575-B9DD-42E452B4381F}.Release|Any CPU.Build.0 = Release|Any CPU - {285FADFC-E221-4575-B9DD-42E452B4381F}.Release|x86.ActiveCfg = Release|x86 - {285FADFC-E221-4575-B9DD-42E452B4381F}.Release|x86.Build.0 = Release|x86 + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release|x64.ActiveCfg = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release|x64.Build.0 = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release|x86.ActiveCfg = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release|x86.Build.0 = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release+Tests|x64.Build.0 = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {285FADFC-E221-4575-B9DD-42E452B4381F}.Release+Tests|x86.Build.0 = Release|Any CPU {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug|x86.ActiveCfg = Debug|x86 - {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug|x86.Build.0 = Debug|x86 + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug|x64.ActiveCfg = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug|x64.Build.0 = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug|x86.ActiveCfg = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug|x86.Build.0 = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Debug+Tests|x86.Build.0 = Debug|Any CPU {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release|Any CPU.ActiveCfg = Release|Any CPU {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release|Any CPU.Build.0 = Release|Any CPU - {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release|x86.ActiveCfg = Release|x86 - {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release|x86.Build.0 = Release|x86 + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release|x64.ActiveCfg = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release|x64.Build.0 = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release|x86.ActiveCfg = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release|x86.Build.0 = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release+Tests|x64.Build.0 = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {0263E5F6-D5B2-4118-B12E-87F9A74DE8AF}.Release+Tests|x86.Build.0 = Release|Any CPU {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug|Any CPU.Build.0 = Debug|Any CPU - {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug|x86.ActiveCfg = Debug|x86 - {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug|x86.Build.0 = Debug|x86 + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug|x64.ActiveCfg = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug|x64.Build.0 = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug|x86.ActiveCfg = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug|x86.Build.0 = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Debug+Tests|x86.Build.0 = Debug|Any CPU {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release|Any CPU.ActiveCfg = Release|Any CPU {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release|Any CPU.Build.0 = Release|Any CPU - {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release|x86.ActiveCfg = Release|x86 - {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release|x86.Build.0 = Release|x86 + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release|x64.ActiveCfg = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release|x64.Build.0 = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release|x86.ActiveCfg = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release|x86.Build.0 = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release+Tests|x64.Build.0 = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {5B4E9515-994A-4DA7-9916-CDA8FD874701}.Release+Tests|x86.Build.0 = Release|Any CPU {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug|x86.ActiveCfg = Debug|x86 - {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug|x86.Build.0 = Debug|x86 + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug|x64.ActiveCfg = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug|x64.Build.0 = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug|x86.ActiveCfg = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug|x86.Build.0 = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Debug+Tests|x86.Build.0 = Debug|Any CPU {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release|Any CPU.ActiveCfg = Release|Any CPU {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release|Any CPU.Build.0 = Release|Any CPU - {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release|x86.ActiveCfg = Release|x86 - {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release|x86.Build.0 = Release|x86 + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release|x64.ActiveCfg = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release|x64.Build.0 = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release|x86.ActiveCfg = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release|x86.Build.0 = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release+Tests|x64.Build.0 = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {DCEEBF26-BB93-45EE-8B00-32927A687761}.Release+Tests|x86.Build.0 = Release|Any CPU {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug|Any CPU.Build.0 = Debug|Any CPU - {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug|x86.ActiveCfg = Debug|x86 - {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug|x86.Build.0 = Debug|x86 + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug|x64.ActiveCfg = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug|x64.Build.0 = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug|x86.ActiveCfg = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug|x86.Build.0 = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Debug+Tests|x86.Build.0 = Debug|Any CPU {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release|Any CPU.ActiveCfg = Release|Any CPU {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release|Any CPU.Build.0 = Release|Any CPU - {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release|x86.ActiveCfg = Release|x86 - {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release|x86.Build.0 = Release|x86 + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release|x64.ActiveCfg = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release|x64.Build.0 = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release|x86.ActiveCfg = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release|x86.Build.0 = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release+Tests|x64.Build.0 = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {40FEAC2B-A68A-498E-AD78-52A8268EFA45}.Release+Tests|x86.Build.0 = Release|Any CPU {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug|x86.ActiveCfg = Debug|x86 - {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug|x86.Build.0 = Debug|x86 + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug|x64.ActiveCfg = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug|x64.Build.0 = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug|x86.ActiveCfg = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug|x86.Build.0 = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Debug+Tests|x86.Build.0 = Debug|Any CPU {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release|Any CPU.ActiveCfg = Release|Any CPU {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release|Any CPU.Build.0 = Release|Any CPU - {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release|x86.ActiveCfg = Release|x86 - {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release|x86.Build.0 = Release|x86 + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release|x64.ActiveCfg = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release|x64.Build.0 = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release|x86.ActiveCfg = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release|x86.Build.0 = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release+Tests|x64.Build.0 = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {FDF347DB-0577-43DD-A819-16C7F30B49A7}.Release+Tests|x86.Build.0 = Release|Any CPU {21912919-338F-431D-945B-F3C104A96B8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {21912919-338F-431D-945B-F3C104A96B8E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {21912919-338F-431D-945B-F3C104A96B8E}.Debug|x86.ActiveCfg = Debug|x86 - {21912919-338F-431D-945B-F3C104A96B8E}.Debug|x86.Build.0 = Debug|x86 + {21912919-338F-431D-945B-F3C104A96B8E}.Debug|x64.ActiveCfg = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug|x64.Build.0 = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug|x86.ActiveCfg = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug|x86.Build.0 = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Debug+Tests|x86.Build.0 = Debug|Any CPU {21912919-338F-431D-945B-F3C104A96B8E}.Release|Any CPU.ActiveCfg = Release|Any CPU {21912919-338F-431D-945B-F3C104A96B8E}.Release|Any CPU.Build.0 = Release|Any CPU - {21912919-338F-431D-945B-F3C104A96B8E}.Release|x86.ActiveCfg = Release|x86 - {21912919-338F-431D-945B-F3C104A96B8E}.Release|x86.Build.0 = Release|x86 + {21912919-338F-431D-945B-F3C104A96B8E}.Release|x64.ActiveCfg = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release|x64.Build.0 = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release|x86.ActiveCfg = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release|x86.Build.0 = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release+Tests|x64.Build.0 = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {21912919-338F-431D-945B-F3C104A96B8E}.Release+Tests|x86.Build.0 = Release|Any CPU {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug|x86.ActiveCfg = Debug|x86 - {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug|x86.Build.0 = Debug|x86 + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug|x64.ActiveCfg = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug|x64.Build.0 = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug|x86.ActiveCfg = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug|x86.Build.0 = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Debug+Tests|x86.Build.0 = Debug|Any CPU {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release|Any CPU.ActiveCfg = Release|Any CPU {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release|Any CPU.Build.0 = Release|Any CPU - {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release|x86.ActiveCfg = Release|x86 - {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release|x86.Build.0 = Release|x86 + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release|x64.ActiveCfg = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release|x64.Build.0 = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release|x86.ActiveCfg = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release|x86.Build.0 = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release+Tests|x64.Build.0 = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {E462A275-2DAF-411C-95ED-C6A35FEC29D8}.Release+Tests|x86.Build.0 = Release|Any CPU {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug|x86.ActiveCfg = Debug|x86 - {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug|x86.Build.0 = Debug|x86 + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug|x64.ActiveCfg = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug|x64.Build.0 = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug|x86.ActiveCfg = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug|x86.Build.0 = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Debug+Tests|x86.Build.0 = Debug|Any CPU {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release|Any CPU.ActiveCfg = Release|Any CPU {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release|Any CPU.Build.0 = Release|Any CPU - {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release|x86.ActiveCfg = Release|x86 - {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release|x86.Build.0 = Release|x86 + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release|x64.ActiveCfg = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release|x64.Build.0 = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release|x86.ActiveCfg = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release|x86.Build.0 = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release+Tests|x64.Build.0 = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {A2C159C1-7D21-4483-AEB1-38D9FDC4C7F3}.Release+Tests|x86.Build.0 = Release|Any CPU {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug|Any CPU.Build.0 = Debug|Any CPU - {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug|x86.ActiveCfg = Debug|x86 - {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug|x86.Build.0 = Debug|x86 + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug|x64.ActiveCfg = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug|x64.Build.0 = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug|x86.ActiveCfg = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug|x86.Build.0 = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Debug+Tests|x86.Build.0 = Debug|Any CPU {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release|Any CPU.ActiveCfg = Release|Any CPU {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release|Any CPU.Build.0 = Release|Any CPU - {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release|x86.ActiveCfg = Release|x86 - {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release|x86.Build.0 = Release|x86 + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release|x64.ActiveCfg = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release|x64.Build.0 = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release|x86.ActiveCfg = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release|x86.Build.0 = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release+Tests|x64.Build.0 = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {1F6DF858-6011-4CAC-B33E-7000EE90FFBE}.Release+Tests|x86.Build.0 = Release|Any CPU {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug|Any CPU.Build.0 = Debug|Any CPU - {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug|x86.ActiveCfg = Debug|x86 - {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug|x86.Build.0 = Debug|x86 + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug|x64.ActiveCfg = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug|x64.Build.0 = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug|x86.ActiveCfg = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug|x86.Build.0 = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Debug+Tests|x86.Build.0 = Debug|Any CPU {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release|Any CPU.ActiveCfg = Release|Any CPU {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release|Any CPU.Build.0 = Release|Any CPU - {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release|x86.ActiveCfg = Release|x86 - {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release|x86.Build.0 = Release|x86 + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release|x64.ActiveCfg = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release|x64.Build.0 = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release|x86.ActiveCfg = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release|x86.Build.0 = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release+Tests|x64.Build.0 = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {E4504497-89BF-4ED5-A0CC-6F02E96C2652}.Release+Tests|x86.Build.0 = Release|Any CPU {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug|Any CPU.Build.0 = Debug|Any CPU - {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug|x86.ActiveCfg = Debug|x86 - {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug|x86.Build.0 = Debug|x86 + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug|x64.ActiveCfg = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug|x64.Build.0 = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug|x86.ActiveCfg = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug|x86.Build.0 = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Debug+Tests|x86.Build.0 = Debug|Any CPU {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release|Any CPU.ActiveCfg = Release|Any CPU {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release|Any CPU.Build.0 = Release|Any CPU - {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release|x86.ActiveCfg = Release|x86 - {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release|x86.Build.0 = Release|x86 + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release|x64.ActiveCfg = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release|x64.Build.0 = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release|x86.ActiveCfg = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release|x86.Build.0 = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release+Tests|x64.Build.0 = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {CDB62A9F-0887-43AE-815D-4593A8E35E44}.Release+Tests|x86.Build.0 = Release|Any CPU {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug|x86.ActiveCfg = Debug|x86 - {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug|x86.Build.0 = Debug|x86 + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug|x64.ActiveCfg = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug|x64.Build.0 = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug|x86.ActiveCfg = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug|x86.Build.0 = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Debug+Tests|x86.Build.0 = Debug|Any CPU {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release|Any CPU.ActiveCfg = Release|Any CPU {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release|Any CPU.Build.0 = Release|Any CPU - {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release|x86.ActiveCfg = Release|x86 - {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release|x86.Build.0 = Release|x86 + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release|x64.ActiveCfg = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release|x64.Build.0 = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release|x86.ActiveCfg = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release|x86.Build.0 = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release+Tests|x64.Build.0 = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {F2CED639-1DA7-489D-9DBB-909F7B590C3D}.Release+Tests|x86.Build.0 = Release|Any CPU {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug|Any CPU.Build.0 = Debug|Any CPU - {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug|x86.ActiveCfg = Debug|x86 - {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug|x86.Build.0 = Debug|x86 + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug|x64.ActiveCfg = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug|x64.Build.0 = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug|x86.ActiveCfg = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug|x86.Build.0 = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Debug+Tests|x86.Build.0 = Debug|Any CPU {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release|Any CPU.ActiveCfg = Release|Any CPU {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release|Any CPU.Build.0 = Release|Any CPU - {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release|x86.ActiveCfg = Release|x86 - {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release|x86.Build.0 = Release|x86 + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release|x64.ActiveCfg = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release|x64.Build.0 = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release|x86.ActiveCfg = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release|x86.Build.0 = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release+Tests|x64.Build.0 = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {B97FEDD3-8F61-4006-ACCD-AD735069B0CA}.Release+Tests|x86.Build.0 = Release|Any CPU {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug|Any CPU.Build.0 = Debug|Any CPU - {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug|x86.ActiveCfg = Debug|x86 - {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug|x86.Build.0 = Debug|x86 + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug|x64.ActiveCfg = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug|x64.Build.0 = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug|x86.ActiveCfg = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug|x86.Build.0 = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Debug+Tests|x86.Build.0 = Debug|Any CPU {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release|Any CPU.ActiveCfg = Release|Any CPU {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release|Any CPU.Build.0 = Release|Any CPU - {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release|x86.ActiveCfg = Release|x86 - {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release|x86.Build.0 = Release|x86 + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release|x64.ActiveCfg = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release|x64.Build.0 = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release|x86.ActiveCfg = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release|x86.Build.0 = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release+Tests|x64.Build.0 = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {3074D447-A469-4CA2-A7E5-FE53DB45CB11}.Release+Tests|x86.Build.0 = Release|Any CPU {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug|x86.ActiveCfg = Debug|x86 - {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug|x86.Build.0 = Debug|x86 + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug|x64.ActiveCfg = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug|x64.Build.0 = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug|x86.ActiveCfg = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug|x86.Build.0 = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Debug+Tests|x86.Build.0 = Debug|Any CPU {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release|Any CPU.ActiveCfg = Release|Any CPU {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release|Any CPU.Build.0 = Release|Any CPU - {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release|x86.ActiveCfg = Release|x86 - {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release|x86.Build.0 = Release|x86 + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release|x64.ActiveCfg = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release|x64.Build.0 = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release|x86.ActiveCfg = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release|x86.Build.0 = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release+Tests|x64.Build.0 = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {2F93393B-9629-470E-B7B8-0D8CFA25315A}.Release+Tests|x86.Build.0 = Release|Any CPU {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug|Any CPU.Build.0 = Debug|Any CPU - {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug|x86.ActiveCfg = Debug|x86 - {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug|x86.Build.0 = Debug|x86 + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug|x64.ActiveCfg = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug|x64.Build.0 = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug|x86.ActiveCfg = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug|x86.Build.0 = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Debug+Tests|x86.Build.0 = Debug|Any CPU {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release|Any CPU.ActiveCfg = Release|Any CPU {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release|Any CPU.Build.0 = Release|Any CPU - {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release|x86.ActiveCfg = Release|x86 - {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release|x86.Build.0 = Release|x86 + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release|x64.ActiveCfg = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release|x64.Build.0 = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release|x86.ActiveCfg = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release|x86.Build.0 = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release+Tests|x64.Build.0 = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {194B58C9-9D2B-4D5E-9256-773FD3222582}.Release+Tests|x86.Build.0 = Release|Any CPU {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug|x86.ActiveCfg = Debug|x86 - {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug|x86.Build.0 = Debug|x86 + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug|x64.ActiveCfg = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug|x64.Build.0 = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug|x86.ActiveCfg = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug|x86.Build.0 = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Debug+Tests|x86.Build.0 = Debug|Any CPU {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release|Any CPU.ActiveCfg = Release|Any CPU {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release|Any CPU.Build.0 = Release|Any CPU - {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release|x86.ActiveCfg = Release|x86 - {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release|x86.Build.0 = Release|x86 + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release|x64.ActiveCfg = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release|x64.Build.0 = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release|x86.ActiveCfg = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release|x86.Build.0 = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release+Tests|x64.Build.0 = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {DC936D9F-7ED7-4D2B-9A03-881C86E2F6C8}.Release+Tests|x86.Build.0 = Release|Any CPU {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug|Any CPU.Build.0 = Debug|Any CPU - {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug|x86.ActiveCfg = Debug|x86 - {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug|x86.Build.0 = Debug|x86 + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug|x64.ActiveCfg = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug|x64.Build.0 = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug|x86.ActiveCfg = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug|x86.Build.0 = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Debug+Tests|x86.Build.0 = Debug|Any CPU {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release|Any CPU.ActiveCfg = Release|Any CPU {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release|Any CPU.Build.0 = Release|Any CPU - {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release|x86.ActiveCfg = Release|x86 - {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release|x86.Build.0 = Release|x86 - {92BBB3B6-E318-4B12-8378-6D46E69AB938}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {92BBB3B6-E318-4B12-8378-6D46E69AB938}.Debug|Any CPU.Build.0 = Debug|Any CPU - {92BBB3B6-E318-4B12-8378-6D46E69AB938}.Debug|x86.ActiveCfg = Debug|x86 - {92BBB3B6-E318-4B12-8378-6D46E69AB938}.Debug|x86.Build.0 = Debug|x86 - {92BBB3B6-E318-4B12-8378-6D46E69AB938}.Release|Any CPU.ActiveCfg = Release|Any CPU - {92BBB3B6-E318-4B12-8378-6D46E69AB938}.Release|Any CPU.Build.0 = Release|Any CPU - {92BBB3B6-E318-4B12-8378-6D46E69AB938}.Release|x86.ActiveCfg = Release|x86 - {92BBB3B6-E318-4B12-8378-6D46E69AB938}.Release|x86.Build.0 = Release|x86 + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release|x64.ActiveCfg = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release|x64.Build.0 = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release|x86.ActiveCfg = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release|x86.Build.0 = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release+Tests|x64.Build.0 = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {DCA7613E-7BC3-4610-A95E-73C0D64C5B98}.Release+Tests|x86.Build.0 = Release|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug|Any CPU.Build.0 = Debug|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug|x64.ActiveCfg = Debug|x64 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug|x64.Build.0 = Debug|x64 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug|x86.ActiveCfg = Debug|x86 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug|x86.Build.0 = Debug|x86 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug+Tests|x64.ActiveCfg = Debug|x64 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug+Tests|x64.Build.0 = Debug|x64 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug+Tests|x86.ActiveCfg = Debug|x86 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Debug+Tests|x86.Build.0 = Debug|x86 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release|Any CPU.ActiveCfg = Release|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release|Any CPU.Build.0 = Release|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release|x64.ActiveCfg = Release|x64 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release|x64.Build.0 = Release|x64 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release|x86.ActiveCfg = Release|x86 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release|x86.Build.0 = Release|x86 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release+Tests|x64.ActiveCfg = Release|x64 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release+Tests|x64.Build.0 = Release|x64 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release+Tests|x86.ActiveCfg = Release|x86 + {FF680DE0-9CB7-45F4-BAFA-6EFFAAFD9C09}.Release+Tests|x86.Build.0 = Release|x86 + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug|x64.ActiveCfg = Debug|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug|x86.ActiveCfg = Debug|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug+Tests|x64.ActiveCfg = Debug|x64 + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug+Tests|x64.Build.0 = Debug|x64 + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug+Tests|x86.ActiveCfg = Debug|x86 + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Debug+Tests|x86.Build.0 = Debug|x86 + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release|Any CPU.ActiveCfg = Release|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release|x64.ActiveCfg = Release|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release|x86.ActiveCfg = Release|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release+Tests|x64.ActiveCfg = Release|x64 + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release+Tests|x64.Build.0 = Release|x64 + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release+Tests|x86.ActiveCfg = Release|x86 + {ABC71D26-295C-4C6C-B6DE-320AD49EEF79}.Release+Tests|x86.Build.0 = Release|x86 + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug|x64.ActiveCfg = Debug|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug|x86.ActiveCfg = Debug|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug+Tests|x64.ActiveCfg = Debug|x64 + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug+Tests|x64.Build.0 = Debug|x64 + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug+Tests|x86.ActiveCfg = Debug|x86 + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Debug+Tests|x86.Build.0 = Debug|x86 + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release|x64.ActiveCfg = Release|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release|x86.ActiveCfg = Release|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release+Tests|x64.ActiveCfg = Release|x64 + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release+Tests|x64.Build.0 = Release|x64 + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release+Tests|x86.ActiveCfg = Release|x86 + {19C1FEE5-CEC3-442B-99B2-3F3FC955CAB4}.Release+Tests|x86.Build.0 = Release|x86 + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug|x64.ActiveCfg = Debug|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug|x86.ActiveCfg = Debug|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug+Tests|x64.ActiveCfg = Debug|x64 + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug+Tests|x64.Build.0 = Debug|x64 + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug+Tests|x86.ActiveCfg = Debug|x86 + {F44D3125-12E8-4143-B250-84C5D89D253C}.Debug+Tests|x86.Build.0 = Debug|x86 + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release|x64.ActiveCfg = Release|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release|x86.ActiveCfg = Release|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release+Tests|x64.ActiveCfg = Release|x64 + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release+Tests|x64.Build.0 = Release|x64 + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release+Tests|x86.ActiveCfg = Release|x86 + {F44D3125-12E8-4143-B250-84C5D89D253C}.Release+Tests|x86.Build.0 = Release|x86 + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug|x64.ActiveCfg = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug|x64.Build.0 = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug|x86.ActiveCfg = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug|x86.Build.0 = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Debug+Tests|x86.Build.0 = Debug|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release|Any CPU.Build.0 = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release|x64.ActiveCfg = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release|x64.Build.0 = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release|x86.ActiveCfg = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release|x86.Build.0 = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release+Tests|x64.Build.0 = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {8B5A1C53-AF20-4379-A8D1-31822ACC6AD8}.Release+Tests|x86.Build.0 = Release|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug|x64.ActiveCfg = Debug|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug|x86.ActiveCfg = Debug|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug+Tests|x64.ActiveCfg = Debug|x64 + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug+Tests|x64.Build.0 = Debug|x64 + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug+Tests|x86.ActiveCfg = Debug|x86 + {F616101E-6103-4788-9382-964D0A1D0A09}.Debug+Tests|x86.Build.0 = Debug|x86 + {F616101E-6103-4788-9382-964D0A1D0A09}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Release|x64.ActiveCfg = Release|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Release|x86.ActiveCfg = Release|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {F616101E-6103-4788-9382-964D0A1D0A09}.Release+Tests|x64.ActiveCfg = Release|x64 + {F616101E-6103-4788-9382-964D0A1D0A09}.Release+Tests|x64.Build.0 = Release|x64 + {F616101E-6103-4788-9382-964D0A1D0A09}.Release+Tests|x86.ActiveCfg = Release|x86 + {F616101E-6103-4788-9382-964D0A1D0A09}.Release+Tests|x86.Build.0 = Release|x86 + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug|x64.ActiveCfg = Debug|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug|x86.ActiveCfg = Debug|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug+Tests|x64.ActiveCfg = Debug|x64 + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug+Tests|x64.Build.0 = Debug|x64 + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug+Tests|x86.ActiveCfg = Debug|x86 + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Debug+Tests|x86.Build.0 = Debug|x86 + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release|Any CPU.ActiveCfg = Release|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release|x64.ActiveCfg = Release|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release|x86.ActiveCfg = Release|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release+Tests|x64.ActiveCfg = Release|x64 + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release+Tests|x64.Build.0 = Release|x64 + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release+Tests|x86.ActiveCfg = Release|x86 + {B7E7E6B5-F1B1-4A44-9966-89AAA7579514}.Release+Tests|x86.Build.0 = Release|x86 + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug|x64.ActiveCfg = Debug|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug|x86.ActiveCfg = Debug|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug+Tests|x64.ActiveCfg = Debug|x64 + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug+Tests|x64.Build.0 = Debug|x64 + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug+Tests|x86.ActiveCfg = Debug|x86 + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Debug+Tests|x86.Build.0 = Debug|x86 + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release|x64.ActiveCfg = Release|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release|x86.ActiveCfg = Release|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release+Tests|x64.ActiveCfg = Release|x64 + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release+Tests|x64.Build.0 = Release|x64 + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release+Tests|x86.ActiveCfg = Release|x86 + {536FDE15-CA93-4F84-B1FF-08126C3C443A}.Release+Tests|x86.Build.0 = Release|x86 + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug|Any CPU.Build.0 = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug|x64.ActiveCfg = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug|x64.Build.0 = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug|x86.ActiveCfg = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug|x86.Build.0 = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Debug+Tests|x86.Build.0 = Debug|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release|Any CPU.ActiveCfg = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release|Any CPU.Build.0 = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release|x64.ActiveCfg = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release|x64.Build.0 = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release|x86.ActiveCfg = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release|x86.Build.0 = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release+Tests|x64.Build.0 = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {BBF3BC59-7FA1-4BE4-B0FD-2D91AB109889}.Release+Tests|x86.Build.0 = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug|x64.ActiveCfg = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug|x64.Build.0 = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug|x86.ActiveCfg = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug|x86.Build.0 = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug+Tests|Any CPU.ActiveCfg = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug+Tests|Any CPU.Build.0 = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug+Tests|x64.ActiveCfg = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug+Tests|x64.Build.0 = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug+Tests|x86.ActiveCfg = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Debug+Tests|x86.Build.0 = Debug|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release|Any CPU.Build.0 = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release|x64.ActiveCfg = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release|x64.Build.0 = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release|x86.ActiveCfg = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release|x86.Build.0 = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release+Tests|Any CPU.ActiveCfg = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release+Tests|Any CPU.Build.0 = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release+Tests|x64.ActiveCfg = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release+Tests|x64.Build.0 = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release+Tests|x86.ActiveCfg = Release|Any CPU + {12FA6A8C-FDEB-41AC-BCB8-9269106105C8}.Release+Tests|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {9549C61A-B51B-4837-B113-0602354608B4} = {C714C81C-C491-42D7-AF9B-55A6E1F972FB} + {43B75BC7-8B9A-4211-BD98-B4B2DA9E4A25} = {9549C61A-B51B-4837-B113-0602354608B4} + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2FD1F61A-3490-4AAD-B095-5FA7AA101210} + EndGlobalSection EndGlobal diff --git a/FlashDevelop/Bin/Debug/.local b/FlashDevelop/Bin/Debug/.local index e69de29bb2..8d1c8b69c3 100644 --- a/FlashDevelop/Bin/Debug/.local +++ b/FlashDevelop/Bin/Debug/.local @@ -0,0 +1 @@ + diff --git a/FlashDevelop/Bin/Debug/.multi b/FlashDevelop/Bin/Debug/.multi index 4d6a3b44f4..8d1c8b69c3 100644 --- a/FlashDevelop/Bin/Debug/.multi +++ b/FlashDevelop/Bin/Debug/.multi @@ -1 +1 @@ -ECHO is on. + diff --git a/FlashDevelop/Bin/Debug/AStyle.dll b/FlashDevelop/Bin/Debug/AStyle.dll new file mode 100755 index 0000000000..1d437213e6 Binary files /dev/null and b/FlashDevelop/Bin/Debug/AStyle.dll differ diff --git a/FlashDevelop/Bin/Debug/AStyle64.dll b/FlashDevelop/Bin/Debug/AStyle64.dll new file mode 100755 index 0000000000..2d60bffa0c Binary files /dev/null and b/FlashDevelop/Bin/Debug/AStyle64.dll differ diff --git a/FlashDevelop/Bin/Debug/Aga.dll b/FlashDevelop/Bin/Debug/Aga.dll old mode 100644 new mode 100755 index 4fec1b000a..df900c3f6e Binary files a/FlashDevelop/Bin/Debug/Aga.dll and b/FlashDevelop/Bin/Debug/Aga.dll differ diff --git a/FlashDevelop/Bin/Debug/Antlr3.dll b/FlashDevelop/Bin/Debug/Antlr3.dll old mode 100644 new mode 100755 index 1a0a3fc936..455339fe5e Binary files a/FlashDevelop/Bin/Debug/Antlr3.dll and b/FlashDevelop/Bin/Debug/Antlr3.dll differ diff --git a/FlashDevelop/Bin/Debug/Docs/fdicon.png b/FlashDevelop/Bin/Debug/Docs/icon.png similarity index 100% rename from FlashDevelop/Bin/Debug/Docs/fdicon.png rename to FlashDevelop/Bin/Debug/Docs/icon.png diff --git a/FlashDevelop/Bin/Debug/Docs/index.html b/FlashDevelop/Bin/Debug/Docs/index.html index 2fbbecceff..8c351f3db1 100644 --- a/FlashDevelop/Bin/Debug/Docs/index.html +++ b/FlashDevelop/Bin/Debug/Docs/index.html @@ -3,6 +3,7 @@ FlashDevelop + @@ -10,7 +11,7 @@
    @@ -18,14 +19,14 @@

    FlashDevelop FlashDevelop 4

    Description

    FlashDevelop is a highly customizable lightweight script editor with extended support for class based languages. Altought the program is designed mostly for ActionScript and Haxe, other languages can - be implemented quite easily too. FlashDevelop requires the Microsoft.NET 2.0 Framework. You can support us by + be implemented quite easily too. FlashDevelop requires the Microsoft.NET 4.0 Framework. You can support us by donating for the project via PayPal. Any donation, even 1$, is good for the project. Code contributions are also welcome.

    You can find more info about FlashDevelop from the project website www.flashdevelop.org.

    Used Icons

    -

    Current smooth FlashDevelop menu icons are free icons downloaded from - www.famfamfam.com. The icons are released under Creative Commons Attribution 2.5 License and are property of Mark James. - Some of the icons are modified from the original icons. Visit Mark's site.

    +

    Current smooth FlashDevelop icons are free icons downloaded from + famfamfam.com, visualfarm.com and fatcow.com. + The icons are released under Creative Commons Attribution 2.5 and 3 Licenses. Some of the used icons are modified from the original ones.

    Used Tools

    FlashDevelop includes few third party tools by default. The listed tools are copyright of their respective owners.

    @@ -33,8 +34,8 @@

    Used Tools

  • SwfOp library by Florian Kruesch (code library)
  • AS2API documentation tool by David Holroyd (console application)
  • Motion-Twin ActionScript Compiler by Motion-Twin (console application)
  • +
  • Flex PMD tool by Apache Software Foundation (console application)
  • Swfmill XML/SWF processor by Daniel Fischer (console application)
  • -
  • Flex PMD tool by Adobe Systems Inc. (console application)
  • Components

    @@ -49,10 +50,11 @@

    Components

  • Aga controls by Andrey Gliznetsov
  • CSScriptLibrary by Oleg Shilo
  • SharpZipLib by ISharpCode
  • +
  • Artistic Style by Jim Pattee
  • Licence

    -

    Copyright (c) 2005-2014 Mika Palmu - FlashDevelop.org

    +

    Copyright (c) 2005-2017 Mika Palmu - FlashDevelop.org

    Portions copyright Philippe Elsass and all helpful contributors.

    Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation diff --git a/FlashDevelop/Bin/Debug/Docs/styles.css b/FlashDevelop/Bin/Debug/Docs/styles.css index 5069c45280..6bed3a7322 100644 --- a/FlashDevelop/Bin/Debug/Docs/styles.css +++ b/FlashDevelop/Bin/Debug/Docs/styles.css @@ -1,12 +1,12 @@ body { - font-size: 8pt; - font-family: "Trebuchet MS", Georgia, Times, serif; + font-size: 9pt; + font-family: "Open Sans", "Trebuchet MS", Georgia, Times, serif; padding-top: 12px; } h4 { - font-size: 9pt; + font-size: 12pt; border-bottom: 1px dotted #999999; } ul @@ -25,10 +25,12 @@ a:hover color: darkblue; text-decoration: underline; } -#wrapper { - width: 600px; +#wrapper +{ + width: auto; padding: 18px; padding-left: 25px; + padding-right: 25px; padding-top: 0px; } #header diff --git a/FlashDevelop/Bin/Debug/FDMT.cmd b/FlashDevelop/Bin/Debug/FDMT.cmd new file mode 100644 index 0000000000..0e4ecd6af3 --- /dev/null +++ b/FlashDevelop/Bin/Debug/FDMT.cmd @@ -0,0 +1,48 @@ +@echo off +cd /d %~dp0 +echo FlashDevelop Maintenance Tool - v1.0.0 +echo. +echo ! Make sure you have admin rights or run this as an admin ! +echo. + +:menu +echo *** Available tasks *** +echo. +echo [1] Toggle standalone mode +echo [2] Toggle multi instance mode +echo [3] Exit, I'm done. +echo. +set /p option="What do you want me to do? " +if "%option%" == "1" goto :local +if "%option%" == "2" goto :multi +if "%option%" == "3" goto :end +echo Invalid option, try again. +echo. +goto :menu + +:local +echo. +if exist .local ( + echo Deleting .local, restart FlashDevelop. + del .local +) else ( + echo Creating .local, restart FlashDevelop. + echo. > .local +) +echo. +goto :menu + +:multi +echo. +if exist .multi ( + echo Deleting .multi, restart FlashDevelop. + del .multi +) else ( + echo Creating .multi, restart FlashDevelop. + echo. > .multi +) +echo. +goto :menu + +:end +exit 0 diff --git a/FlashDevelop/Bin/Debug/FDOPT.cmd b/FlashDevelop/Bin/Debug/FDOPT.cmd new file mode 100644 index 0000000000..eddd97b46f --- /dev/null +++ b/FlashDevelop/Bin/Debug/FDOPT.cmd @@ -0,0 +1,65 @@ +@echo off +echo FlashDevelop OPtimizer Tool - v1.0.0 +echo. +echo ! Make sure you have admin rights or run this as an admin ! +echo. + +:: Set paths +cd %~dp0% +set CDIR=%~dp0% +set PDIR=%~dp0%Plugins +set NGEN=%WINDIR%\Microsoft.NET\Framework\v2.0.50727\ngen.exe + +if "%1" == "install" goto :install +if "%1" == "uninstall" goto :uninstall + +:menu +echo *** Available tasks *** +echo. +echo [1] Optimize with NGEN +echo [2] Remove NGEN optimizations +echo [3] Exit, I'm done. +echo. +set /p option="What do you want me to do? " +if "%option%" == "1" goto :install +if "%option%" == "2" goto :uninstall +if "%option%" == "3" goto :end +echo Invalid option, try again. +echo. +goto :menu + +:install + +echo Optimizing with NGEN... +if exist "%CDIR%HaxeDevelop.exe" "%NGEN%" install "%CDIR%HaxeDevelop.exe" /AppBase:"%CDIR%\" +if exist "%CDIR%FlashDevelop.exe" "%NGEN%" install "%CDIR%FlashDevelop.exe" /AppBase:"%CDIR%\" +"%NGEN%" install "%CDIR%Aga.dll" /AppBase:"%CDIR%\" +"%NGEN%" install "%CDIR%SwfOp.dll" /AppBase:"%CDIR%\" +"%NGEN%" install "%CDIR%Antlr3.dll" /AppBase:"%CDIR%\" +"%NGEN%" install "%CDIR%Scripting.dll" /AppBase:"%CDIR%\" +"%NGEN%" install "%CDIR%Tools\fdbuild\fdbuild.exe" /AppBase:"%CDIR%Tools\fdbuild" +"%NGEN%" install "%CDIR%Tools\asdocgen\ASDocGen.exe" /AppBase:"%CDIR%Tools\asdocgen" +"%NGEN%" install "%CDIR%Tools\appman\AppMan.exe" /AppBase:"%CDIR%Tools\appman" +:: Install plugins? +:: for %%G in ("%PDIR%\*.dll") do "%NGEN%" install "%%G" /AppBase:"%CDIR%\" +goto :end + +:uninstall + +echo Removing NGEN optimizations... +if exist "%CDIR%HaxeDevelop.exe" "%NGEN%" uninstall "%CDIR%HaxeDevelop.exe" +if exist "%CDIR%FlashDevelop.exe" "%NGEN%" uninstall "%CDIR%FlashDevelop.exe" +"%NGEN%" uninstall "%CDIR%Aga.dll" +"%NGEN%" uninstall "%CDIR%SwfOp.dll" +"%NGEN%" uninstall "%CDIR%Antlr3.dll" +"%NGEN%" uninstall "%CDIR%Scripting.dll" +"%NGEN%" uninstall "%CDIR%Tools\fdbuild\fdbuild.exe" +"%NGEN%" uninstall "%CDIR%Tools\asdocgen\ASDocGen.exe" +"%NGEN%" uninstall "%CDIR%Tools\appman\AppMan.exe" +:: Uninstall plugins? +:: for %%G in ("%PDIR%\*.dll") do "%NGEN%" uninstall "%%G" +goto :end + +:end +echo Done. +exit 0 diff --git a/FlashDevelop/Bin/Debug/FirstRun.fdb b/FlashDevelop/Bin/Debug/FirstRun.fdb index 90f4c2eacb..535c97ec21 100644 Binary files a/FlashDevelop/Bin/Debug/FirstRun.fdb and b/FlashDevelop/Bin/Debug/FirstRun.fdb differ diff --git a/FlashDevelop/Bin/Debug/FlashDevelop.exe.config b/FlashDevelop/Bin/Debug/FlashDevelop.exe.config index 8baa6ea256..3e6dce789d 100644 --- a/FlashDevelop/Bin/Debug/FlashDevelop.exe.config +++ b/FlashDevelop/Bin/Debug/FlashDevelop.exe.config @@ -1,9 +1,14 @@ - + - - - - - - + + + + + + + + + + + \ No newline at end of file diff --git a/FlashDevelop/Bin/Debug/FlashDevelop64.exe.config b/FlashDevelop/Bin/Debug/FlashDevelop64.exe.config new file mode 100644 index 0000000000..dbde00c152 --- /dev/null +++ b/FlashDevelop/Bin/Debug/FlashDevelop64.exe.config @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/AccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/AccImpl.as index 50c08f9ccc..712b74ad4e 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/AccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/AccImpl.as @@ -1,87 +1,87 @@ -package fl.accessibility -{ - import flash.accessibility.Accessibility; - import flash.accessibility.AccessibilityImplementation; - import flash.accessibility.AccessibilityProperties; - import flash.events.Event; - import fl.core.UIComponent; - import flash.display.MovieClip; - import flash.text.TextField; - +package fl.accessibility +{ + import flash.accessibility.Accessibility; + import flash.accessibility.AccessibilityImplementation; + import flash.accessibility.AccessibilityProperties; + import flash.events.Event; + import fl.core.UIComponent; + import flash.display.MovieClip; + import flash.text.TextField; + /** * The AccImpl class, also called the Accessibility Implementation class, is the base class * for the implementation of accessibility in components. This class enables communication between * a component and a screen reader. Screen readers are used to translate * screen content into synthesized speech or braille for visually impaired users. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class AccImpl extends AccessibilityImplementation - { + public class AccImpl extends AccessibilityImplementation + { /** * @private * Default state for all the components. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_NORMAL : uint = 0x00000000; + private static const STATE_SYSTEM_NORMAL : uint = 0x00000000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_FOCUSABLE : uint = 0x00100000; + private static const STATE_SYSTEM_FOCUSABLE : uint = 0x00100000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_FOCUSED : uint = 0x00000004; + private static const STATE_SYSTEM_FOCUSED : uint = 0x00000004; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_UNAVAILABLE : uint = 0x00000001; + private static const STATE_SYSTEM_UNAVAILABLE : uint = 0x00000001; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_NAMECHANGE : uint = 0x800C; + private static const EVENT_OBJECT_NAMECHANGE : uint = 0x800C; /** * @private (protected) * A reference to the UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var master : UIComponent; + protected var master : UIComponent; /** * @private (protected) * Accessibility Role of the component being made accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var role : uint; - + protected var role : uint; + /** * @private (protected) * All subclasses must override this property by returning an array * of strings that contains the events for which to listen. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function get eventsToHandle () : Array; - + protected function get eventsToHandle () : Array; + /** * @private * All subclasses must implement this function. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a new Accessibility Implementation instance for the specified component. * * @param component The UIComponent instance that this AccImpl instance * makes accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function AccImpl (component:UIComponent); + public function AccImpl (component:UIComponent); /** * @private * Returns the system role for the component. * * @param childID The child id. * * @return Role associated with the component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accRole (childID:uint) : uint; + public function get_accRole (childID:uint) : uint; /** * @private * Returns the name of the component. * * @param childID The child id. * * @return Name of the component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accName (childID:uint) : String; + public function get_accName (childID:uint) : String; /** * @private (protected) * Returns the name of the accessible component. All subclasses must * implement this instead of implementing get_accName. * * @param childID The child id. * * @return Name. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getName (childID:uint) : String; + protected function getName (childID:uint) : String; /** * @private (protected) * Returns the state of the accessible component. * * @param childID The child id. * * @return State. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getState (childID:uint) : uint; + protected function getState (childID:uint) : uint; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function getStatusName () : String; + private function getStatusName () : String; /** * @private (protected) * Handles events from the master component. * All AccImpl subclasses must implement this * to listen for events from its master component. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function eventHandler (event:Event) : void; - } -} + protected function eventHandler (event:Event) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ButtonAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ButtonAccImpl.as index b718a00689..09da81c12b 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ButtonAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ButtonAccImpl.as @@ -1,33 +1,33 @@ -package fl.accessibility -{ - import fl.controls.Button; - import fl.core.UIComponent; - +package fl.accessibility +{ + import fl.controls.Button; + import fl.core.UIComponent; + /** * The ButtonAccImpl class, also called the Button Accessibility Implementation class, * enables communication between a Button component and a screen reader. Screen readers are used * to translate screen content into synthesized speech or braille for visually impaired users. * *

    The ButtonAccImpl class supports system roles, object-based events, and states.

    * *

    A Button reports the role ROLE_SYSTEM_PUSHBUTTON (0x2B) to a screen * reader.

    * *

    A Button reports the following states to a screen reader:

    *
      *
    • STATE_SYSTEM_NORMAL (0x00000000)
    • *
    • STATE_SYSTEM_UNAVAILABLE (0x00000001)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_PRESSED (0x00000008)
    • *
    • STATE_SYSTEM_FOCUSABLE (0x00100000)
    • *
    * *

    A Button dispatches the following events to a screen reader:

    *
      *
    • EVENT_OBJECT_STATECHANGE (0x800A)
    • *
    • EVENT_OBJECT_NAMECHANGE (0x800C)
    • *
    * *

    The user of a screen reader can activate a button component by using the spacebar or the Enter key.

    * * @see fl.controls.Button Button * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ButtonAccImpl extends LabelButtonAccImpl - { + public class ButtonAccImpl extends LabelButtonAccImpl + { /** * @private * * Static variable triggering the hookAccessibility() method. * This is used for initializing ButtonAccImpl class to hook its * createAccessibilityImplementation() method to Button class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; - + private static var accessibilityHooked : Boolean; + /** * @private * * Static method for swapping the createAccessibilityImplementation() * method of Button with the ButtonAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a Button component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a ButtonAccImpl instance for the specified Button component. * * @param component The Button instance that this ButtonAccImpl instance * makes accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ButtonAccImpl (component:UIComponent); - } -} + public function ButtonAccImpl (component:UIComponent); + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/CheckBoxAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/CheckBoxAccImpl.as index 69dd85066a..e5f5bf41c2 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/CheckBoxAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/CheckBoxAccImpl.as @@ -1,46 +1,46 @@ -package fl.accessibility -{ - import fl.controls.LabelButton; - import fl.controls.CheckBox; - import fl.core.UIComponent; - +package fl.accessibility +{ + import fl.controls.LabelButton; + import fl.controls.CheckBox; + import fl.core.UIComponent; + /** * The CheckBoxAccImpl class, also called the CheckBox Accessibility Implementation class, * is used to make a CheckBox component accessible. This class enables communication * between a CheckBox component and a screen reader. Screen readers are used to translate * screen content into synthesized speech or braille for visually impaired users. * *

    The CheckBoxAccImpl class supports system roles, object-based events, and states.

    * *

    A CheckBox reports the role ROLE_SYSTEM_CHECKBUTTON (0x2C) to a screen * reader.

    * *

    A CheckBox reports the following states to a screen reader:

    *
      *
    • STATE_SYSTEM_NORMAL (0x00000000)
    • *
    • STATE_SYSTEM_UNAVAILABLE (0x00000001)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_PRESSED (0x00000008)
    • *
    • STATE_SYSTEM_CHECKED (0x00000010)
    • *
    • STATE_SYSTEM_FOCUSABLE (0x00100000)
    • *
    * *

    A CheckBox dispatches the following events to a screen reader:

    *
      *
    • EVENT_OBJECT_STATECHANGE (0x800A)
    • *
    • EVENT_OBJECT_NAMECHANGE (0x800C)
    • *
    * *

    Screen reader users can activate a Checkbox component with the spacebar or the Enter key.

    * * @see fl.controls.CheckBox CheckBox * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class CheckBoxAccImpl extends LabelButtonAccImpl - { + public class CheckBoxAccImpl extends LabelButtonAccImpl + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing CheckBoxAccImpl class to hook its * createAccessibilityImplementation() method to CheckBox class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; + private static var accessibilityHooked : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_CHECKED : uint = 0x00000010; - + private static const STATE_SYSTEM_CHECKED : uint = 0x00000010; + /** * @private * Static method for swapping the createAccessibilityImplementation() * method of CheckBox with the CheckBoxAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a CheckBox component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a CheckBoxAccImpl instance for the specified CheckBox component. * * @param component The CheckBox instance that this CheckBoxAccImpl instance * makes accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function CheckBoxAccImpl (component:UIComponent); + public function CheckBoxAccImpl (component:UIComponent); /** * @private * IAccessible method for returning the state of the CheckBox. * States are predefined for all the components in MSAA. * Values are assigned to each state. * Depending upon whether the CheckBox is checked or unchecked, * a value is returned. * * @param childID The child id. * * @return State. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accState (childID:uint) : uint; + public function get_accState (childID:uint) : uint; /** * @private * IAccessible method for returning the default action of * the CheckBox, which is Check or UnCheck depending on the state. * * @param childID The child id. * * @return DefaultAction. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accDefaultAction (childID:uint) : String; - } -} + public function get_accDefaultAction (childID:uint) : String; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ComboBoxAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ComboBoxAccImpl.as index aa53b4e002..c0d828160c 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ComboBoxAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ComboBoxAccImpl.as @@ -1,88 +1,88 @@ -package fl.accessibility -{ - import flash.accessibility.Accessibility; - import flash.events.Event; - import fl.controls.ComboBox; - import fl.core.UIComponent; - +package fl.accessibility +{ + import flash.accessibility.Accessibility; + import flash.events.Event; + import fl.controls.ComboBox; + import fl.core.UIComponent; + /** * The ComboBoxAccImpl class, also called the ComboBox Accessibility Implementation class, * is used to make a ComboBox component accessible. * *

    The ComboBoxAccImpl class supports system roles, object-based events, and states.

    * *

    A ComboBox reports the role ROLE_SYSTEM_COMBOBOX (0x2E) to a screen * reader. Items of a ComboBox report the role ROLE_SYSTEM_LISTITEM (0x22).

    * *

    A ComboBox reports the following states to a screen reader:

    *
      *
    • STATE_SYSTEM_NORMAL (0x00000000)
    • *
    • STATE_SYSTEM_UNAVAILABLE (0x00000001)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_PRESSED (0x00000008)
    • *
    • STATE_SYSTEM_CHECKED (0x00000010)
    • *
    • STATE_SYSTEM_FOCUSABLE (0x00100000)
    • *
    * *

    Additionally, items of a ComboBox report the following states:

    *
      *
    • STATE_SYSTEM_SELECTED (0x00000002)
    • *
    • STATE_SYSTEM_SELECTABLE (0x00200000)
    • *
    * *

    A ComboBox dispatches the following events to a screen reader:

    *
      *
    • EVENT_OBJECT_SELECTION (0x8006)
    • *
    • EVENT_OBJECT_STATECHANGE (0x800A)
    • *
    • EVENT_OBJECT_NAMECHANGE (0x800C)
    • *
    • EVENT_OBJECT_VALUECHANGE (0x800E)
    • *
    * * @see fl.controls.ComboBox ComboBox * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ComboBoxAccImpl extends AccImpl - { + public class ComboBoxAccImpl extends AccImpl + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing ComboBoxAccImpl class to hook its * createAccessibilityImplementation() method to ComboBox class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; + private static var accessibilityHooked : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const ROLE_SYSTEM_LISTITEM : uint = 0x22; + private static const ROLE_SYSTEM_LISTITEM : uint = 0x22; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_FOCUSED : uint = 0x00000004; + private static const STATE_SYSTEM_FOCUSED : uint = 0x00000004; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_SELECTABLE : uint = 0x00200000; + private static const STATE_SYSTEM_SELECTABLE : uint = 0x00200000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_SELECTED : uint = 0x00000002; + private static const STATE_SYSTEM_SELECTED : uint = 0x00000002; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_VALUECHANGE : uint = 0x800E; + private static const EVENT_OBJECT_VALUECHANGE : uint = 0x800E; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_SELECTION : uint = 0x8006; - + private static const EVENT_OBJECT_SELECTION : uint = 0x8006; + /** * @private * Array of events that we should listen for from the master component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function get eventsToHandle () : Array; - + protected function get eventsToHandle () : Array; + /** * @private * Static method for swapping the createAccessibilityImplementation() * method of ComboBox with the ComboBoxAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * * Method for creating the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a ComboBox component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a new ComboBox Accessibility Implementation. * * @param master The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ComboBoxAccImpl (master:UIComponent); + public function ComboBoxAccImpl (master:UIComponent); /** * @private * Gets the role for the component. * * @param childID uint * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accRole (childID:uint) : uint; + public function get_accRole (childID:uint) : uint; /** * @private * IAccessible method for returning the value of the ComboBox * (which would be the text of the item selected). * The ComboBox should return the content of the TextField as the value. * * @param childID uint * * @return Value string * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accValue (childID:uint) : String; + public function get_accValue (childID:uint) : String; /** * @private * IAccessible method for returning the state of the ListItem * (basically to remove 'not selected'). * States are predefined for all the components in MSAA. * Values are assigned to each state. * Depending upon the listItem being Selected, Selectable, * Invisible, Offscreen, a value is returned. * * @param childID * * @return * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accState (childID:uint) : uint; + public function get_accState (childID:uint) : uint; /** * @private * Method to return an array of childIDs. * * @return * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getChildIDArray () : Array; + public function getChildIDArray () : Array; /** * @private * Method for returning the name of the ComboBox * For children items, it would add m of n string to the name. * ComboBox should return the name specified in the AccessibilityProperties. * * @param childID * * @return * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getName (childID:uint) : String; + protected function getName (childID:uint) : String; /** * @private * Override the generic event handler. * All AccImpl must implement this to listen for events * from its master component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function eventHandler (event:Event) : void; - } -} + protected function eventHandler (event:Event) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/DataGridAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/DataGridAccImpl.as index 4489543904..7b20a5ef50 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/DataGridAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/DataGridAccImpl.as @@ -1,115 +1,115 @@ -package fl.accessibility -{ - import flash.events.Event; - import flash.accessibility.Accessibility; - import fl.events.DataGridEvent; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.SelectableList; - import fl.controls.DataGrid; - import fl.core.UIComponent; - +package fl.accessibility +{ + import flash.events.Event; + import flash.accessibility.Accessibility; + import fl.events.DataGridEvent; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.SelectableList; + import fl.controls.DataGrid; + import fl.core.UIComponent; + /** * The DataGridAccImpl class, also called the DataGrid Accessibility Implementation class, * is used to make a DataGrid component accessible. * *

    The DataGridAccImpl class supports system roles, object-based events, and states.

    * *

    A DataGrid reports the role ROLE_SYSTEM_LIST (0x21) to a screen * reader. Items of a DataGrid report the role ROLE_SYSTEM_LISTITEM (0x22).

    * *

    A DataGrid reports the following states to a screen reader:

    *
      *
    • STATE_SYSTEM_NORMAL (0x00000000)
    • *
    • STATE_SYSTEM_UNAVAILABLE (0x00000001)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_FOCUSABLE (0x00100000)
    • *
    * *

    Additionally, items of a DataGrid report the following states:

    *
      *
    • STATE_SYSTEM_SELECTED (0x00000002)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_INVISIBLE (0x00008000)
    • *
    • STATE_SYSTEM_OFFSCREEN (0x00010000)
    • *
    • STATE_SYSTEM_SELECTABLE (0x00200000)
    • *
    * *

    A DataGrid dispatches the following events to a screen reader:

    *
      *
    • EVENT_OBJECT_FOCUS (0x8005)
    • *
    • EVENT_OBJECT_SELECTION (0x8006)
    • *
    • EVENT_OBJECT_STATECHANGE (0x800A)
    • *
    • EVENT_OBJECT_NAMECHANGE (0x800C)
    • *
    * * @see fl.controls.DataGrid DataGrid * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataGridAccImpl extends SelectableListAccImpl - { + public class DataGridAccImpl extends SelectableListAccImpl + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing DataGridAccImpl class to hook its * createAccessibilityImplementation() method to DataGrid class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; + private static var accessibilityHooked : Boolean; /** * @private * Role of listItem. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const ROLE_SYSTEM_LISTITEM : uint = 0x22; + private static const ROLE_SYSTEM_LISTITEM : uint = 0x22; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_FOCUSED : uint = 0x00000004; + private static const STATE_SYSTEM_FOCUSED : uint = 0x00000004; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_INVISIBLE : uint = 0x00008000; + private static const STATE_SYSTEM_INVISIBLE : uint = 0x00008000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_OFFSCREEN : uint = 0x00010000; + private static const STATE_SYSTEM_OFFSCREEN : uint = 0x00010000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_SELECTABLE : uint = 0x00200000; + private static const STATE_SYSTEM_SELECTABLE : uint = 0x00200000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_SELECTED : uint = 0x00000002; + private static const STATE_SYSTEM_SELECTED : uint = 0x00000002; /** * @private * Event emitted if 1 item is selected. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_FOCUS : uint = 0x8005; + private static const EVENT_OBJECT_FOCUS : uint = 0x8005; /** * @private * Event emitted if 1 item is selected. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_SELECTION : uint = 0x8006; - + private static const EVENT_OBJECT_SELECTION : uint = 0x8006; + /** * @private * Array of events that we should listen for from the master component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function get eventsToHandle () : Array; - + protected function get eventsToHandle () : Array; + /** * @private * Static method for swapping the createAccessibilityImplementation() * method of DataGrid with the DataGridAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a DataGrid component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a new List Accessibility Implementation. * * @param master The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function DataGridAccImpl (master:UIComponent); + public function DataGridAccImpl (master:UIComponent); /** * @private * Gets the role for the component. * * @param childID Children of the component * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accRole (childID:uint) : uint; + public function get_accRole (childID:uint) : uint; /** * @private * IAccessible method for returning the value of the ListItem/DataGrid * which is spoken out by the screen reader * The DataGrid should return the name of the currently selected item * with m of n string as value when focus moves to DataGrid. * * @param childID * * @return Name * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accValue (childID:uint) : String; + public function get_accValue (childID:uint) : String; /** * @private * IAccessible method for returning the state of the grid item. * States are predefined for all the components in MSAA. * Values are assigned to each state. * Depending upon the GridItem being Selected, Selectable, Invisible, * Offscreen, a value is returned. * * @param childID uint * * @return State uint * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accState (childID:uint) : uint; + public function get_accState (childID:uint) : uint; /** * @private * IAccessible method for executing the Default Action. * * @param childID uint * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function accDoDefaultAction (childID:uint) : void; + public function accDoDefaultAction (childID:uint) : void; /** * @private * Method to return an array of childIDs. * * @return Array * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getChildIDArray () : Array; + public function getChildIDArray () : Array; /** * @private * IAccessible method for returning the bounding box of the GridItem. * * @param childID uint * * @return Location Object * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function accLocation (childID:uint) : *; + public function accLocation (childID:uint) : *; /** * @private * IAccessible method for returning the childFocus of the DataGrid. * * @param childID uint * * @return focused childID. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accFocus () : uint; + public function get_accFocus () : uint; /** * @private * method for returning the name of the DataGrid/ListItem * which is spoken out by the screen reader * The ListItem should return the label as the name with m of n string and * DataGrid should return the name specified in the AccessibilityProperties. * * @param childID uint * * @return Name * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getName (childID:uint) : String; + protected function getName (childID:uint) : String; /** * @private * Override the generic event handler. * All AccImpl must implement this to listen * for events from its master component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function eventHandler (event:Event) : void; + protected function eventHandler (event:Event) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function getItemAt (index:int) : Object; - } -} + private function getItemAt (index:int) : Object; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/LabelButtonAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/LabelButtonAccImpl.as index 9978b3e7d5..7e8956135e 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/LabelButtonAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/LabelButtonAccImpl.as @@ -1,75 +1,75 @@ -package fl.accessibility -{ - import flash.accessibility.Accessibility; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.ui.Keyboard; - import fl.controls.LabelButton; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - +package fl.accessibility +{ + import flash.accessibility.Accessibility; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.ui.Keyboard; + import fl.controls.LabelButton; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + /** * The LabelButtonAccImpl class, also called the LabelButton Accessibility Implementation class, * is used to make a LabelButton component accessible. This class enables communication * between a LabelButton component and a screen reader. Screen readers are used to translate * screen content into synthesized speech or braille for visually impaired users. * *

    The LabelButtonAccImpl class supports system roles, object-based events, and states.

    * *

    A LabelButton reports the role ROLE_SYSTEM_PUSHBUTTON (0x2B) to a screen * reader.

    * *

    A LabelButton reports the following states to a screen reader:

    *
      *
    • STATE_SYSTEM_NORMAL (0x00000000)
    • *
    • STATE_SYSTEM_UNAVAILABLE (0x00000001)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_PRESSED (0x00000008)
    • *
    • STATE_SYSTEM_FOCUSABLE (0x00100000)
    • *
    * *

    A LabelButton dispatches the following events to a screen reader:

    *
      *
    • EVENT_OBJECT_STATECHANGE (0x800A)
    • *
    • EVENT_OBJECT_NAMECHANGE (0x800C)
    • *
    * * @see fl.controls.LabelButton LabelButton * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class LabelButtonAccImpl extends AccImpl - { + public class LabelButtonAccImpl extends AccImpl + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing LabelButtonAccImpl class to hook its * createAccessibilityImplementation() method to LabelButton class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; + private static var accessibilityHooked : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_PRESSED : uint = 0x00000008; + private static const STATE_SYSTEM_PRESSED : uint = 0x00000008; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_NAMECHANGE : uint = 0x800C; + private static const EVENT_OBJECT_NAMECHANGE : uint = 0x800C; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_STATECHANGE : uint = 0x800A; - + private static const EVENT_OBJECT_STATECHANGE : uint = 0x800A; + /** * @private * Array of events that we should listen for from the master component. * * @return * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function get eventsToHandle () : Array; - + protected function get eventsToHandle () : Array; + /** * @private * Static method for swapping the createAccessibilityImplementation() * method of LabelButton with the LabelButtonAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a LabelButton component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a new LabelButtonAccImpl instance for the specified LabelButton component. * * @param component The LabelButton instance that this LabelButtonAccImpl instance * makes accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function LabelButtonAccImpl (component:UIComponent); + public function LabelButtonAccImpl (component:UIComponent); /** * @private * IAccessible method for returning the state of the LabelButton. * States are predefined for all the components in MSAA. * Values are assigned to each state. * Depending upon the button being pressed or released, * a value is returned. * * @param childID The child id. * * @return State. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accState (childID:uint) : uint; + public function get_accState (childID:uint) : uint; /** * @private * IAccessible method for returning the default action * of the LabelButton, which is Press. * * @param childID The child id * * @return DefaultAction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accDefaultAction (childID:uint) : String; + public function get_accDefaultAction (childID:uint) : String; /** * @private * IAccessible method for performing the default action * associated with LabelButton, which is Press. * * @param childID The child id. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function accDoDefaultAction (childID:uint) : void; + public function accDoDefaultAction (childID:uint) : void; /** * @private * method for returning the name of the LabelButton * which is spoken out by the screen reader * The LabelButton should return the label inside as the name of the LabelButton. * The name returned here would take precedence over the name * specified in the Accessibility panel. * * @param childID The child id. * * @return Name. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getName (childID:uint) : String; + protected function getName (childID:uint) : String; /** * @private * Override the generic event handler. * All AccImpl must implement this to listen for events from its master component. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function eventHandler (event:Event) : void; - } -} + protected function eventHandler (event:Event) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ListAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ListAccImpl.as index 6f7599cfee..8b55aab4e1 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ListAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/ListAccImpl.as @@ -1,44 +1,44 @@ -package fl.accessibility -{ - import flash.accessibility.Accessibility; - import flash.events.Event; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.List; - import fl.core.UIComponent; - +package fl.accessibility +{ + import flash.accessibility.Accessibility; + import flash.events.Event; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.List; + import fl.core.UIComponent; + /** * The ListAccImpl class, also called the List Accessiblity Implementation class, * is used to make a List component accessible. * *

    The ListAccImpl class supports system roles, object-based events, and states.

    * *

    A List reports the role ROLE_SYSTEM_LIST (0x21) to a screen * reader. Items of a List report the role ROLE_SYSTEM_LISTITEM (0x22).

    * *

    A List reports the following states to a screen reader:

    *
      *
    • STATE_SYSTEM_NORMAL (0x00000000)
    • *
    • STATE_SYSTEM_UNAVAILABLE (0x00000001)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_FOCUSABLE (0x00100000)
    • *
    * *

    Additionally, items of a List report the following states:

    *
      *
    • STATE_SYSTEM_SELECTED (0x00000002)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_INVISIBLE (0x00008000)
    • *
    • STATE_SYSTEM_OFFSCREEN (0x00010000)
    • *
    • STATE_SYSTEM_SELECTABLE (0x00200000)
    • *
    * *

    A List dispatches the following events to a screen reader:

    *
      *
    • EVENT_OBJECT_FOCUS (0x8005)
    • *
    • EVENT_OBJECT_SELECTION (0x8006)
    • *
    • EVENT_OBJECT_STATECHANGE (0x800A)
    • *
    • EVENT_OBJECT_NAMECHANGE (0x800C)
    • *
    * * @see fl.controls.List List * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ListAccImpl extends SelectableListAccImpl - { + public class ListAccImpl extends SelectableListAccImpl + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing ListAccImpl class to hook its * createAccessibilityImplementation() method to List class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; - + private static var accessibilityHooked : Boolean; + /** * @private * Static method for swapping the createAccessibilityImplementation() * method of List with the ListAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a List component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a new List Accessibility Implementation. * * @param master The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ListAccImpl (master:UIComponent); + public function ListAccImpl (master:UIComponent); /** * @private * IAccessible method for returning the value of the ListItem/List * which is spoken out by the screen reader * The List should return the name of the currently selected item * with m of n string as value when focus moves to List. * * @param childID The child id * * @return Value * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accValue (childID:uint) : String; + public function get_accValue (childID:uint) : String; /** * @private * method for returning the name of the ListItem/List * which is spoken out by the screen reader. * The ListItem should return the label as the name * with m of n string and List should return the name * specified in the Accessibility Panel. * * @param childID The child id. * * @return Name. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getName (childID:uint) : String; - } -} + protected function getName (childID:uint) : String; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/RadioButtonAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/RadioButtonAccImpl.as index 261ac34c8c..edf351f107 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/RadioButtonAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/RadioButtonAccImpl.as @@ -1,33 +1,33 @@ -package fl.accessibility -{ - import fl.controls.RadioButton; - import fl.core.UIComponent; - +package fl.accessibility +{ + import fl.controls.RadioButton; + import fl.core.UIComponent; + /** * The RadioButtonAccImpl class, also called the RadioButton Accessibility Implementation class, * is used to make a RadioButton component accessible. This class enables communication * between a RadioButton component and a screen reader. Screen readers are used to translate * screen content into synthesized speech or braille for visually impaired users. * *

    The RadioButtonAccImpl class supports system roles, object-based events, and states.

    * *

    A RadioButton reports the role ROLE_SYSTEM_RADIOBUTTON (0x2D) to a screen * reader.

    * *

    A RadioButton reports the following states to a screen reader:

    *
      *
    • STATE_SYSTEM_NORMAL (0x00000000)
    • *
    • STATE_SYSTEM_UNAVAILABLE (0x00000001)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_PRESSED (0x00000008)
    • *
    • STATE_SYSTEM_CHECKED (0x00000010)
    • *
    • STATE_SYSTEM_FOCUSABLE (0x00100000)
    • *
    * *

    A RadioButton dispatches the following events to a screen reader:

    *
      *
    • EVENT_OBJECT_STATECHANGE (0x800A)
    • *
    • EVENT_OBJECT_NAMECHANGE (0x800C)
    • *
    * * @see fl.controls.RadioButton RadioButton * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class RadioButtonAccImpl extends CheckBoxAccImpl - { + public class RadioButtonAccImpl extends CheckBoxAccImpl + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing CheckBoxAccImpl class to hook its * createAccessibilityImplementation() method to CheckBox class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; - + private static var accessibilityHooked : Boolean; + /** * @private * Static method for swapping the createAccessibilityImplementation() * method of CheckBox with the CheckBoxAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a RadioButton component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a RadioButtonAccImpl instance for the specified RadioButton component. * * @param master The RadioButton instance that this AccImpl instance * makes accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function RadioButtonAccImpl (master:UIComponent); - } -} + public function RadioButtonAccImpl (master:UIComponent); + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/SelectableListAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/SelectableListAccImpl.as index caf5ab61aa..dbb1533463 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/SelectableListAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/SelectableListAccImpl.as @@ -1,121 +1,121 @@ -package fl.accessibility -{ - import flash.events.Event; - import flash.accessibility.Accessibility; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.SelectableList; - import fl.core.UIComponent; - +package fl.accessibility +{ + import flash.events.Event; + import flash.accessibility.Accessibility; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.SelectableList; + import fl.core.UIComponent; + /** * The SelectableListAccImpl class, also called the SelectableList Accessibility Implementation class, * is used to make a SelectableList component accessible. * * @see fl.controls.SelectableList SelectableList * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class SelectableListAccImpl extends AccImpl - { + public class SelectableListAccImpl extends AccImpl + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing SelectableListAccImpl class to hook its * createAccessibilityImplementation() method to SelectableList class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; + private static var accessibilityHooked : Boolean; /** * @private * Role of listItem. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const ROLE_SYSTEM_LISTITEM : uint = 0x22; + private static const ROLE_SYSTEM_LISTITEM : uint = 0x22; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_FOCUSED : uint = 0x00000004; + private static const STATE_SYSTEM_FOCUSED : uint = 0x00000004; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_INVISIBLE : uint = 0x00008000; + private static const STATE_SYSTEM_INVISIBLE : uint = 0x00008000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_OFFSCREEN : uint = 0x00010000; + private static const STATE_SYSTEM_OFFSCREEN : uint = 0x00010000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_SELECTABLE : uint = 0x00200000; + private static const STATE_SYSTEM_SELECTABLE : uint = 0x00200000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const STATE_SYSTEM_SELECTED : uint = 0x00000002; + private static const STATE_SYSTEM_SELECTED : uint = 0x00000002; /** * @private * Event emitted if 1 item is selected. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_FOCUS : uint = 0x8005; + private static const EVENT_OBJECT_FOCUS : uint = 0x8005; /** * @private * Event emitted if 1 item is selected. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static const EVENT_OBJECT_SELECTION : uint = 0x8006; - + private static const EVENT_OBJECT_SELECTION : uint = 0x8006; + /** * @private * Array of events that we should listen for from the master component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function get eventsToHandle () : Array; - + protected function get eventsToHandle () : Array; + /** * @private * Static method for swapping the createAccessibilityImplementation() * method of SelectableList with the SelectableListAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a SelectableList component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a new SelectableList Accessibility Implementation. * * @param master The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function SelectableListAccImpl (master:UIComponent); + public function SelectableListAccImpl (master:UIComponent); /** * @private * Gets the role for the component. * * @param childID The child id. * * @return Role. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accRole (childID:uint) : uint; + public function get_accRole (childID:uint) : uint; /** * @private * must be overridden in SelectableListAccImpl subclasses. * * @param childID The child id. * @return Value. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accValue (childID:uint) : String; + public function get_accValue (childID:uint) : String; /** * @private * IAccessible method for returning the state of the ListItem. * States are predefined for all the components in MSAA. * Values are assigned to each state. * Depending upon the listItem being Selected, Selectable, * Invisible, Offscreen, a value is returned. * * @param childID The child id. * * @return State. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accState (childID:uint) : uint; + public function get_accState (childID:uint) : uint; /** * @private * IAccessible method for returning the Default Action. * * @param childID The child id. * * @return DefaultAction. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accDefaultAction (childID:uint) : String; + public function get_accDefaultAction (childID:uint) : String; /** * @private * IAccessible method for executing the Default Action. * * @param childID The child id. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function accDoDefaultAction (childID:uint) : void; + public function accDoDefaultAction (childID:uint) : void; /** * @private * Method to return an array of childIDs. * * @return Array child ids * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getChildIDArray () : Array; + public function getChildIDArray () : Array; /** * @private * IAccessible method for returning the bounding box of the ListItem. * * @param childID The child id * * @return Object Location * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function accLocation (childID:uint) : *; + public function accLocation (childID:uint) : *; /** * @private * IAccessible method for returning the child Selections in the List. * * @param childID The child id * * @return Array child ids. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accSelection () : Array; + public function get_accSelection () : Array; /** * @private * IAccessible method for returning the childFocus of the List. * * @param childID The child id * * @return uint focused child id. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accFocus () : uint; + public function get_accFocus () : uint; /** * @private * IAccessible method for selecting an item. * * @param childID The child id * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function accSelect (selFlag:uint, childID:uint) : void; + public function accSelect (selFlag:uint, childID:uint) : void; /** * @private * must be overridden in SelectableListAccImpl subclasses * * @param childID The child id. * @return Name. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getName (childID:uint) : String; + protected function getName (childID:uint) : String; /** * @private * Override the generic event handler. * All AccImpl must implement this * to listen for events from its master component. * * @param event The event object * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function eventHandler (event:Event) : void; - } -} + protected function eventHandler (event:Event) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/TileListAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/TileListAccImpl.as index 897f8c3de6..f1e5c60094 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/TileListAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/TileListAccImpl.as @@ -1,44 +1,44 @@ -package fl.accessibility -{ - import flash.accessibility.Accessibility; - import flash.events.Event; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.TileList; - import fl.core.UIComponent; - +package fl.accessibility +{ + import flash.accessibility.Accessibility; + import flash.events.Event; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.TileList; + import fl.core.UIComponent; + /** * The TileListAccImpl class, also called the Tile List Accessibility Implementation class, is * used to make a TileList component accessible. This class enables communication * between a TileList component and a screen reader. Screen readers are used to translate * screen content into synthesized speech or braille for visually impaired users. * *

    The TileListAccImpl class supports system roles, object-based events, and states.

    * *

    A TileList reports the role ROLE_SYSTEM_LIST (0x21) to a screen * reader. Items of a TileList report the role ROLE_SYSTEM_LISTITEM (0x22).

    * *

    A TileList reports the following states to a screen reader:

    *
      *
    • STATE_SYSTEM_NORMAL (0x00000000)
    • *
    • STATE_SYSTEM_UNAVAILABLE (0x00000001)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_FOCUSABLE (0x00100000)
    • *
    * *

    Additionally, items of a TileList report the following states:

    *
      *
    • STATE_SYSTEM_SELECTED (0x00000002)
    • *
    • STATE_SYSTEM_FOCUSED (0x00000004)
    • *
    • STATE_SYSTEM_INVISIBLE (0x00008000)
    • *
    • STATE_SYSTEM_OFFSCREEN (0x00010000)
    • *
    • STATE_SYSTEM_SELECTABLE (0x00200000)
    • *
    * *

    A TileList dispatches the following events to a screen reader:

    *
      *
    • EVENT_OBJECT_FOCUS (0x8005)
    • *
    • EVENT_OBJECT_SELECTION (0x8006)
    • *
    • EVENT_OBJECT_STATECHANGE (0x800A)
    • *
    • EVENT_OBJECT_NAMECHANGE (0x800C)
    • *
    * * @see fl.controls.TileList TileList * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class TileListAccImpl extends SelectableListAccImpl - { + public class TileListAccImpl extends SelectableListAccImpl + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing TileListAccImpl class to hook its * createAccessibilityImplementation() method to the TileList class * before it gets called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; - + private static var accessibilityHooked : Boolean; + /** * @private * Static method for swapping the createAccessibilityImplementation() * method of the TileList class with the TileListAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a TileList component. This method is required for * the compiler to activate the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * Creates a new TileList Accessibility Implementation. * * @param master The UIComponent instance that this AccImpl instance * makes accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function TileListAccImpl (master:UIComponent); + public function TileListAccImpl (master:UIComponent); /** * @private * IAccessible method for returning the value of the ListItem/TileList * which is spoken out by the screen reader * The TileList should return the name of the currently selected item * with m of n string as value when focus moves to TileList. * * @param childID The child id * * @return String Value * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get_accValue (childID:uint) : String; + public function get_accValue (childID:uint) : String; /** * @private * This method retrieves the name of the ListItem/TileList * component that is spoken out by the screen reader. * The ListItem should return the label as the name * with m of n string and TileList should return the name * that is specified in the Accessibility Panel. * * @param childID The child id * * @return String Name * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getName (childID:uint) : String; - } -} + protected function getName (childID:uint) : String; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/UIComponentAccImpl.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/UIComponentAccImpl.as index 8499dee69c..0d881adc0d 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/UIComponentAccImpl.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/accessibility/UIComponentAccImpl.as @@ -1,44 +1,44 @@ -package fl.accessibility -{ - import flash.accessibility.Accessibility; - import flash.accessibility.AccessibilityProperties; - import fl.controls.ScrollBar; - import fl.core.UIComponent; - import flash.events.Event; - +package fl.accessibility +{ + import flash.accessibility.Accessibility; + import flash.accessibility.AccessibilityProperties; + import fl.controls.ScrollBar; + import fl.core.UIComponent; + import flash.events.Event; + /** * The UIComponentAccImpl class, also called the UIComponent Accessibility Implementation class, * is used to make a UIComponent accessible. This class enables communication * between a List-based component and a screen reader. Screen readers are used to translate * screen content into synthesized speech or braille for visually impaired users. * *

    The ListAccImpl class supports system roles, object-based events, and states.

    * * @internal * Adobe: Probably just a dup-and-revise error, but this last sentence references the BaseListAccImpl class. * Probably should refer to the UIComponentAccImpl class? * [CW] the whole description is wrong here. UIComponentAccImpl extends AccessibilityProperties * and not AccessibilityImplementation, and exists purely to wrap the accessibilityProperties * property of UIComponents (and to make the ScrollBar component silent to screenreaders). * * Metaliq: Claus, did you change the description above? I still see a mention of BaseListAccImpl class. (line 15, i changed it to ListAccImpl though) * * @see fl.core.UIComponent UIComponent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class UIComponentAccImpl extends AccessibilityProperties - { + public class UIComponentAccImpl extends AccessibilityProperties + { /** * @private * Static variable triggering the hookAccessibility() method. * This is used for initializing UIComponentAccImpl class to hook its * createAccessibilityImplementation() method to UIComponent class * before it gets called from UIComponent.initialize(). * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var accessibilityHooked : Boolean; + private static var accessibilityHooked : Boolean; /** * @private (protected) * A reference to the UIComponent itself. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var master : UIComponent; - + protected var master : UIComponent; + /** * @private * Static Method for swapping the createAccessibilityImplementation() * method of UIComponent with the UIComponentAccImpl class. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function hookAccessibility () : Boolean; + private static function hookAccessibility () : Boolean; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @param component The UIComponent instance that this AccImpl instance * is making accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function createAccessibilityImplementation (component:UIComponent) : void; + public static function createAccessibilityImplementation (component:UIComponent) : void; /** * Enables accessibility for a UIComponent component. * This method is required for the compiler to activate * the accessibility classes for a component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function enableAccessibility () : void; + public static function enableAccessibility () : void; /** * @private * @internal Nivesh says: I don't think we should document the constructors * for the accessibility classes. End-users just have to call the * static enableAccessibility method. They don't really create an * instance of the classes. * * Creates a new UIComponentAccImpl instance for the specified UIComponent component. * * @param master The UIComponent instance that this AccImpl instance * makes accessible. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function UIComponentAccImpl (component:UIComponent); + public function UIComponentAccImpl (component:UIComponent); /** * @private (protected) * Generic event handler. * All UIComponentAccImpl subclasses must implement this * to listen for events from its master component. * * @param event The event object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function eventHandler (event:Event) : void; - } -} + protected function eventHandler (event:Event) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/BaseScrollPane.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/BaseScrollPane.as index 7753512e30..ba0d1fbcad 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/BaseScrollPane.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/BaseScrollPane.as @@ -1,363 +1,363 @@ -package fl.containers -{ - import fl.core.UIComponent; - import fl.controls.BaseButton; - import fl.controls.ScrollBar; - import fl.events.ScrollEvent; - import fl.controls.ScrollPolicy; - import fl.controls.ScrollBarDirection; - import fl.core.InvalidationType; - import flash.display.DisplayObject; - import flash.events.Event; - import flash.events.MouseEvent; - import flash.display.DisplayObject; - import flash.display.Shape; - import flash.display.Graphics; - import flash.geom.Rectangle; - +package fl.containers +{ + import fl.core.UIComponent; + import fl.controls.BaseButton; + import fl.controls.ScrollBar; + import fl.events.ScrollEvent; + import fl.controls.ScrollPolicy; + import fl.controls.ScrollBarDirection; + import fl.core.InvalidationType; + import flash.display.DisplayObject; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.display.DisplayObject; + import flash.display.Shape; + import flash.display.Graphics; + import flash.geom.Rectangle; + /** * Dispatched when the user scrolls content by using the scroll bars on the * component or the wheel on a mouse device. * * @eventType fl.events.ScrollEvent.SCROLL * * @includeExample examples/ScrollPane.scroll.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="scroll", type="fl.events.ScrollEvent")] + [Event(name="scroll", type="fl.events.ScrollEvent")] /** * @copy fl.controls.ScrollBar#style:downArrowDisabledSkin * * @default ScrollArrowDown_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowDisabledSkin", type="Class")] + [Style(name="downArrowDisabledSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:downArrowDownSkin * * @default ScrollArrowDown_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowDownSkin", type="Class")] + [Style(name="downArrowDownSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:downArrowOverSkin * * @default ScrollArrowDown_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowOverSkin", type="Class")] + [Style(name="downArrowOverSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:downArrowUpSkin * * @default ScrollArrowDown_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowUpSkin", type="Class")] + [Style(name="downArrowUpSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbDisabledSkin * * @default ScrollThumb_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbDisabledSkin", type="Class")] + [Style(name="thumbDisabledSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbDownSkin * * @default ScrollThumb_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbDownSkin", type="Class")] + [Style(name="thumbDownSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbOverSkin * * @default ScrollThumb_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbOverSkin", type="Class")] + [Style(name="thumbOverSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbUpSkin * * @default ScrollThumb_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbUpSkin", type="Class")] + [Style(name="thumbUpSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:trackDisabledSkin * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackDisabledSkin", type="Class")] + [Style(name="trackDisabledSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:trackDownSkin * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackDownSkin", type="Class")] + [Style(name="trackDownSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:trackOverSkin * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackOverSkin", type="Class")] + [Style(name="trackOverSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:trackUpSkin * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackUpSkin", type="Class")] + [Style(name="trackUpSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:upArrowDisabledSkin * * @default ScrollArrowUp_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowDisabledSkin", type="Class")] + [Style(name="upArrowDisabledSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:upArrowDownSkin * * @default ScrollArrowUp_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowDownSkin", type="Class")] + [Style(name="upArrowDownSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:upArrowOverSkin * * @default ScrollArrowUp_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowOverSkin", type="Class")] + [Style(name="upArrowOverSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:upArrowUpSkin * * @default ScrollArrowUp_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowUpSkin", type="Class")] + [Style(name="upArrowUpSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbIcon * * @default ScrollBar_thumbIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbIcon", type="Class")] + [Style(name="thumbIcon", type="Class")] /** * @copy fl.controls.BaseButton#style:repeatDelay * * @default 500 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatDelay", type="Number", format="Time")] + [Style(name="repeatDelay", type="Number", format="Time")] /** * @copy fl.controls.BaseButton#style:repeatInterval * * @default 35 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatInterval", type="Number", format="Time")] + [Style(name="repeatInterval", type="Number", format="Time")] /** * The skin to be used as the background of the scroll pane. * * @default ScrollPane_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="skin", type="Class")] + [Style(name="skin", type="Class")] /** * Padding between the content (the component and scroll bar), and the outside edge of the background, in pixels. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] What does "control and scrollbar" mean here -- what is the relationship between these * elements and the content? I'd like to make this more understandable * but don't know how it should be written based on the current description. */ - [Style(name="contentPadding", type="Number", format="Length")] + [Style(name="contentPadding", type="Number", format="Length")] /** * When the enabled property is set to false, * interaction with the component is prevented and a white overlay is * displayed over the component, dimming the component contents. The * disabledAlpha style specifies the level of transparency * that is applied to this overlay. Valid values range from 0, for an * overlay that is completely transparent, to 1 for an overlay that is opaque. * * @default 0.5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledAlpha", type="Number", format="Length")] - + [Style(name="disabledAlpha", type="Number", format="Length")] + /** * The BaseScrollPane class handles basic scroll pane functionality including events, styling, * drawing the mask and background, the layout of scroll bars, and the handling of scroll positions. * *

    By default, the BaseScrollPane class is extended by the ScrollPane and SelectableList classes, * for all list-based components. This means that any component that uses horizontal or vertical * scrolling does not need to implement any scrolling, masking or layout logic, except for behavior * that is specific to the component.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class BaseScrollPane extends UIComponent - { + public class BaseScrollPane extends UIComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _verticalScrollBar : ScrollBar; + protected var _verticalScrollBar : ScrollBar; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _horizontalScrollBar : ScrollBar; + protected var _horizontalScrollBar : ScrollBar; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var contentScrollRect : Rectangle; + protected var contentScrollRect : Rectangle; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var disabledOverlay : Shape; + protected var disabledOverlay : Shape; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var background : DisplayObject; + protected var background : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var contentWidth : Number; + protected var contentWidth : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var contentHeight : Number; + protected var contentHeight : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _horizontalScrollPolicy : String; + protected var _horizontalScrollPolicy : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _verticalScrollPolicy : String; + protected var _verticalScrollPolicy : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var contentPadding : Number; + protected var contentPadding : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var availableWidth : Number; + protected var availableWidth : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var availableHeight : Number; + protected var availableHeight : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var vOffset : Number; + protected var vOffset : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var vScrollBar : Boolean; + protected var vScrollBar : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var hScrollBar : Boolean; + protected var hScrollBar : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _maxHorizontalScrollPosition : Number; + protected var _maxHorizontalScrollPosition : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _horizontalPageScrollSize : Number; + protected var _horizontalPageScrollSize : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _verticalPageScrollSize : Number; + protected var _verticalPageScrollSize : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var defaultLineScrollSize : Number; + protected var defaultLineScrollSize : Number; /** * @private (protected) * * If false, uses contentWidth to determine hscroll, otherwise uses fixed _maxHorizontalScroll value. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var useFixedHorizontalScrolling : Boolean; + protected var useFixedHorizontalScrolling : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _useBitmpScrolling : Boolean; + protected var _useBitmpScrolling : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected static const SCROLL_BAR_STYLES : Object; - + protected static const SCROLL_BAR_STYLES : Object; + /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets a value that indicates the state of the horizontal scroll * bar. A value of ScrollPolicy.ON indicates that the horizontal * scroll bar is always on; a value of ScrollPolicy.OFF indicates * that the horizontal scroll bar is always off; and a value of ScrollPolicy.AUTO * indicates that its state automatically changes. This property is used with * other scrolling properties to set the setScrollProperties() method * of the scroll bar. * * @default ScrollPolicy.AUTO * * @see #verticalScrollPolicy * @see fl.controls.ScrollPolicy ScrollPolicy * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollPolicy () : String; + public function get horizontalScrollPolicy () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalScrollPolicy (value:String) : void; + public function set horizontalScrollPolicy (value:String) : void; /** * Gets or sets a value that indicates the state of the vertical scroll * bar. A value of ScrollPolicy.ON indicates that the vertical * scroll bar is always on; a value of ScrollPolicy.OFF indicates * that the vertical scroll bar is always off; and a value of ScrollPolicy.AUTO * indicates that its state automatically changes. This property is used with * other scrolling properties to set the setScrollProperties() method * of the scroll bar. * * @default ScrollPolicy.AUTO * * @see #horizontalScrollPolicy * @see fl.controls.ScrollPolicy ScrollPolicy * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get verticalScrollPolicy () : String; + public function get verticalScrollPolicy () : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set verticalScrollPolicy (value:String) : void; + public function set verticalScrollPolicy (value:String) : void; /** * Gets or sets a value that describes the amount of content to be scrolled, * horizontally, when a scroll arrow is clicked. This value is measured in pixels. * * @default 4 * * @see #horizontalPageScrollSize * @see #verticalLineScrollSize * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalLineScrollSize () : Number; + public function get horizontalLineScrollSize () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalLineScrollSize (value:Number) : void; + public function set horizontalLineScrollSize (value:Number) : void; /** * Gets or sets a value that describes how many pixels to scroll vertically when a scroll arrow is clicked. * * @default 4 * * @see #horizontalLineScrollSize * @see #verticalPageScrollSize * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get verticalLineScrollSize () : Number; + public function get verticalLineScrollSize () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set verticalLineScrollSize (value:Number) : void; + public function set verticalLineScrollSize (value:Number) : void; /** * Gets or sets a value that describes the horizontal position of the * horizontal scroll bar in the scroll pane, in pixels. * * @default 0 * * @includeExample examples/BaseScrollPane.horizontalScrollPosition.1.as -noswf * * @see #maxHorizontalScrollPosition * @see #verticalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollPosition () : Number; + public function get horizontalScrollPosition () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalScrollPosition (value:Number) : void; + public function set horizontalScrollPosition (value:Number) : void; /** * Gets or sets a value that describes the vertical position of the * vertical scroll bar in the scroll pane, in pixels. * * @default 0 * * @includeExample examples/BaseScrollPane.horizontalScrollPosition.1.as -noswf * * @see #horizontalScrollPosition * @see #maxVerticalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get verticalScrollPosition () : Number; + public function get verticalScrollPosition () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set verticalScrollPosition (value:Number) : void; + public function set verticalScrollPosition (value:Number) : void; /** * Gets the maximum horizontal scroll position for the current content, in pixels. * * @see #horizontalScrollPosition * @see #maxVerticalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxHorizontalScrollPosition () : Number; + public function get maxHorizontalScrollPosition () : Number; /** * Gets the maximum vertical scroll position for the current content, in pixels. * * @see #maxHorizontalScrollPosition * @see #verticalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxVerticalScrollPosition () : Number; + public function get maxVerticalScrollPosition () : Number; /** * When set to true, the cacheAsBitmap property for the scrolling content is set * to true; when set to false this value is turned off. * *

    Note: Setting this property to true increases scrolling performance.

    * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get useBitmapScrolling () : Boolean; + public function get useBitmapScrolling () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set useBitmapScrolling (value:Boolean) : void; + public function set useBitmapScrolling (value:Boolean) : void; /** * Gets or sets the count of pixels by which to move the scroll thumb * on the horizontal scroll bar when the scroll bar track is pressed. When * this value is 0, this property retrieves the available width of the component. * * @default 0 * * @see #horizontalLineScrollSize * @see #verticalPageScrollSize * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalPageScrollSize () : Number; + public function get horizontalPageScrollSize () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalPageScrollSize (value:Number) : void; + public function set horizontalPageScrollSize (value:Number) : void; /** * Gets or sets the count of pixels by which to move the scroll thumb * on the vertical scroll bar when the scroll bar track is pressed. When * this value is 0, this property retrieves the available height of the component. * * @default 0 * * @see #horizontalPageScrollSize * @see #verticalLineScrollSize * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] Is available height specified in pixels? */ - public function get verticalPageScrollSize () : Number; + public function get verticalPageScrollSize () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set verticalPageScrollSize (value:Number) : void; + public function set verticalPageScrollSize (value:Number) : void; /** * Gets a reference to the horizontal scroll bar. * * @see #verticalScrollBar * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollBar () : ScrollBar; + public function get horizontalScrollBar () : ScrollBar; /** * Gets a reference to the vertical scroll bar. * * @see #horizontalScrollBar * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get verticalScrollBar () : ScrollBar; - + public function get verticalScrollBar () : ScrollBar; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setContentSize (width:Number, height:Number) : void; + protected function setContentSize (width:Number, height:Number) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleScroll (event:ScrollEvent) : void; + protected function handleScroll (event:ScrollEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleWheel (event:MouseEvent) : void; + protected function handleWheel (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setHorizontalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setHorizontalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setStyles () : void; + protected function setStyles () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBackground () : void; + protected function drawBackground () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawDisabledOverlay () : void; + protected function drawDisabledOverlay () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function calculateAvailableSize () : void; + protected function calculateAvailableSize () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function calculateContentWidth () : void; + protected function calculateContentWidth () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateChildren () : void; - } -} + protected function updateChildren () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/ScrollPane.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/ScrollPane.as index 802db0560f..997ec9c06f 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/ScrollPane.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/ScrollPane.as @@ -1,251 +1,251 @@ -package fl.containers -{ - import fl.containers.BaseScrollPane; - import fl.controls.ScrollBar; - import fl.controls.ScrollPolicy; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ScrollEvent; - import fl.managers.IFocusManagerComponent; - import flash.display.DisplayObject; - import flash.display.Loader; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.events.ProgressEvent; - import flash.events.SecurityErrorEvent; - import flash.events.IOErrorEvent; - import flash.events.HTTPStatusEvent; - import flash.geom.Rectangle; - import flash.net.URLRequest; - import flash.system.ApplicationDomain; - import flash.system.LoaderContext; - import flash.ui.Keyboard; - +package fl.containers +{ + import fl.containers.BaseScrollPane; + import fl.controls.ScrollBar; + import fl.controls.ScrollPolicy; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ScrollEvent; + import fl.managers.IFocusManagerComponent; + import flash.display.DisplayObject; + import flash.display.Loader; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.events.ProgressEvent; + import flash.events.SecurityErrorEvent; + import flash.events.IOErrorEvent; + import flash.events.HTTPStatusEvent; + import flash.geom.Rectangle; + import flash.net.URLRequest; + import flash.system.ApplicationDomain; + import flash.system.LoaderContext; + import flash.ui.Keyboard; + /** * @copy BaseScrollPane#event:scroll * * @includeExample examples/ScrollPane.scroll.1.as -noswf * * @eventType fl.events.ScrollEvent.SCROLL * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="scroll", type="fl.events.ScrollEvent")] + [Event(name="scroll", type="fl.events.ScrollEvent")] /** * Dispatched while content is loading. * * @eventType flash.events.ProgressEvent.PROGRESS * * @includeExample examples/ScrollPane.percentLoaded.1.as -noswf * * @see #event:complete * @see #bytesLoaded * @see #bytesTotal * @see #percentLoaded * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="progress", type="flash.events.ProgressEvent")] + [Event(name="progress", type="flash.events.ProgressEvent")] /** * Dispatched when content has finished loading. * * @includeExample examples/ScrollPane.complete.1.as -noswf * * @eventType flash.events.Event.COMPLETE * * @see #event:progress * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="complete", type="flash.events.Event")] + [Event(name="complete", type="flash.events.Event")] /** * Dispatched when the properties and methods of a loaded SWF file are accessible. * The following conditions must exist for this event to be dispatched: *
      *
    • All the properties and methods that are associated with the loaded object, * as well as those that are associated with the component, must be accessible.
    • *
    • The constructors for all child objects must have completed.
    • *
    * * @eventType flash.events.Event.INIT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("init", type="flash.events.Event")] + [Event("init", type="flash.events.Event")] /** * Dispatched after an input or output error occurs. * * @includeExample examples/UILoader.ioError.1.as -noswf * * @eventType flash.events.IOErrorEvent.IO_ERROR * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("ioError", type="flash.events.IOErrorEvent")] + [Event("ioError", type="flash.events.IOErrorEvent")] /** * Dispatched after a network operation starts. * * @eventType flash.events.Event.OPEN * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("open", type="flash.events.Event")] + [Event("open", type="flash.events.Event")] /** * Dispatched after a security error occurs while content is loading. * * @eventType flash.events.SecurityErrorEvent.SECURITY_ERROR * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("securityError", type="flash.events.SecurityErrorEvent")] + [Event("securityError", type="flash.events.SecurityErrorEvent")] /** * Dispatched when content is loading. This event is dispatched regardless of * whether the load operation was triggered by an auto-load process or an explicit call to the * load() method. * * @includeExample examples/UILoader.progress.1.as -noswf * * @eventType flash.events.ProgressEvent.PROGRESS * * @see #event:complete * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("progress", type="flash.events.ProgressEvent")] + [Event("progress", type="flash.events.ProgressEvent")] /** * The skin that shows when the scroll pane is disabled. * * @default ScrollPane_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledSkin", type="Class")] + [Style(name="disabledSkin", type="Class")] /** * The default skin shown on the scroll pane. * * @default ScrollPane_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * The amount of padding to put around the content in the scroll pane, in pixels. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="contentPadding", type="Number", format="Length")] - + [Style(name="contentPadding", type="Number", format="Length")] + /** * The ScrollPane component displays display objects and JPEG, GIF, and PNG files, * as well as SWF files, in a scrollable area. You can use a scroll pane to * limit the screen area that is occupied by these media types. * The scroll pane can display content that is loaded from a local * disk or from the Internet. You can set this content while * authoring and, at run time, by using ActionScript. After the scroll * pane has focus, if its content has valid tab stops, those * markers receive focus. After the last tab stop in the content, * focus moves to the next component. The vertical and horizontal * scroll bars in the scroll pane do not receive focus. * *

    Note: When content is being loaded from a different * domain or sandbox, the properties of the content may be inaccessible * for security reasons. For more information about how domain security * affects the load process, see the Loader class.

    * *

    Note: When loading very large image files into a ScrollPane object, * it may be necessary to listen for the complete event and then resize the * ScrollPane using the setSize() method. See the complete * event example.

    * * @see flash.display.Loader Loader * * @includeExample examples/ScrollPaneExample.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ScrollPane extends BaseScrollPane implements IFocusManagerComponent - { + public class ScrollPane extends BaseScrollPane implements IFocusManagerComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _source : Object; + protected var _source : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _scrollDrag : Boolean; + protected var _scrollDrag : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var contentClip : Sprite; + protected var contentClip : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var loader : Loader; + protected var loader : Loader; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var xOffset : Number; + protected var xOffset : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var yOffset : Number; + protected var yOffset : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var scrollDragHPos : Number; + protected var scrollDragHPos : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var scrollDragVPos : Number; + protected var scrollDragVPos : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var currentContent : Object; + protected var currentContent : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * Gets or sets a value that indicates whether scrolling occurs when a * user drags on content within the scroll pane. A value of true * indicates that scrolling occurs when a user drags on the content; a value * of false indicates that it does not. * * @default false * * @includeExample examples/ScrollPane.scrollDrag.1.as -noswf * * @see #event:scroll * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scrollDrag () : Boolean; + public function get scrollDrag () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scrollDrag (value:Boolean) : void; + public function set scrollDrag (value:Boolean) : void; /** * Gets a number between 0 and 100 indicating what percentage of the content is loaded. * If you are loading assets from your library, and not externally loaded content, * the percentLoaded property is set to 0. * * @default 0 * * @includeExample examples/ScrollPane.percentLoaded.1.as -noswf * * @see #bytesLoaded * @see #bytesTotal * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get percentLoaded () : Number; + public function get percentLoaded () : Number; /** * Gets the count of bytes of content that have been loaded. * When this property equals the value of bytesTotal, * all the bytes are loaded. * * @default 0 * * @see #bytesTotal * @see #percentLoaded * * @includeExample examples/ScrollPane.bytesLoaded.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bytesLoaded () : Number; + public function get bytesLoaded () : Number; /** * Gets the count of bytes of content to be loaded. * * @default 0 * * @includeExample examples/ScrollPane.percentLoaded.1.as -noswf * * @see #bytesLoaded * @see #percentLoaded * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bytesTotal () : Number; + public function get bytesTotal () : Number; /** * Gets a reference to the content loaded into the scroll pane. * * @default null * * @includeExample examples/ScrollPane.content.1.as -noswf * @includeExample examples/ScrollPane.content.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get content () : DisplayObject; + public function get content () : DisplayObject; /** * Gets or sets an absolute or relative URL that identifies the * location of the SWF or image file to load, the class name * of a movie clip in the library, a reference to a display object, * or a instance name of a movie clip on the same level as the component. * *

    Valid image file formats include GIF, PNG, and JPEG. To load an * asset by using a URLRequest object, use the load() * method.

    * * @default null * * @includeExample examples/ScrollPane.source.1.as -noswf * @includeExample examples/ScrollPane.source.2.as -noswf * * @see #load() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get source () : Object; + public function get source () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set source (value:Object) : void; - + public function set source (value:Object) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new ScrollPane component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ScrollPane (); + public function ScrollPane (); /** * Reloads the contents of the scroll pane. * *

    This method does not redraw the scroll bar. To reset the * scroll bar, use the update() method.

    * * @includeExample examples/ScrollPane.refreshPane.1.as -noswf * * @see #update() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function refreshPane () : void; + public function refreshPane () : void; /** * Refreshes the scroll bar properties based on the width * and height of the content. This is useful if the content * of the ScrollPane changes during run time. * * @includeExample examples/ScrollPane.update.1.as -noswf * * @see #refreshPane() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function update () : void; + public function update () : void; /** * The request parameter of this method accepts only a URLRequest object * whose source property contains a string, a class, or a * URLRequest object. * * By default, the LoaderContext object uses the current domain as the * application domain. To specify a different application domain value, * to check a policy file, or to change the security domain, initialize * a new LoaderContext object and pass it to this method. * * @param request The URLRequest object to use to load an image into the scroll pane. * @param context The LoaderContext object that sets the context of the load operation. * * @see #source * @see fl.containers.UILoader#load() UILoader.load() * @see flash.net.URLRequest * @see flash.system.ApplicationDomain * @see flash.system.LoaderContext * * @includeExample examples/ScrollPane.load.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function load (request:URLRequest, context:LoaderContext = null) : void; + public function load (request:URLRequest, context:LoaderContext = null) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setVerticalScrollPosition (scrollPos:Number, fireEvent:Boolean = false) : void; + protected function setVerticalScrollPosition (scrollPos:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setHorizontalScrollPosition (scrollPos:Number, fireEvent:Boolean = false) : void; + protected function setHorizontalScrollPosition (scrollPos:Number, fireEvent:Boolean = false) : void; /** * @private (protected) */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onContentLoad (event:Event) : void; + protected function onContentLoad (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function passEvent (event:Event) : void; + protected function passEvent (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initLoader () : void; + protected function initLoader () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleScroll (event:ScrollEvent) : void; + protected function handleScroll (event:ScrollEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleError (event:Event) : void; + protected function handleError (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleInit (event:Event) : void; + protected function handleInit (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function clearLoadEvents () : void; + protected function clearLoadEvents () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function doDrag (event:MouseEvent) : void; + protected function doDrag (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function doStartDrag (event:MouseEvent) : void; + protected function doStartDrag (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function endDrag (event:MouseEvent) : void; + protected function endDrag (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setScrollDrag () : void; + protected function setScrollDrag () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBackground () : void; + protected function drawBackground () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function clearContent () : void; + protected function clearContent () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private */ - protected function calculateAvailableHeight () : Number; + protected function calculateAvailableHeight () : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; - } -} + protected function configUI () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/UILoader.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/UILoader.as index dc56c7a72e..5e980f5838 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/UILoader.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/containers/UILoader.as @@ -1,211 +1,211 @@ -package fl.containers -{ - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - import flash.display.DisplayObject; - import flash.display.Graphics; - import flash.display.Loader; - import flash.display.LoaderInfo; - import flash.display.Shape; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.ProgressEvent; - import flash.events.SecurityErrorEvent; - import flash.events.IOErrorEvent; - import flash.events.HTTPStatusEvent; - import flash.net.URLRequest; - import flash.system.ApplicationDomain; - import flash.system.LoaderContext; - import flash.utils.ByteArray; - +package fl.containers +{ + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.Loader; + import flash.display.LoaderInfo; + import flash.display.Shape; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.ProgressEvent; + import flash.events.SecurityErrorEvent; + import flash.events.IOErrorEvent; + import flash.events.HTTPStatusEvent; + import flash.net.URLRequest; + import flash.system.ApplicationDomain; + import flash.system.LoaderContext; + import flash.utils.ByteArray; + /** * Dispatched when content loading is complete. This event is dispatched * regardless of whether the load operation was triggered by an auto-load process or an explicit * call to the load() method. * * @eventType flash.events.Event.COMPLETE * * @includeExample examples/UILoader.complete.1.as -noswf * * @see #event:progress * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("complete", type="flash.events.Event")] + [Event("complete", type="flash.events.Event")] /** * Dispatched when the properties and methods of a loaded SWF file are accessible. * The following conditions must exist for this event to be dispatched: *
      *
    • All the properties and methods that are associated with the loaded object, * as well as those that are associated with the component, must be accessible.
    • *
    • The constructors for all child objects must have completed.
    • *
    * * @eventType flash.events.Event.INIT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("init", type="flash.events.Event")] + [Event("init", type="flash.events.Event")] /** * Dispatched after an input or output error occurs. * * @includeExample examples/UILoader.ioError.1.as -noswf * * @eventType flash.events.IOErrorEvent.IO_ERROR * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("ioError", type="flash.events.IOErrorEvent")] + [Event("ioError", type="flash.events.IOErrorEvent")] /** * Dispatched after a network operation starts. * * @eventType flash.events.Event.OPEN * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("open", type="flash.events.Event")] + [Event("open", type="flash.events.Event")] /** * Dispatched when content is loading. This event is dispatched regardless of * whether the load operation was triggered by an auto-load process or an explicit call to the * load() method. * * @includeExample examples/UILoader.progress.1.as -noswf * * @eventType flash.events.ProgressEvent.PROGRESS * * @see #event:complete * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("progress", type="flash.events.ProgressEvent")] + [Event("progress", type="flash.events.ProgressEvent")] /** * Dispatched after the component is resized. * * @includeExample examples/UILoader.resize.1.as -noswf * * @eventType fl.events.ComponentEvent.RESIZE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("resize", type="fl.events.ComponentEvent")] + [Event("resize", type="fl.events.ComponentEvent")] /** * Dispatched after a security error occurs while content is loading. * * @eventType flash.events.SecurityErrorEvent.SECURITY_ERROR * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("securityError", type="flash.events.SecurityErrorEvent")] - + [Event("securityError", type="flash.events.SecurityErrorEvent")] + /** * The UILoader class makes it possible to set content to load and to then * monitor the loading operation at run time. This class also handles the resizing * of the loaded content. If loading content from a different domain (sandbox), * security implications may mean content properties are inaccessible. Please * see the Loader class for more information. * *

    Using ActionScript to set a property of the UILoader class * overrides the parameter of the same name that is set in the Property * inspector or Component inspector.

    * *

    This component wraps flash.display.Loader. The Loader class handles all the actual * loading; the UILoader just provides a visual display for the Loader object.

    * *

    Note: When content is being loaded from a different * domain or sandbox, the properties of the content may be inaccessible * for security reasons. For more information about how domain security * affects the load process, see the Loader class.

    * * @see flash.display.Loader Loader * * @includeExample examples/UILoaderExample.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class UILoader extends UIComponent - { + public class UILoader extends UIComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _scaleContent : Boolean; + protected var _scaleContent : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _autoLoad : Boolean; + protected var _autoLoad : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var contentInited : Boolean; + protected var contentInited : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _source : Object; + protected var _source : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var loader : Loader; + protected var loader : Loader; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _maintainAspectRatio : Boolean; + protected var _maintainAspectRatio : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var contentClip : Sprite; + protected var contentClip : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * Gets or sets a value that indicates whether the UILoader instance automatically * loads the specified content. A value of true indicates that the UILoader * automatically loads the content; a value of false indicates that content * is not loaded until the load() method is called. * * @default true * * @includeExample examples/UILoader.autoLoad.1.as -noswf * * @see #load() * @see #source * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get autoLoad () : Boolean; + public function get autoLoad () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set autoLoad (value:Boolean) : void; + public function set autoLoad (value:Boolean) : void; /** * Gets or sets a value that indicates whether to automatically scale the image to * the size of the UILoader instance. A value of true indicates that the * image is automatically scaled to the size of the UILoader instance; a value of * false indicates that the loaded content is automatically scaled * to its default size. * * @default true * * @includeExample examples/UILoader.scaleContent.1.as -noswf * * @see #maintainAspectRatio * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scaleContent () : Boolean; + public function get scaleContent () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scaleContent (value:Boolean) : void; + public function set scaleContent (value:Boolean) : void; /** * Gets or sets a value that indicates whether to maintain * the aspect ratio that was used in the original image or to resize * the image at the curent width and height of the UILoader component. * A value of true indicates that the original aspect ratio * is to be maintained; a value of false indicates that the * loaded content should be resized to the current dimensions of the UILoader. * *

    To use this property, you must set the scaleContent property to * false; otherwise, this property is ignored.

    * * @default true * * @includeExample examples/UILoader.maintainAspectRatio.1.as -noswf * * @see #scaleContent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maintainAspectRatio () : Boolean; + public function get maintainAspectRatio () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maintainAspectRatio (value:Boolean) : void; + public function set maintainAspectRatio (value:Boolean) : void; /** * @copy ScrollPane#bytesLoaded * * @default 0 * * @includeExample examples/UILoader.progress.1.as -noswf * * @see #bytesTotal * @see #percentLoaded * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bytesLoaded () : uint; + public function get bytesLoaded () : uint; /** * @copy ScrollPane#bytesTotal * * @default 0 * * @includeExample examples/UILoader.progress.1.as -noswf * * @see #bytesLoaded * @see #percentLoaded * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bytesTotal () : uint; + public function get bytesTotal () : uint; /** * Contains the root display object of the SWF file or image file (a JPEG, PNG, or GIF format file) * that was loaded by using the load() method or setting the source property. * The value is undefined until the load begins. Set the properties for the content * within an event handler function for the complete event. * * @default null * * @includeExample examples/UILoader.content.1.as -noswf * * @see #event:complete * @see #load() * @see #source * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get content () : DisplayObject; + public function get content () : DisplayObject; /** * @copy fl.containers.ScrollPane#source * * @default null * * @includeExample examples/UILoader.source.1.as -noswf * * @see #autoLoad * @see #load() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get source () : Object; + public function get source () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set source (value:Object) : void; + public function set source (value:Object) : void; /** * @copy ScrollPane#percentLoaded * * @default 0 * * @includeExample examples/UILoader.progress.1.as -noswf * * @see #bytesLoaded * @see #bytesTotal * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get percentLoaded () : Number; - + public function get percentLoaded () : Number; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new UILoader component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function UILoader (); + public function UILoader (); /** * Resizes the component to the requested size. If the scaleContent * property is set to true, the UILoader is not resized. * * @param w The width of the component, in pixels. * @param h The height of the component, in pixels. * * @includeExample examples/UILoader.setSize.1.as -noswf * * @see #scaleContent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSize (w:Number, h:Number) : void; + public function setSize (w:Number, h:Number) : void; /** * Loads binary data that is stored in a ByteArray object. * * @param bytes A ByteArray object that contains a file in one of the formats supported * by the Loader class: SWF, GIF, JPEG, or PNG. * * @param context Only the applicationDomain property of the LoaderContext * object applies; the checkPolicyFile and securityDomain * properties of the LoaderContext object do not apply. * * @throws ArgumentError The length property of the ByteArray object is 0. * * @throws IllegalOperationError The checkPolicyFile or securityDomain * property of the context parameter is non-null. * * @throws SecurityError The applicationDomain property of the * context property that was provided is from a domain that is not allowed. * * @includeExample examples/UILoader.loadBytes.1.as -noswf * * @see #source * @see flash.display.Loader#loadBytes() Loader.loadBytes() * @see flash.system.LoaderContext LoaderContext * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function loadBytes (bytes:ByteArray, context:LoaderContext = null) : void; + public function loadBytes (bytes:ByteArray, context:LoaderContext = null) : void; /** * Loads the specified content or, if no content is specified, loads the * content from the location identified by the source property. * * By default, the LoaderContext object uses the current domain as the * application domain. To specify a different application domain, to check * a policy file, or to change the security domain, initialize a new LoaderContext * object and pass it to this method. * *

    By default, the context property uses the current domain. * To specify a different ApplicationDomain, check a policy file, or * change the SecurityDomain, pass a new LoaderContext object.

    * * @param request The URLRequest object that identifies the location from * which to load the content. If this value is not specified, * the current value of the source property is * used as the content location. * @param context The LoaderContext object that sets the context of the load operation. * @param context A LoaderContext object used to specify the context of the load . * * @includeExample examples/UILoader.load.1.as -noswf * @includeExample examples/UILoader.load.2.as -noswf * * @see #autoLoad * @see #close() * @see #source * @see #unload() * @see flash.system.ApplicationDomain * @see flash.system.LoaderContext * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function load (request:URLRequest = null, context:LoaderContext = null) : void; + public function load (request:URLRequest = null, context:LoaderContext = null) : void; /** * Removes a child of this UILoader object that was loaded by using * either the load() method or the source * property. * * @includeExample examples/UILoader.unload.1.as -noswf * * @see #load() * @see #source * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function unload () : void; + public function unload () : void; /** * Cancels a load() method operation that is currently in progress for the * Loader instance. The load() method can also be called from the source parameter. * * @throws Error The URLStream object does not have an open stream. * * @includeExample examples/UILoader.close.1.as -noswf * * @see #load() * @see #source * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function close () : void; + public function close () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function _unload (throwError:Boolean = false) : void; + protected function _unload (throwError:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initLoader () : void; + protected function initLoader () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleComplete (event:Event) : void; + protected function handleComplete (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function passEvent (event:Event) : void; + protected function passEvent (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleError (event:Event) : void; + protected function handleError (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleInit (event:Event) : void; + protected function handleInit (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function clearLoadEvents () : void; + protected function clearLoadEvents () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function sizeContent (target:DisplayObject, contentWidth:Number, contentHeight:Number, targetWidth:Number, targetHeight:Number) : void; + protected function sizeContent (target:DisplayObject, contentWidth:Number, contentHeight:Number, targetWidth:Number, targetHeight:Number) : void; /** * @private (protected) */ - protected function configUI () : void; - } -} + protected function configUI () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/BaseButton.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/BaseButton.as index 9e02f5b722..1148c86039 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/BaseButton.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/BaseButton.as @@ -1,174 +1,174 @@ -package fl.controls -{ - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - import flash.display.DisplayObject; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.MouseEvent; - import flash.events.TimerEvent; - import flash.utils.Timer; - +package fl.controls +{ + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.events.TimerEvent; + import flash.utils.Timer; + /** * Dispatched when the user presses the Button component. * If the autoRepeat property is true, * this event is dispatched at specified intervals until the * button is released. * *

    The repeatDelay style is used to * specify the delay before the buttonDown event is * dispatched a second time. The repeatInterval style * specifies the interval at which this event is dispatched thereafter, * until the user releases the button.

    * * @eventType fl.events.ComponentEvent.BUTTON_DOWN * * @includeExample examples/BaseButton.autoRepeat.1.as -noswf * * @see #autoRepeat * @see #style:repeatDelay style * @see #style:repeatInterval style * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="buttonDown", type="fl.events.ComponentEvent")] + [Event(name="buttonDown", type="fl.events.ComponentEvent")] /** * Dispatched when the value of the selected property * of a toggle Button component changes. A toggle Button component is a * Button component whose toggle property is set to true. * *

    The CheckBox and RadioButton components dispatch this event after * there is a change in the selected property.

    * * @eventType flash.events.Event.CHANGE * * @includeExample examples/LabelButton.toggle.1.as -noswf * * @see #selected selected * @see LabelButton#toggle LabelButton.toggle * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change", type="flash.events.Event")] + [Event(name="change", type="flash.events.Event")] /** * @copy fl.controls.LabelButton#style:upSkin * * @default Button_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:downSkin * * @default Button_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downSkin", type="Class")] + [Style(name="downSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:overSkin * * @default Button_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="overSkin", type="Class")] + [Style(name="overSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:disabledSkin * * @default Button_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledSkin", type="Class")] + [Style(name="disabledSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDisabledSkin * * @default Button_selectedDisabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDisabledSkin", type="Class")] + [Style(name="selectedDisabledSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedUpSkin * * @default Button_selectedUpSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedUpSkin", type="Class")] + [Style(name="selectedUpSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDownSkin * * @default Button_selectedDownSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDownSkin", type="Class")] + [Style(name="selectedDownSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedOverSkin * * @default Button_selectedOverSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedOverSkin", type="Class")] + [Style(name="selectedOverSkin", type="Class")] /** * The number of milliseconds to wait after the buttonDown * event is first dispatched before sending a second buttonDown * event. * * @default 500 * * @see #event:buttonDown * @see #autoRepeat * @see #style:repeatInterval * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatDelay", type="Number", format="Time")] + [Style(name="repeatDelay", type="Number", format="Time")] /** * The interval, in milliseconds, between buttonDown events * that are dispatched after the delay that is specified by the repeatDelay * style. * * @default 35 * * @see #event:buttonDown * @see #autoRepeat * @see #style:repeatDelay * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatInterval", type="Number", format="Time")] - + [Style(name="repeatInterval", type="Number", format="Time")] + /** * The BaseButton class is the base class for all button components, defining * properties and methods that are common to all buttons. This class handles * drawing states and the dispatching of button events. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class BaseButton extends UIComponent - { + public class BaseButton extends UIComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var background : DisplayObject; + protected var background : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var mouseState : String; + protected var mouseState : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _selected : Boolean; + protected var _selected : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _autoRepeat : Boolean; + protected var _autoRepeat : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var pressTimer : Timer; + protected var pressTimer : Timer; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _mouseStateLocked : Boolean; + private var _mouseStateLocked : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var unlockedMouseState : String; + private var unlockedMouseState : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * Gets or sets a value that indicates whether the component can accept user * input. A value of true indicates that the component can accept * user input; a value of false indicates that it cannot. * *

    When this property is set to false, the button is disabled. * This means that although it is visible, it cannot be clicked. This property is * useful for disabling a specific part of the user interface. For example, a button * that is used to trigger the reloading of a web page could be disabled * by using this technique.

    * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get enabled () : Boolean; + public function get enabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether a toggle button * is selected. A value of true indicates that the button is * selected; a value of false indicates that it is not. * This property has no effect if the toggle property * is not set to true. * *

    For a CheckBox component, this value indicates whether the box is * checked. For a RadioButton component, this value indicates whether the * component is selected.

    * *

    This value changes when the user clicks the component * but can also be changed programmatically. If the toggle * property is set to true, changing this property causes * a change event object to be dispatched.

    * * @default false * * @includeExample examples/LabelButton.toggle.1.as -noswf * * @see #event:change change * @see LabelButton#toggle LabelButton.toggle * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selected () : Boolean; + public function get selected () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selected (value:Boolean) : void; + public function set selected (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether the buttonDown event * is dispatched more than one time when the user holds the mouse button down over the component. * A value of true indicates that the buttonDown event * is dispatched repeatedly while the mouse button remains down; a value of false * indicates that the event is dispatched only one time. * *

    If this value is true, after the delay specified by the * repeatDelay style, the buttonDown * event is dispatched at the interval that is specified by the repeatInterval style.

    * * @default false * * @includeExample examples/BaseButton.autoRepeat.1.as -noswf * * @see #style:repeatDelay * @see #style:repeatInterval * @see #event:buttonDown * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get autoRepeat () : Boolean; + public function get autoRepeat () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set autoRepeat (value:Boolean) : void; + public function set autoRepeat (value:Boolean) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set mouseStateLocked (value:Boolean) : void; - + public function set mouseStateLocked (value:Boolean) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new BaseButton instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function BaseButton (); + public function BaseButton (); /** * Set the mouse state via ActionScript. The BaseButton class * uses this property internally, but it can also be invoked manually, * and will set the mouse state visually. * * @param state A string that specifies a mouse state. Supported values are * "up", "over", and "down". * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setMouseState (state:String) : void; + public function setMouseState (state:String) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setupMouseEvents () : void; + protected function setupMouseEvents () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function mouseEventHandler (event:MouseEvent) : void; + protected function mouseEventHandler (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function startPress () : void; + protected function startPress () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function buttonDown (event:TimerEvent) : void; + protected function buttonDown (event:TimerEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function endPress () : void; + protected function endPress () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBackground () : void; + protected function drawBackground () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; - } -} + protected function drawLayout () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/Button.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/Button.as index 9903152c34..cbec82d31b 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/Button.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/Button.as @@ -1,75 +1,75 @@ -package fl.controls -{ - import fl.controls.LabelButton; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.managers.IFocusManagerComponent; - import flash.display.DisplayObject; - import flash.display.Sprite; - +package fl.controls +{ + import fl.controls.LabelButton; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.managers.IFocusManagerComponent; + import flash.display.DisplayObject; + import flash.display.Sprite; + /** * The skin to be used when a button has emphasis. * * @default Button_emphasizedSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="emphasizedSkin", type="Class")] + [Style(name="emphasizedSkin", type="Class")] /** * The padding to be applied around the Buttons in an * emphasized skin, in pixels. * * @default 2 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="emphasizedPadding", type="Number", format="Length")] - + [Style(name="emphasizedPadding", type="Number", format="Length")] + /** * The Button component represents a commonly used rectangular button. * Button components display a text label, an icon, or both. * *

    A Button component is typically associated with an event handler * method that listens for a click event and performs the * specified task after the click event is dispatched. When * the user clicks an enabled button, the button dispatches the click * and buttonDown events. Even if it is not enabled, a button * dispatches other events including mouseMove, mouseOver, mouseOut, * rollOver, rollOut, mouseDown, * and mouseUp.

    * *

    You can change the appearance of the button by associating a different * skin with each button state. A Button component can also be set to * function as a push button or a toggle button.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @includeExample examples/ButtonExample.as */ - public class Button extends LabelButton implements IFocusManagerComponent - { + public class Button extends LabelButton implements IFocusManagerComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _emphasized : Boolean; + protected var _emphasized : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var emphasizedBorder : DisplayObject; + protected var emphasizedBorder : DisplayObject; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * * Method for creating the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * Gets or sets a Boolean value that indicates whether a border is drawn * around the Button component when the button is in its up state. A value * of true indicates that the button is surrounded by a border * when it is in its up state; a value of false indicates that * it is not. * * @default false * * @includeExample examples/Button.emphasized.1.as -noswf * * @see #style:emphasizedPadding * @see #style:emphasizedSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get emphasized () : Boolean; + public function get emphasized () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set emphasized (value:Boolean) : void; - + public function set emphasized (value:Boolean) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new Button component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function Button (); + public function Button (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawEmphasized () : void; + protected function drawEmphasized () : void; /** * @private * * @copy fl.core.UIComponent#drawFocus() * @internal Added logic to resize focusRect if button has emphasis * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawFocus (focused:Boolean) : void; + public function drawFocus (focused:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; - } -} + protected function initializeAccessibility () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ButtonLabelPlacement.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ButtonLabelPlacement.as index 50ac5f2fd2..060cbb1e27 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ButtonLabelPlacement.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ButtonLabelPlacement.as @@ -1,26 +1,26 @@ -package fl.controls -{ +package fl.controls +{ /** * The ButtonLabelPlacement class defines constants for the * values of the labelPlacement property of a Button, * CheckBox, or RadioButton component. * * @includeExample examples/ButtonLabelPlacementExample.as * * @see LabelButton#labelPlacement * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ButtonLabelPlacement - { + public class ButtonLabelPlacement + { /** * The label appears below the icon. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const BOTTOM : String = "bottom"; + public static const BOTTOM : String = "bottom"; /** * The label appears above the icon. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const TOP : String = "top"; + public static const TOP : String = "top"; /** * The label appears to the left of the icon. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const LEFT : String = "left"; + public static const LEFT : String = "left"; /** * The label appears to the right of the icon. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const RIGHT : String = "right"; - - } -} + public static const RIGHT : String = "right"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/CheckBox.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/CheckBox.as index 3c896ea5a7..904c441f84 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/CheckBox.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/CheckBox.as @@ -1,113 +1,113 @@ -package fl.controls -{ - import fl.controls.ButtonLabelPlacement; - import fl.controls.LabelButton; - import fl.core.UIComponent; - import flash.display.DisplayObject; - import flash.display.Graphics; - import flash.display.Sprite; - import flash.display.Shape; - import Error; - +package fl.controls +{ + import fl.controls.ButtonLabelPlacement; + import fl.controls.LabelButton; + import fl.core.UIComponent; + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.Sprite; + import flash.display.Shape; + import Error; + /** * @copy fl.controls.LabelButton#style:icon * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="icon", type="Class")] + [Style(name="icon", type="Class")] /** * @copy fl.controls.LabelButton#style:upIcon * * @default CheckBox_upIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upIcon", type="Class")] + [Style(name="upIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:downIcon * * @default CheckBox_downIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downIcon", type="Class")] + [Style(name="downIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:overIcon * * @default CheckBox_overIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="overIcon", type="Class")] + [Style(name="overIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:disabledIcon * * @default CheckBox_disabledIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledIcon", type="Class")] + [Style(name="disabledIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDisabledIcon * * @default CheckBox_selectedDisabledIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDisabledIcon", type="Class")] + [Style(name="selectedDisabledIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedUpIcon * * @default CheckBox_selectedUpIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedUpIcon", type="Class")] + [Style(name="selectedUpIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDownIcon * * @default CheckBox_selectedDownIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDownIcon", type="Class")] + [Style(name="selectedDownIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedOverIcon * * @default CheckBox_selectedOverIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedOverIcon", type="Class")] + [Style(name="selectedOverIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:textPadding * * @default 5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] - + [Style(name="textPadding", type="Number", format="Length")] + /** * The CheckBox component displays a small box that can contain * a check mark. A CheckBox component can also display an optional * text label that is positioned to the left, right, top, or bottom * of the CheckBox. * *

    A CheckBox component changes its state in response to a mouse * click, from selected to cleared, or from cleared to selected. * CheckBox components include a set of true or false values * that are not mutually exclusive.

    * * @includeExample examples/CheckBoxExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class CheckBox extends LabelButton - { + public class CheckBox extends LabelButton + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * Creates the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * A CheckBox toggles by definition, so the toggle property is set to * true in the constructor and cannot be changed for a CheckBox. * * @default true * * @throws Error This value cannot be changed for a CheckBox component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get toggle () : Boolean; + public function get toggle () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set toggle (value:Boolean) : void; + public function set toggle (value:Boolean) : void; /** * A CheckBox never auto-repeats by definition, so the autoRepeat property is set * to false in the constructor and cannot be changed for a CheckBox. * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get autoRepeat () : Boolean; + public function get autoRepeat () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set autoRepeat (value:Boolean) : void; - + public function set autoRepeat (value:Boolean) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new CheckBox component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function CheckBox (); + public function CheckBox (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBackground () : void; + protected function drawBackground () : void; /** * Shows or hides the focus indicator around this component. * * @param focused Show or hide the focus indicator. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawFocus (focused:Boolean) : void; + public function drawFocus (focused:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; + protected function initializeAccessibility () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; - } -} + protected function configUI () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ColorPicker.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ColorPicker.as index 9793ef572e..5d393aaec7 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ColorPicker.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ColorPicker.as @@ -1,421 +1,421 @@ -package fl.controls -{ - import fl.core.UIComponent; - import fl.core.InvalidationType; - import fl.controls.BaseButton; - import fl.controls.TextInput; - import fl.controls.TextArea; - import fl.events.ComponentEvent; - import fl.events.ColorPickerEvent; - import fl.managers.IFocusManager; - import fl.managers.IFocusManagerComponent; - import flash.events.MouseEvent; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.events.FocusEvent; - import flash.display.DisplayObject; - import flash.display.Graphics; - import flash.display.Sprite; - import flash.geom.ColorTransform; - import flash.geom.Point; - import flash.geom.Rectangle; - import flash.text.TextField; - import flash.text.TextFieldType; - import flash.text.TextFormat; - import flash.ui.Keyboard; - import flash.system.IME; - +package fl.controls +{ + import fl.core.UIComponent; + import fl.core.InvalidationType; + import fl.controls.BaseButton; + import fl.controls.TextInput; + import fl.controls.TextArea; + import fl.events.ComponentEvent; + import fl.events.ColorPickerEvent; + import fl.managers.IFocusManager; + import fl.managers.IFocusManagerComponent; + import flash.events.MouseEvent; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.FocusEvent; + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.Sprite; + import flash.geom.ColorTransform; + import flash.geom.Point; + import flash.geom.Rectangle; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFormat; + import flash.ui.Keyboard; + import flash.system.IME; + /** * Dispatched when the user opens the color palette. * * @eventType flash.events.Event.OPEN * * @includeExample examples/ColorPicker.open.2.as -noswf * * @see #event:close * @see #open() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="open", type="flash.events.Event")] + [Event(name="open", type="flash.events.Event")] /** * Dispatched when the user closes the color palette. * * @eventType flash.events.Event.CLOSE * * @see #event:open * @see #close() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="close", type="flash.events.Event")] + [Event(name="close", type="flash.events.Event")] /** * Dispatched when the user clicks a color in the palette. * * @includeExample examples/ColorPicker.hexValue.1.as -noswf * * @eventType fl.events.ColorPickerEvent.CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change", type="fl.events.ColorPickerEvent")] + [Event(name="change", type="fl.events.ColorPickerEvent")] /** * Dispatched when the user rolls over a swatch in the color palette. * * @eventType fl.events.ColorPickerEvent.ITEM_ROLL_OVER * * @see #event:itemRollOut * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemRollOver", type="fl.events.ColorPickerEvent")] + [Event(name="itemRollOver", type="fl.events.ColorPickerEvent")] /** * Dispatched when the user rolls out of a swatch in the color palette. * * @eventType fl.events.ColorPickerEvent.ITEM_ROLL_OUT * * @see #event:itemRollOver * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemRollOut", type="fl.events.ColorPickerEvent")] + [Event(name="itemRollOut", type="fl.events.ColorPickerEvent")] /** * Dispatched when the user presses the Enter key after editing the internal text field of the ColorPicker component. * * @eventType fl.events.ColorPickerEvent.ENTER * * @includeExample examples/ColorPicker.enter.1.as -noswf * * @see #editable * @see #textField * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="enter", type="fl.events.ColorPickerEvent")] + [Event(name="enter", type="fl.events.ColorPickerEvent")] /** * Defines the padding that appears around each swatch in the color palette, in pixels. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="swatchPadding", type="Number", format="Length")] + [Style(name="swatchPadding", type="Number", format="Length")] /** * The class that provides the skin for a disabled button in the ColorPicker. * * @default ColorPicker_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] Changed description from "Disabled skin for the ColorPicker button" to the current. * Is this correct? */ - [Style(name="disabledSkin", type="Class")] + [Style(name="disabledSkin", type="Class")] /** * The padding that appears around the color TextField, in pixels. * * @default 3 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] + [Style(name="textPadding", type="Number", format="Length")] /** * The class that provides the skin for the color well when the pointing device rolls over it. * * @default ColorPicker_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="overSkin", type="Class")] + [Style(name="overSkin", type="Class")] /** * The padding that appears around the group of color swatches, in pixels. * * @default 5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="backgroundPadding", type="Number", format="Length")] + [Style(name="backgroundPadding", type="Number", format="Length")] /** * The class that provides the skin for the color well when it is filled with a color. * * @default ColorPicker_colorWell * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - [Style(name="colorWell", type="Class")] + [Style(name="colorWell", type="Class")] /** * The class that provides the skin for the ColorPicker button when it is in the down position. * * @default ColorPicker_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] Description was "Down skin for the ColorPicker button." Is the revised description correct? */ - [Style(name="downSkin", type="Class")] + [Style(name="downSkin", type="Class")] /** * The class that provides the background for the text field of the ColorPicker component. * * @default ColorPicker_textFieldSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textFieldSkin", type="Class")] + [Style(name="textFieldSkin", type="Class")] /** * The class that provides the background of the palette that appears in the ColorPicker component. * * @default ColorPicker_backgroundSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="background", type="Class")] + [Style(name="background", type="Class")] /** * The class that provides the skin which is used to draw the swatches contained in the ColorPicker component. * * @default ColorPicker_swatchSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="swatchSkin", type="Class")] + [Style(name="swatchSkin", type="Class")] /** * The class that provides the skin which is used to highlight the currently selected color. * * @default ColorPicker_swatchSelectedSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="swatchSelectedSkin", type="Class")] + [Style(name="swatchSelectedSkin", type="Class")] /** * The width of each swatch, in pixels. * * @default 10 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="swatchWidth", type="Number", format="Length")] + [Style(name="swatchWidth", type="Number", format="Length")] /** * The height of each swatch, in pixels. * * @default 10 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="swatchHeight", type="Number", format="Length")] + [Style(name="swatchHeight", type="Number", format="Length")] /** * The number of columns to be drawn in the ColorPicker color palette. * * @default 18 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="columnCount", type="Number", format="Length")] + [Style(name="columnCount", type="Number", format="Length")] /** * The class that provides the skin for the ColorPicker button when it is in the up position. * * @default ColorPicker_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] The previous description was "Up skin for the ColorPicker button." Is the revised description * correct? */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:embedFonts * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="embedFonts", type="Boolean")] - + [Style(name="embedFonts", type="Boolean")] + /** * The ColorPicker component displays a list of one or more swatches * from which the user can select a color. * *

    By default, the component displays a single swatch of color on a * square button. When the user clicks this button, a panel opens to * display the complete list of swatches.

    * * @includeExample examples/ColorPickerExample.as * * @see fl.events.ColorPickerEvent ColorPickerEvent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ColorPicker extends UIComponent implements IFocusManagerComponent - { + public class ColorPicker extends UIComponent implements IFocusManagerComponent + { /** * A reference to the internal text field of the ColorPicker component. * * @see #showTextField * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var textField : TextField; + public var textField : TextField; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var customColors : Array; + protected var customColors : Array; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var defaultColors : Array; + public static var defaultColors : Array; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var colorHash : Object; + protected var colorHash : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var paletteBG : DisplayObject; + protected var paletteBG : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var selectedSwatch : Sprite; + protected var selectedSwatch : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _selectedColor : uint; + protected var _selectedColor : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var rollOverColor : int; + protected var rollOverColor : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _editable : Boolean; + protected var _editable : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _showTextField : Boolean; + protected var _showTextField : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var isOpen : Boolean; + protected var isOpen : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var doOpen : Boolean; + protected var doOpen : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var swatchButton : BaseButton; + protected var swatchButton : BaseButton; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var colorWell : DisplayObject; + protected var colorWell : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var swatchSelectedSkin : DisplayObject; + protected var swatchSelectedSkin : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var palette : Sprite; + protected var palette : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var textFieldBG : DisplayObject; + protected var textFieldBG : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var swatches : Sprite; + protected var swatches : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var swatchMap : Array; + protected var swatchMap : Array; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var currRowIndex : int; + protected var currRowIndex : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var currColIndex : int; + protected var currColIndex : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected static const POPUP_BUTTON_STYLES : Object; + protected static const POPUP_BUTTON_STYLES : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected const SWATCH_STYLES : Object; - + protected const SWATCH_STYLES : Object; + /** * Gets or sets the swatch that is currently highlighted in the palette of the ColorPicker component. * * @default 0x000000 * * @includeExample examples/ColorPicker.selectedColor.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedColor () : uint; + public function get selectedColor () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectedColor (value:uint) : void; + public function set selectedColor (value:uint) : void; /** * Gets the string value of the current color selection. * * @includeExample examples/ColorPicker.hexValue.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get hexValue () : String; + public function get hexValue () : String; /** * @copy fl.core.UIComponent#enabled * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get enabled () : Boolean; + public function get enabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether the internal text field of the * ColorPicker component is editable. A value of true indicates that * the internal text field is editable; a value of false indicates * that it is not. * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get editable () : Boolean; + public function get editable () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set editable (value:Boolean) : void; + public function set editable (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether the internal text field * of the ColorPicker component is displayed. A value of true indicates * that the internal text field is displayed; a value of false indicates * that it is not. * * @default true * * @includeExample examples/ColorPicker.showTextField.1.as -noswf * * @see #textField * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get showTextField () : Boolean; + public function get showTextField () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set showTextField (value:Boolean) : void; + public function set showTextField (value:Boolean) : void; /** * Gets or sets the array of custom colors that the ColorPicker component * provides. The ColorPicker component draws and displays the colors that are * described in this array. * *

    Note: The maximum number of colors that the ColorPicker * component can display is 1024.

    * *

    By default, this array contains 216 autogenerated colors.

    * * @includeExample examples/ColorPicker.colors.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - public function get colors () : Array; + public function get colors () : Array; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set colors (value:Array) : void; + public function set colors (value:Array) : void; /** * @copy fl.controls.TextArea#imeMode * * @see flash.system.IMEConversionMode IMEConversionMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get imeMode () : String; + public function get imeMode () : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set imeMode (value:String) : void; - + public function set imeMode (value:String) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Shows the color palette. Calling this method causes the open * event to be dispatched. If the color palette is already open or disabled, * this method has no effect. * * @includeExample examples/ColorPicker.open.2.as -noswf * * @see #close() * @see #event:open * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function open () : void; + public function open () : void; /** * Hides the color palette. Calling this method causes the close * event to be dispatched. If the color palette is already closed or disabled, * this method has no effect. * * @see #event:close * @see #open() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function close () : void; + public function close () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function addCloseListener (event:Event); + private function addCloseListener (event:Event); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onStageClick (event:MouseEvent) : void; + protected function onStageClick (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setStyles () : void; + protected function setStyles () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function cleanUpSelected () : void; + protected function cleanUpSelected () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onPopupButtonClick (event:MouseEvent) : void; + protected function onPopupButtonClick (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function showPalette () : void; + protected function showPalette () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setEmbedFonts () : void; + protected function setEmbedFonts () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawSwatchHighlight () : void; + protected function drawSwatchHighlight () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawPalette () : void; + protected function drawPalette () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawTextField () : void; + protected function drawTextField () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawSwatches () : void; + protected function drawSwatches () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBG () : void; + protected function drawBG () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function positionPalette () : void; + protected function positionPalette () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setTextEditable () : void; + protected function setTextEditable () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyUpHandler (event:KeyboardEvent) : void; + protected function keyUpHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function positionTextField () : void; + protected function positionTextField () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setColorDisplay () : void; + protected function setColorDisplay () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setSwatchHighlight (swatch:Sprite) : void; + protected function setSwatchHighlight (swatch:Sprite) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function findSwatch (color:uint) : Sprite; + protected function findSwatch (color:uint) : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onSwatchClick (event:MouseEvent) : void; + protected function onSwatchClick (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onSwatchOver (event:MouseEvent) : void; + protected function onSwatchOver (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onSwatchOut (event:MouseEvent) : void; + protected function onSwatchOut (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setColorText (color:uint) : void; + protected function setColorText (color:uint) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function colorToString (color:uint) : String; + protected function colorToString (color:uint) : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setColorWellColor (colorTransform:ColorTransform) : void; + protected function setColorWellColor (colorTransform:ColorTransform) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function createSwatch (color:uint) : Sprite; + protected function createSwatch (color:uint) : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function addStageListener (event:Event = null) : void; + protected function addStageListener (event:Event = null) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function removeStageListener (event:Event = null) : void; + protected function removeStageListener (event:Event = null) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusInHandler (event:FocusEvent) : void; + protected function focusInHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusOutHandler (event:FocusEvent) : void; + protected function focusOutHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function isOurFocus (target:DisplayObject) : Boolean; + protected function isOurFocus (target:DisplayObject) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; - } -} + protected function configUI () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ComboBox.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ComboBox.as index 1a8e01f101..4509688bf6 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ComboBox.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ComboBox.as @@ -1,546 +1,546 @@ -package fl.controls -{ - import fl.data.DataProvider; - import fl.containers.BaseScrollPane; - import fl.controls.BaseButton; - import fl.controls.List; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.TextInput; - import fl.controls.TextArea; - import fl.controls.ScrollBar; - import fl.controls.SelectableList; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - import fl.events.DataChangeEvent; - import fl.events.DataChangeType; - import fl.events.ListEvent; - import fl.managers.IFocusManagerComponent; - import fl.data.DataProvider; - import fl.data.SimpleCollectionItem; - import flash.display.DisplayObject; - import flash.events.Event; - import flash.events.FocusEvent; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.events.TextEvent; - import flash.geom.Point; - import flash.system.IME; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.ui.Keyboard; - +package fl.controls +{ + import fl.data.DataProvider; + import fl.containers.BaseScrollPane; + import fl.controls.BaseButton; + import fl.controls.List; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.TextInput; + import fl.controls.TextArea; + import fl.controls.ScrollBar; + import fl.controls.SelectableList; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + import fl.events.DataChangeEvent; + import fl.events.DataChangeType; + import fl.events.ListEvent; + import fl.managers.IFocusManagerComponent; + import fl.data.DataProvider; + import fl.data.SimpleCollectionItem; + import flash.display.DisplayObject; + import flash.events.Event; + import flash.events.FocusEvent; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.events.TextEvent; + import flash.geom.Point; + import flash.system.IME; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.ui.Keyboard; + /** * Dispatched when the user changes the selection in the ComboBox component or, if * the ComboBox component is editable, each time the user enters a keystroke in the * text field. * * @eventType flash.events.Event.CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change", type="flash.events.Event")] + [Event(name="change", type="flash.events.Event")] /** * @copy fl.controls.SelectableList#event:itemRollOver * * @eventType fl.events.ListEvent.ITEM_ROLL_OVER * * @includeExample examples/ComboBox.itemRollOver.1.as -noswf * * @see #event:itemRollOut * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemRollOver", type="fl.events.ListEvent")] + [Event(name="itemRollOver", type="fl.events.ListEvent")] /** * @copy fl.controls.SelectableList#event:itemRollOut * * @eventType fl.events.ListEvent.ITEM_ROLL_OUT * * @see #event:itemRollOver * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemRollOut", type="fl.events.ListEvent")] + [Event(name="itemRollOut", type="fl.events.ListEvent")] /** * Dispatched when the drop-down list is dismissed for any reason. * * @eventType flash.events.Event.CLOSE * * @includeExample examples/ComboBox.close.1.as -noswf * * @see #close() * @see #event:open * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="close", type="flash.events.Event")] + [Event(name="close", type="flash.events.Event")] /** * Dispatched if the editable property is set to true and the user * presses the Enter key while typing in the editable text field. * * @eventType fl.events.ComponentEvent.ENTER * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="enter", type="fl.events.ComponentEvent")] + [Event(name="enter", type="fl.events.ComponentEvent")] /** * Dispatched when the user clicks the drop-down button to display * the drop-down list. Also dispatched when the user clicks the text * field, if the ComboBox component is not editable. * * @eventType flash.events.Event.OPEN * * @includeExample examples/ComboBox.open.1.as -noswf * * @see #event:close * @see #open() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="open", type="flash.events.Event")] + [Event(name="open", type="flash.events.Event")] /** * Dispatched when the user scrolls the drop-down list of the ComboBox component. * * @eventType fl.events.ScrollEvent.SCROLL * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="scroll", type="fl.events.ScrollEvent")] + [Event(name="scroll", type="fl.events.ScrollEvent")] /** * The space that separates the right edge of the component from the * text representing the selected item, in pixels. The button is * part of the background skin. * * @default 24 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="buttonWidth", type="Number", format="Length")] + [Style(name="buttonWidth", type="Number", format="Length")] /** * The space that separates the border from the text representing the * selected item, in pixels. * * @default 3 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] + [Style(name="textPadding", type="Number", format="Length")] /** * The name of the class that provides the background of the ComboBox component. * * @default ComboBox_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * The name of the class that provides the background that appears * in the ComboBox component when the mouse is over it. * * @default ComboBox_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="overSkin", type="Class")] + [Style(name="overSkin", type="Class")] /** * The name of the class that provides the background that appears * in the ComboBox component when the mouse is down. * * @default ComboBox_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downSkin", type="Class")] + [Style(name="downSkin", type="Class")] /** * The name of the class that provides the background that appears * in the ComboBox component when the enabled property of the * component is set to false. * * @default ComboBox_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledSkin", type="Class")] + [Style(name="disabledSkin", type="Class")] /** * @copy fl.controls.SelectableList#style:cellRenderer * * @default fl.controls.listClasses.CellRenderer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="cellRenderer", type="Class")] + [Style(name="cellRenderer", type="Class")] /** * @copy fl.containers.BaseScrollPane#style:contentPadding * * @default 3 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="contentPadding", type="Number", format="Length")] + [Style(name="contentPadding", type="Number", format="Length")] /** * @copy fl.controls.SelectableList#style:disabledAlpha * * @default 0.5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledAlpha", type="Class")] + [Style(name="disabledAlpha", type="Class")] /** * @copy fl.controls.ScrollBar#style:downArrowDisabledSkin * * @default ScrollArrowDown_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowDisabledSkin", type="Class")] + [Style(name="downArrowDisabledSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:downArrowDownSkin * * @default ScrollArrowDown_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowDownSkin", type="Class")] + [Style(name="downArrowDownSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:downArrowOverSkin * * @default ScrollArrowDown_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowOverSkin", type="Class")] + [Style(name="downArrowOverSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:downArrowUpSkin * * @default ScrollArrowDown_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowUpSkin", type="Class")] + [Style(name="downArrowUpSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbDisabledSkin * * @default ScrollThumb_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbDisabledSkin", type="Class")] + [Style(name="thumbDisabledSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbDownSkin * * @default ScrollThumb_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbDownSkin", type="Class")] + [Style(name="thumbDownSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbOverSkin * * @default ScrollThumb_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbOverSkin", type="Class")] + [Style(name="thumbOverSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbUpSkin * * @default ScrollThumb_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbArrowUpSkin", type="Class")] + [Style(name="thumbArrowUpSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:trackDisabledSkin * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackDisabledSkin", type="Class")] + [Style(name="trackDisabledSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:trackDownSkin * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackDownSkin", type="Class")] + [Style(name="trackDownSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:trackOverSkin * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackOverSkin", type="Class")] + [Style(name="trackOverSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:trackUpSkin * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackUpSkin", type="Class")] + [Style(name="trackUpSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:upArrowDisabledSkin * * @default ScrollArrowUp_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowDisabledSkin", type="Class")] + [Style(name="upArrowDisabledSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:upArrowDownSkin * * @default ScrollArrowUp_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowDownSkin", type="Class")] + [Style(name="upArrowDownSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:upArrowOverSkin * * @default ScrollArrowUp_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowOverSkin", type="Class")] + [Style(name="upArrowOverSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:upArrowUpSkin * * @default ScrollArrowUp_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowUpSkin", type="Class")] + [Style(name="upArrowUpSkin", type="Class")] /** * @copy fl.controls.ScrollBar#style:thumbIcon * * @default ScrollBar_thumbIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbIcon", type="Class")] + [Style(name="thumbIcon", type="Class")] /** * @copy fl.controls.BaseButton#style:repeatDelay * * @default 500 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatDelay", type="Number", format="Time")] + [Style(name="repeatDelay", type="Number", format="Time")] /** * @copy fl.controls.BaseButton#style:repeatInterval * * @default 35 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatInterval", type="Number", format="Time")] + [Style(name="repeatInterval", type="Number", format="Time")] /** * @copy fl.controls.LabelButton#style:embedFonts * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="embedFonts", type="Boolean")] - + [Style(name="embedFonts", type="Boolean")] + /** * The ComboBox component contains a drop-down list from which the * user can select one value. Its functionality is similar to that * of the SELECT form element in HTML. The ComboBox component can be editable, * in which case the user can type entries that are not in the list * into the TextInput portion of the ComboBox component. * * @includeExample examples/ComboBoxExample.as * * @see List * @see TextInput * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ComboBox extends UIComponent implements IFocusManagerComponent - { + public class ComboBox extends UIComponent implements IFocusManagerComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var inputField : TextInput; + protected var inputField : TextInput; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var background : BaseButton; + protected var background : BaseButton; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var list : List; + protected var list : List; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _rowCount : uint; + protected var _rowCount : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _editable : Boolean; + protected var _editable : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var isOpen : Boolean; + protected var isOpen : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var highlightedCell : int; + protected var highlightedCell : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var editableValue : String; + protected var editableValue : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _prompt : String; + protected var _prompt : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var isKeyDown : Boolean; + protected var isKeyDown : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var currentIndex : int; + protected var currentIndex : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var listOverIndex : uint; + protected var listOverIndex : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _dropdownWidth : Number; + protected var _dropdownWidth : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _labels : Array; + protected var _labels : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var collectionItemImport : SimpleCollectionItem; + private var collectionItemImport : SimpleCollectionItem; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected static const LIST_STYLES : Object; + protected static const LIST_STYLES : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected const BACKGROUND_STYLES : Object; + protected const BACKGROUND_STYLES : Object; /** * @private (internal) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * Gets or sets a Boolean value that indicates whether the ComboBox * component is editable or read-only. A value of true indicates * that the ComboBox component is editable; a value of false * indicates that it is not. * *

    In an editable ComboBox component, a user can enter values into the text * box that do not appear in the drop-down list. The text box displays the text * of the item in the list. If a ComboBox component is not editable, text cannot * be entered into the text box.

    * * @default false * * @includeExample examples/ComboBox.editable.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get editable () : Boolean; + public function get editable () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set editable (value:Boolean) : void; + public function set editable (value:Boolean) : void; /** * Gets or sets the maximum number of rows that can appear in a drop-down * list that does not have a scroll bar. If the number of items in the * drop-down list exceeds this value, the list is resized and a scroll bar is displayed, * if necessary. If the number of items in the drop-down list is less than this value, * the drop-down list is resized to accommodate the number of items that it contains. * *

    This behavior differs from that of the List component, which always shows the number * of rows specified by its rowCount property, even if this includes empty space.

    * * @default 5 * * @includeExample examples/ComboBox.rowCount.1.as -noswf * * @see #length * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowCount () : uint; + public function get rowCount () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set rowCount (value:uint) : void; + public function set rowCount (value:uint) : void; /** * Gets or sets the characters that a user can enter in the text field. * If the value of the restrict property is * a string of characters, you can enter only characters in the string * into the text field. The string is read from left to right. If * the value of the restrict property is null, you * can enter any character. If the value of the restrict * property is an empty string (""), you cannot enter any character. * You can specify a range by using the hyphen (-) character. This restricts * only user interaction; a script can put any character into the text * field. * * @default null * * @includeExample examples/ComboBox.restrict.1.as -noswf * * @see flash.text.TextField#restrict TextField.restrict * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get restrict () : String; + public function get restrict () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set restrict (value:String) : void; + public function set restrict (value:String) : void; /** * @copy fl.controls.SelectableList#selectedIndex * * @default 0 * * @includeExample examples/ComboBox.selectedIndex.1.as -noswf * @includeExample examples/ComboBox.selectedIndex.2.as -noswf * * @see #selectedItem * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedIndex () : int; + public function get selectedIndex () : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectedIndex (value:int) : void; + public function set selectedIndex (value:int) : void; /** * Gets or sets the text that the text box contains in an editable ComboBox component. * For ComboBox components that are not editable, this value is read-only. * * @default "" * * @includeExample examples/ComboBox.text.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get text () : String; + public function get text () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set text (value:String) : void; + public function set text (value:String) : void; /** * @copy fl.controls.List#labelField * * @default "label" * * @includeExample examples/ComboBox.labelField.1.as -noswf * * @see #labelFunction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelField () : String; + public function get labelField () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelField (value:String) : void; + public function set labelField (value:String) : void; /** * @copy fl.controls.List#labelFunction * * @includeExample examples/List.labelFunction.1.as -noswf * @includeExample examples/ComboBox.labelFunction.2.as -noswf * * @see #labelField * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelFunction () : Function; + public function get labelFunction () : Function; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelFunction (value:Function) : void; + public function set labelFunction (value:Function) : void; /** * Gets or sets the value of the item that is selected in the drop-down list. * If the user enters text into the text box of an editable ComboBox component, the * selectedItem property is undefined. This * property has a value only if the user selects an item * or if ActionScript is used to select an item from the drop-down list. * If the ComboBox component is not editable, the value of the selectedItem * property is always valid. If there are no items in the drop-down list of * an editable ComboBox component, the value of this property is null. * * @default null * * @includeExample examples/ComboBox.selectedItem.1.as -noswf * @includeExample examples/ComboBox.selectedItem.2.as -noswf * * @see #selectedIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedItem () : Object; + public function get selectedItem () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectedItem (value:Object) : void; + public function set selectedItem (value:Object) : void; /** * Gets a reference to the List component that the ComboBox component contains. * The List subcomponent is not instantiated within the ComboBox until it * must be displayed. However, the list is created when the dropdown * property is accessed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get dropdown () : List; + public function get dropdown () : List; /** * Gets the number of items in the list. This property belongs to * the List component but can be accessed from a ComboBox instance. * * @default 0 * * @includeExample examples/ComboBox.length.1.as -noswf * @includeExample examples/ComboBox.length.2.as -noswf * * @see #rowCount * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get length () : int; + public function get length () : int; /** * Gets a reference to the TextInput component that the ComboBox * component contains. Use this property to access and manipulate * the underlying TextInput component. For example, you can use * this property to change the selection of the text box or to * restrict the set of characters that can be entered into it. * * @internal includeExample examples/ComboBox.textField.1.as -noswf * * @includeExample examples/ComboBox.textField.3.as -noswf * @includeExample examples/ComboBox.textField.2.as -noswf * @includeExample examples/ComboBox.textField.4.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get textField () : TextInput; + public function get textField () : TextInput; /** * Gets the label of an item in an editable ComboBox component. For a ComboBox * component that is not editable, this property gets the data that the item contains. * * @includeExample examples/ComboBox.value.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get value () : String; + public function get value () : String; /** * @copy fl.controls.SelectableList#dataProvider * * @see fl.data.DataProvider DataProvider * * @includeExample examples/ComboBox.dataProvider.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get dataProvider () : DataProvider; + public function get dataProvider () : DataProvider; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set dataProvider (value:DataProvider) : void; + public function set dataProvider (value:DataProvider) : void; /** * Gets or sets the maximum width of the drop-down list, in pixels. * The default value of this property is the width of the ComboBox * component (the width of the TextInput instance plus the width of the BaseButton instance). * * @default 100 * * @includeExample examples/ComboBox.dropdownWidth.1.as -noswf * @includeExample examples/ComboBox.dropdownWidth.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get dropdownWidth () : Number; + public function get dropdownWidth () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set dropdownWidth (value:Number) : void; + public function set dropdownWidth (value:Number) : void; /** * Gets or sets the prompt for the ComboBox component. This prompt is a string * that is displayed in the TextInput portion of the ComboBox when * the selectedIndex is -1. It is usually a string like "Select one...". * If a prompt is not set, the ComboBox component sets the selectedIndex property * to 0 and displays the first item in the dataProvider property. * * @default "" * * @includeExample examples/ComboBox.prompt.1.as -noswf * @includeExample examples/ComboBox.prompt.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get prompt () : String; + public function get prompt () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set prompt (value:String) : void; + public function set prompt (value:String) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get imeMode () : String; + public function get imeMode () : String; /** * @private (protected) */ - public function set imeMode (value:String) : void; + public function set imeMode (value:String) : void; /** * Gets the string that is displayed in the TextInput portion * of the ComboBox component. This value is calculated from the data by using * the labelField or labelFunction property. * * @includeExample examples/ComboBox.selectedLabel.1.as -noswf * * @see #labelField * @see #labelFunction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedLabel () : String; - + public function get selectedLabel () : String; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getStyleDefinition () : Object; + public function getStyleDefinition () : Object; /** * Creates a new ComboBox component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ComboBox (); + public function ComboBox (); /** * @copy fl.controls.List#itemToLabel() * * @see #labelField * @see #labelFunction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function itemToLabel (item:Object) : String; + public function itemToLabel (item:Object) : String; /** * @copy fl.controls.SelectableList#addItem() * * @see #addItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addItem (item:Object) : void; + public function addItem (item:Object) : void; /** * @copy fl.controls.SelectableList#addItemAt() * * @see #addItem() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addItemAt (item:Object, index:uint) : void; + public function addItemAt (item:Object, index:uint) : void; /** * @copy fl.controls.SelectableList#removeAll() * * @includeExample examples/ComboBox.removeAll.1.as -noswf * * @see #removeItem() * @see #removeItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeAll () : void; + public function removeAll () : void; /** * @copy fl.controls.SelectableList#removeItem() * * @see #removeAll() * @see #removeItemAt() * * @includeExample examples/ComboBox.removeItem.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeItem (item:Object) : Object; + public function removeItem (item:Object) : Object; /** * Removes the item at the specified index position. The index * locations of items whose indices are greater than the specified * index advance in the array by 1. * *

    This is a method of the List component that is * available from an instance of the ComboBox component.

    * * @param index Index of the item to be removed. * * @throws RangeError The specified index is less than 0 or greater than or * equal to the length of the data provider. * * @see #removeAll() * @see #removeItem() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeItemAt (index:uint) : void; + public function removeItemAt (index:uint) : void; /** * @copy fl.controls.SelectableList#getItemAt() * * @includeExample examples/ComboBox.getItemAt.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getItemAt (index:uint) : Object; + public function getItemAt (index:uint) : Object; /** * @copy fl.controls.SelectableList#replaceItemAt() * * @includeExample examples/ComboBox.replaceItemAt.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function replaceItemAt (item:Object, index:uint) : Object; + public function replaceItemAt (item:Object, index:uint) : Object; /** * @copy fl.controls.SelectableList#sortItems() * * @see Array#sort() * @see #sortItemsOn() * * @includeExample examples/ComboBox.sortItems.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function sortItems (...sortArgs:Array) : *; + public function sortItems (...sortArgs:Array) : *; /** * @copy fl.controls.SelectableList#sortItemsOn() * * @includeExample examples/ComboBox.sortItemsOn.1.as -noswf * @includeExample examples/ComboBox.sortItemsOn.2.as -noswf * * @see Array#sortOn() * @see #sortItems() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function sortItemsOn (field:String, options:Object = null) : *; + public function sortItemsOn (field:String, options:Object = null) : *; /** * Opens the drop-down list. * *

    Note: Calling this method causes the open * event to be dispatched. If the ComboBox component is already open, calling this method has no effect.

    * * @see #close() * @see #event:open * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function open () : void; + public function open () : void; /** * Closes the drop-down list. * *

    Note: Calling this method causes the close * event to be dispatched. If the ComboBox is already closed, calling this method has no effect.

    * * @includeExample examples/ComboBox.close.1.as -noswf * * @see #open() * @see #event:close * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function close () : void; + public function close () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusInHandler (event:FocusEvent) : void; + protected function focusInHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusOutHandler (event:FocusEvent) : void; + protected function focusOutHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleDataChange (event:DataChangeEvent) : void; + protected function handleDataChange (event:DataChangeEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setEmbedFonts () : void; + protected function setEmbedFonts () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function showPrompt () : void; + protected function showPrompt () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setStyles () : void; + protected function setStyles () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawTextFormat () : void; + protected function drawTextFormat () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawList () : void; + protected function drawList () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function positionList () : void; + protected function positionList () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawTextField () : void; + protected function drawTextField () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onInputFieldFocus (event:FocusEvent) : void; + protected function onInputFieldFocus (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onInputFieldFocusOut (event:FocusEvent) : void; + protected function onInputFieldFocusOut (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onEnter (event:ComponentEvent) : void; + protected function onEnter (event:ComponentEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onToggleListVisibility (event:MouseEvent) : void; + protected function onToggleListVisibility (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onListItemUp (event:MouseEvent) : void; + protected function onListItemUp (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onListChange (event:Event) : void; + protected function onListChange (event:Event) : void; /** * @private (protected) */ - protected function onStageClick (event:MouseEvent) : void; + protected function onStageClick (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function passEvent (event:Event) : void; + protected function passEvent (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function addCloseListener (event:Event); + private function addCloseListener (event:Event); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onTextInput (event:Event) : void; + protected function onTextInput (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function calculateAvailableHeight () : Number; + protected function calculateAvailableHeight () : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function highlightCell (index:int = -1) : void; + protected function highlightCell (index:int = -1) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyUpHandler (event:KeyboardEvent) : void; + protected function keyUpHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; - } -} + protected function initializeAccessibility () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/DataGrid.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/DataGrid.as index 5339cac228..d07a747639 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/DataGrid.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/DataGrid.as @@ -1,671 +1,671 @@ -package fl.controls -{ - import fl.controls.dataGridClasses.DataGridColumn; - import fl.controls.dataGridClasses.HeaderRenderer; - import fl.controls.listClasses.CellRenderer; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.listClasses.ListData; - import fl.controls.ScrollPolicy; - import fl.controls.SelectableList; - import fl.controls.TextInput; - import fl.core.UIComponent; - import fl.core.InvalidationType; - import fl.data.DataProvider; - import fl.events.ScrollEvent; - import fl.events.ListEvent; - import fl.events.DataGridEvent; - import fl.events.DataGridEventReason; - import fl.events.DataChangeType; - import fl.events.DataChangeEvent; - import fl.managers.IFocusManager; - import fl.managers.IFocusManagerComponent; - import flash.display.Sprite; - import flash.display.Graphics; - import flash.display.InteractiveObject; - import flash.display.DisplayObjectContainer; - import flash.events.MouseEvent; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.events.FocusEvent; - import flash.ui.Keyboard; - import flash.ui.Mouse; - import flash.display.DisplayObject; - import flash.utils.Dictionary; - import flash.utils.describeType; - import flash.geom.Point; - import flash.system.IME; - +package fl.controls +{ + import fl.controls.dataGridClasses.DataGridColumn; + import fl.controls.dataGridClasses.HeaderRenderer; + import fl.controls.listClasses.CellRenderer; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.listClasses.ListData; + import fl.controls.ScrollPolicy; + import fl.controls.SelectableList; + import fl.controls.TextInput; + import fl.core.UIComponent; + import fl.core.InvalidationType; + import fl.data.DataProvider; + import fl.events.ScrollEvent; + import fl.events.ListEvent; + import fl.events.DataGridEvent; + import fl.events.DataGridEventReason; + import fl.events.DataChangeType; + import fl.events.DataChangeEvent; + import fl.managers.IFocusManager; + import fl.managers.IFocusManagerComponent; + import flash.display.Sprite; + import flash.display.Graphics; + import flash.display.InteractiveObject; + import flash.display.DisplayObjectContainer; + import flash.events.MouseEvent; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.FocusEvent; + import flash.ui.Keyboard; + import flash.ui.Mouse; + import flash.display.DisplayObject; + import flash.utils.Dictionary; + import flash.utils.describeType; + import flash.geom.Point; + import flash.system.IME; + /** * Dispatched after the user clicks a header cell. * * @includeExample examples/DataGrid.headerRelease.1.as -noswf * * @eventType fl.events.DataGridEvent.HEADER_RELEASE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="headerRelease", type="fl.events.DataGridEvent")] + [Event(name="headerRelease", type="fl.events.DataGridEvent")] /** * Dispatched after a user expands a column horizontally. * * @includeExample examples/DataGrid.columnStretch.1.as -noswf * * @eventType fl.events.DataGridEvent.COLUMN_STRETCH * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="columnStretch", type="fl.events.DataGridEvent")] + [Event(name="columnStretch", type="fl.events.DataGridEvent")] /** * Dispatched after a user prepares to edit an item, for example, * by releasing the mouse button over the item. * * @eventType fl.events.DataGridEvent.ITEM_EDIT_BEGINNING * * @see #event:itemEditBegin * @see #event:itemEditEnd * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemEditBeginning", type="fl.events.DataGridEvent")] + [Event(name="itemEditBeginning", type="fl.events.DataGridEvent")] /** * Dispatched after the editedItemPosition property is set * and the item can be edited. * * @eventType fl.events.DataGridEvent.ITEM_EDIT_BEGIN * * @see #event:itemEditBeginning * @see #event:itemEditEnd * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemEditBegin", type="fl.events.DataGridEvent")] + [Event(name="itemEditBegin", type="fl.events.DataGridEvent")] /** * Dispatched when an item editing session ends for any reason. * * @eventType fl.events.DataGridEvent.ITEM_EDIT_END * * @see #event:itemEditBegin * @see #event:itemEditBeginning * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemEditEnd", type="fl.events.DataGridEvent")] + [Event(name="itemEditEnd", type="fl.events.DataGridEvent")] /** * Dispatched after an item receives focus. * * @eventType fl.events.DataGridEvent.ITEM_FOCUS_IN * * @see #event:itemFocusOut * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemFocusIn", type="fl.events.DataGridEvent")] + [Event(name="itemFocusIn", type="fl.events.DataGridEvent")] /** * Dispatched after an item loses focus. * * @eventType fl.events.DataGridEvent.ITEM_FOCUS_OUT * * @see #event:itemFocusIn * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemFocusOut", type="fl.events.DataGridEvent")] + [Event(name="itemFocusOut", type="fl.events.DataGridEvent")] /** * The name of the class that provides the cursor that is used when * the mouse is between two column headers and the resizableColumns * property is set to true. * * @default DataGrid_columnStretchCursorSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="columnStretchCursorSkin", type="Class")] + [Style(name="columnStretchCursorSkin", type="Class")] /** * The name of the class that provides the divider that appears * between columns. * * @default DataGrid_columnDividerSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="columnDividerSkin", type="Class")] + [Style(name="columnDividerSkin", type="Class")] /** * The name of the class that provides the background for each column header. * * @default HeaderRenderer_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerUpSkin", type="Class")] + [Style(name="headerUpSkin", type="Class")] /** * The name of the class that provides the background for each column header * when the mouse is over it. * * @default HeaderRenderer_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerOverSkin", type="Class")] + [Style(name="headerOverSkin", type="Class")] /** * The name of the class that provides the background for each column header * when the mouse is down. * * @default HeaderRenderer_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerDownSkin", type="Class")] + [Style(name="headerDownSkin", type="Class")] /** * The name of the class that provides the background for each column header * when the component is disabled. * * @default HeaderRenderer_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerDisabledSkin", type="Class")] + [Style(name="headerDisabledSkin", type="Class")] /** * The name of the class that provides the sort arrow when the sorted * column is in descending order. * * @default HeaderSortArrow_descIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerSortArrowDescSkin", type="Class")] + [Style(name="headerSortArrowDescSkin", type="Class")] /** * The name of the class that provides the sort arrow when the sorted * column is in ascending order. * * @default HeaderSortArrow_ascIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerSortArrowAscSkin", type="Class")] + [Style(name="headerSortArrowAscSkin", type="Class")] /** * The format to be applied to the text contained in each column header. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerTextFormat", type="flash.text.TextFormat")] + [Style(name="headerTextFormat", type="flash.text.TextFormat")] /** * The format to be applied to the text contained in each column header * when the component is disabled. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerDisabledTextFormat", type="flash.text.TextFormat")] + [Style(name="headerDisabledTextFormat", type="flash.text.TextFormat")] /** * The padding that separates the column header border from the column header * text, in pixels. * * @default 5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerTextPadding", type="Number", format="Length")] + [Style(name="headerTextPadding", type="Number", format="Length")] /** * The name of the class that provides each column header. * * @default fl.controls.dataGridClasses.HeaderRenderer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="headerRenderer", type="Class")] - + [Style(name="headerRenderer", type="Class")] + /** * The DataGrid class is a list-based component that provides a grid of * rows and columns. You can specify an optional header row at the top * of the component that shows all the property names. Each row consists * of one or more columns, each of which represents a property that belongs * to the specified data object. The DataGrid component is used to view data; * it is not intended to be used as a layout tool like an HTML table. * *

    A DataGrid component is well suited for the display of objects that contain * multiple properties. The data that a DataGrid component displays can * be contained in a DataProvider object or as an array of objects. The columns of a DataGrid * component can be represented by a list of DataGridColumn objects, * each of which contains information that is specific to the column.

    * *

    The DataGrid component provides the following features:

    *
      *
    • Columns of different widths or identical fixed widths
    • *
    • Columns that the user can resize at run time
    • *
    • Columns that the user can reorder at run time by using ActionScript
    • *
    • Optional customizable column headers
    • *
    • Support for custom item renderers to display data other than text * in any column
    • *
    • Support for sorting data by clicking on the column that contains it
    • *
    * *

    The DataGrid component is composed of subcomponents including ScrollBar, * HeaderRenderer, CellRenderer, DataGridCellEditor, and ColumnDivider components, all of which * can be skinned during authoring or at run time.

    * *

    The DataGrid component uses the following classes that can be found in the dataGridClasses package:

    *
      *
    • DataGridColumn: Describes a column in a DataGrid component. Contains the indexes, * widths, and other properties of the column. Does not contain cell data.
    • *
    • HeaderRenderer: Displays the column header for the current DataGrid column. Contains * the label and other properties of the column header.
    • *
    • DataGridCellEditor: Manages the editing of the data for each cell.
    • *
    * * @includeExample examples/DataGridExample.as * * @see fl.controls.dataGridClasses.DataGridCellEditor DataGridCellEditor * @see fl.controls.dataGridClasses.DataGridColumn DataGridColumn * @see fl.controls.dataGridClasses.HeaderRenderer HeaderRenderer * @see fl.controls.listClasses.CellRenderer CellRenderer * @see fl.events.DataGridEvent DataGridEvent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataGrid extends SelectableList implements IFocusManagerComponent - { + public class DataGrid extends SelectableList implements IFocusManagerComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _rowHeight : Number; + protected var _rowHeight : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _headerHeight : Number; + protected var _headerHeight : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _showHeaders : Boolean; + protected var _showHeaders : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _columns : Array; + protected var _columns : Array; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _minColumnWidth : Number; + protected var _minColumnWidth : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var header : Sprite; + protected var header : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var headerMask : Sprite; + protected var headerMask : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var headerSortArrow : Sprite; + protected var headerSortArrow : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _cellRenderer : Object; + protected var _cellRenderer : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _headerRenderer : Object; + protected var _headerRenderer : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _labelFunction : Function; + protected var _labelFunction : Function; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var visibleColumns : Array; + protected var visibleColumns : Array; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var displayableColumns : Array; + protected var displayableColumns : Array; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var columnsInvalid : Boolean; + protected var columnsInvalid : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var minColumnWidthInvalid : Boolean; + protected var minColumnWidthInvalid : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var activeCellRenderersMap : Dictionary; + protected var activeCellRenderersMap : Dictionary; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var availableCellRenderersMap : Dictionary; + protected var availableCellRenderersMap : Dictionary; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var dragHandlesMap : Dictionary; + protected var dragHandlesMap : Dictionary; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var columnStretchIndex : Number; + protected var columnStretchIndex : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var columnStretchStartX : Number; + protected var columnStretchStartX : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var columnStretchStartWidth : Number; + protected var columnStretchStartWidth : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var columnStretchCursor : Sprite; + protected var columnStretchCursor : Sprite; /** * @private (protected) * The index of the column being sorted. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _sortIndex : int; + protected var _sortIndex : int; /** * @private (protected) * The index of the last column being sorted on. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var lastSortIndex : int; + protected var lastSortIndex : int; /** * @private (protected) * The direction of the current sort. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _sortDescending : Boolean; + protected var _sortDescending : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _editedItemPosition : Object; + protected var _editedItemPosition : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var editedItemPositionChanged : Boolean; + protected var editedItemPositionChanged : Boolean; /** * @private (protected) * undefined means we've processed it, null means don't put up an editor * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var proposedEditedItemPosition : *; + protected var proposedEditedItemPosition : *; /** * @private (protected) * Last known position of item editor instance * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var actualRowIndex : int; + protected var actualRowIndex : int; /** * @private (protected) * Last known position of item editor instance * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var actualColIndex : int; + protected var actualColIndex : int; /** * @private (protected) * Whether the mouse button is pressed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var isPressed : Boolean; + protected var isPressed : Boolean; /** * @private (protected) * True if we want to block editing on mouseUp. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var losingFocus : Boolean; + protected var losingFocus : Boolean; /** * @private (protected) * Stores the user set headerheight (we modify header height when dg is resized down) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var maxHeaderHeight : Number; + protected var maxHeaderHeight : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var currentHoveredRow : int; + protected var currentHoveredRow : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected static const HEADER_STYLES : Object; + protected static const HEADER_STYLES : Object; /** * @private * Creates the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var createAccessibilityImplementation : Function; + public var createAccessibilityImplementation : Function; /** * Indicates whether or not the user can edit items in the data provider. * A value of true indicates that the user can edit items in the * data provider; a value of false indicates that the user cannot. * *

    If this value is true, the item renderers in the component * are editable. The user can click on an item renderer to open an editor.

    * *

    You can turn off editing for individual columns of the DataGrid component * by using the DataGridColumn.editable property, or by handling * the itemEditBeginning and itemEditBegin events.

    * * @default false * * @see #event:itemEditBegin * @see #event:itemEditBeginning * @see fl.controls.dataGridClasses.DataGridColumn#editable DataGridColumn.editable * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var editable : Boolean; + public var editable : Boolean; /** * Indicates whether the user can change the size of the * columns. A value of true indicates that the user can * change the column size; a value of false indicates that * column size is fixed. * *

    If this value is true, the user can stretch or shrink * the columns of the DataGrid component by dragging the grid lines between * the header cells. Additionally, if this value is true, * the user can change the size of the columns unless the resizeable * properties of individual columns are set to false.

    * * @default true * * @includeExample examples/DataGrid.resizableColumns.1.as -noswf * * @see fl.controls.dataGridClasses.DataGridColumn#resizable DataGridColumn.resizable * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var resizableColumns : Boolean; + public var resizableColumns : Boolean; /** * Indicates whether the user can sort the items in the data provider * by clicking on a column header cell. If this value is true, * the user can sort the data provider items by clicking on a column header cell; * if this value is false, the user cannot. * *

    If this value is true, to prevent an individual column * from responding to a user mouse click on a header cell, set the * sortable property of that column to false.

    * *

    The sort field of a column is either the dataField or * sortCompareFunction property of the DataGridColumn component. * If the user clicks a column more than one time, the sort operation * alternates between ascending and descending order.

    * *

    If both this property and the sortable property of a * column are set to true, the DataGrid component dispatches * a headerRelease event after the user releases the mouse * button of the column header cell. If a call is not made to the preventDefault() * method from a handler method of the headerRelease event, * the DataGrid component performs a sort based on the values of the dataField * or sortCompareFunction properties.

    * * @default true * * @includeExample examples/DataGrid.sortableColumns.1.as -noswf * * @see fl.controls.dataGridClasses.DataGridColumn#sortable DataGridColumn.sortable * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var sortableColumns : Boolean; + public var sortableColumns : Boolean; /** * A reference to the currently active instance of the item editor, * if one exists. * *

    To access the item editor instance and the new item value when an * item is being edited, use the itemEditorInstance * property. The itemEditorInstance property is not valid * until after the event listener for the itemEditBegin * event executes. For this reason, the itemEditorInstance property * is typically accessed from the event listener for the itemEditEnd * event.

    * *

    The DataGridColumn.itemEditor property defines the * class of the item editor, and therefore, the data type of the * item editor instance.

    * * @includeExample examples/DataGrid.itemEditorInstance.1.as -noswf * * @see #event:itemEditBegin * @see #event:itemEditEnd * @see fl.controls.dataGridClasses.DataGridColumn#itemEditor DataGridColumn.itemEditor * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var itemEditorInstance : Object; - + public var itemEditorInstance : Object; + /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set dataProvider (dataSource:DataProvider) : void; + public function set dataProvider (dataSource:DataProvider) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether the * horizontal scroll bar is always on. The following list describes * the valid values: * *
      *
    • ScrollPolicy.ON: The scroll bar is always on.
    • *
    • ScrollPolicy.OFF: The scroll bar is always off.
    • *
    • ScrollPolicy.AUTO: The state of the scroll bar changes * based on the parameters that are passed to the setScrollBarProperties() * method.
    • *
    * *

    Note: If the combined width of the visible columns in the DataGrid * component is smaller than the available width of the DataGrid component, the columns may not expand to fill * the available space of the DataGrid component, depending on the value of the * horizontalScrollPolicy property. The following list describes * these values and their effects:

    * *
      *
    • ScrollPolicy.ON: The horizontal scroll bar is disabled. The columns do not expand * to fill the available space of the DataGrid component.
    • *
    • ScrollPolicy.AUTO: The horizontal scroll bar is not visible. The columns do not expand * to fill the available space of the DataGrid component.
    • *
    * * @default ScrollPolicy.OFF * * @see fl.containers.BaseScrollPane#verticalScrollPolicy BaseScrollPane.verticalScrollPolicy * @see ScrollPolicy * * @includeExample examples/DataGrid.horizontalScrollPolicy.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollPolicy () : String; + public function get horizontalScrollPolicy () : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalScrollPolicy (policy:String) : void; + public function set horizontalScrollPolicy (policy:String) : void; /** * Gets or sets an array of DataGridColumn objects, one for each column that can be displayed. * If not explicitly set, the DataGrid component examines the first item in the * data provider, locates its properties, and then displays those properties * in alphabetic order. * *

    You can make changes to the columns and to their order in this DataGridColumn * array. After the changes are made, however, you must explicitly assign the * changed array to the columns property. If an explicit assignment * is not made, the set of columns that was used before will continue to be used.

    * * @default [] * * @includeExample examples/DataGrid.columns.1.as -noswf * @includeExample examples/DataGrid.columns.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get columns () : Array; + public function get columns () : Array; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set columns (value:Array) : void; + public function set columns (value:Array) : void; /** * Gets or sets the minimum width of a DataGrid column, in pixels. * If this value is set to NaN, the minimum column * width can be individually set for each column of the DataGrid component. * * @default NaN * * @includeExample examples/DataGrid.minColumnWidth.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get minColumnWidth () : Number; + public function get minColumnWidth () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set minColumnWidth (value:Number) : void; + public function set minColumnWidth (value:Number) : void; /** * Gets or sets a function that determines which fields of each * item to use for the label text. * * @default null * * @includeExample examples/DataGrid.labelFunction.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelFunction () : Function; + public function get labelFunction () : Function; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelFunction (value:Function) : void; + public function set labelFunction (value:Function) : void; /** * Gets or sets the number of rows that are at least partially visible in the * list. * * @includeExample examples/DataGrid.rowCount.1.as -noswf * * @see SelectableList#length SelectableList.length * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowCount () : uint; + public function get rowCount () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set rowCount (value:uint) : void; + public function set rowCount (value:uint) : void; /** * Gets or sets the height of each row in the DataGrid component, in pixels. * * @default 20 * * @includeExample examples/DataGrid.rowHeight.1.as -noswf * * @see #headerHeight * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowHeight () : Number; + public function get rowHeight () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set rowHeight (value:Number) : void; + public function set rowHeight (value:Number) : void; /** * Gets or sets the height of the DataGrid header, in pixels. * * @default 25 * * @includeExample examples/DataGrid.headerHeight.1.as -noswf * * @see #rowHeight * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get headerHeight () : Number; + public function get headerHeight () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set headerHeight (value:Number) : void; + public function set headerHeight (value:Number) : void; /** * Gets or sets a Boolean value that indicates whether the DataGrid component shows column headers. * A value of true indicates that the DataGrid component shows column headers; a value * of false indicates that it does not. * * @default true * * @includeExample examples/DataGrid.showHeaders.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get showHeaders () : Boolean; + public function get showHeaders () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set showHeaders (value:Boolean) : void; + public function set showHeaders (value:Boolean) : void; /** * Gets the index of the column to be sorted. * * @default -1 * * @see #sortDescending * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get sortIndex () : int; + public function get sortIndex () : int; /** * Gets the order in which a column is sorted when * the user clicks its header. A value of true * indicates that the column is sorted in descending order; a * value of false indicates that the column is * sorted in ascending order. * *

    The sortDescending property does not affect * how the sort method completes the sort operation. By default, * the sort operation involves a case-sensitive string sort. * To change this behavior, modify the sortOptions * and sortCompareFunction properties of the DataGridColumn * class.

    * *

    Note: If you query this property from an event * listener for the headerRelease event, the property value * identifies the sort order for the previous sort operation. This * is because the next sort has not yet occurred.

    * * * * @default false * * @includeExample examples/DataGrid.sortDescending.1.as -noswf * * @see fl.controls.dataGridClasses.DataGridColumn#sortOptions DataGridColumn.sortOptions * @see fl.controls.dataGridClasses.DataGridColumn#sortCompareFunction DataGridColumn.sortCompareFunction * @see Array#sort() Array.sort() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get sortDescending () : Boolean; + public function get sortDescending () : Boolean; /** * @copy fl.controls.TextArea#imeMode * * @see flash.system.IMEConversionMode IMEConversionMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get imeMode () : String; + public function get imeMode () : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set imeMode (value:String) : void; + public function set imeMode (value:String) : void; /** * Gets a reference to the item renderer in the DataGrid component whose item is currently being * edited. If no item is being edited, this property contains a value of null. * *

    You can obtain the current value of the item that is being edited by using the * editedItemRenderer.data property from an event listener for the * itemEditBegin event or the itemEditEnd event.

    * *

    This is a read-only property. To set a custom item editor, use the itemEditor * property of the class that represents the relevant column.

    * * @see fl.controls.dataGridClasses.DataGridColumn#itemEditor DataGridColumn.itemEditor * * @includeExample examples/DataGrid.editedItemPosition.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get editedItemRenderer () : ICellRenderer; + public function get editedItemRenderer () : ICellRenderer; /** * Gets or sets the column and row index of the item renderer for * the data provider item that is being edited. If no item is being * edited, this property is null. * *

    This object has two fields:

    * *
      *
    • columnIndex: The zero-based column index of the current item
    • *
    • rowIndex: The zero-based row index of the current item
    • *
    * *

    For example: { columnIndex:2, rowIndex:3 }

    * *

    Setting this property scrolls the item into view and dispatches the * itemEditBegin event to open an item editor on the specified * item renderer.

    * * @default null * * @includeExample examples/DataGrid.editedItemPosition.1.as -noswf * * @see #event:itemEditBegin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get editedItemPosition () : Object; + public function get editedItemPosition () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set editedItemPosition (value:Object) : void; - + public function set editedItemPosition (value:Object) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new DataGrid component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function DataGrid (); + public function DataGrid (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSize (w:Number, h:Number) : void; + public function setSize (w:Number, h:Number) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function calculateAvailableHeight () : Number; + protected function calculateAvailableHeight () : Number; /** * Adds a column to the end of the columns array. * * @param column A String or a DataGridColumn object. * * @return The DataGridColumn object that was added. * * @see #addColumnAt() * * @includeExample examples/DataGrid.addColumn.2.as -noswf * @includeExample examples/DataGrid.addColumn.3.as -noswf * @includeExample examples/DataGrid.addColumn.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addColumn (column:*) : DataGridColumn; + public function addColumn (column:*) : DataGridColumn; /** * Inserts a column at the specified index in the columns array. * * @param column The string or DataGridColumn object that represents the column to be inserted. * @param index The array index that identifies the location at which the column is to be inserted. * * @return The DataGridColumn object that was inserted into the array of columns. * * @see #addColumn() * * @includeExample examples/DataGrid.addColumn.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addColumnAt (column:*, index:uint) : DataGridColumn; + public function addColumnAt (column:*, index:uint) : DataGridColumn; /** * Removes the column that is located at the specified index of the columns array. * * @param index The index of the column to be removed. * * @return The DataGridColumn object that was removed. This method returns null * if a column is not found at the specified index. * * @see #removeAllColumns() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeColumnAt (index:uint) : DataGridColumn; + public function removeColumnAt (index:uint) : DataGridColumn; /** * Removes all columns from the DataGrid component. * * @see #removeColumnAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeAllColumns () : void; + public function removeAllColumns () : void; /** * Retrieves the column that is located at the specified index of the columns array. * * @param index The index of the column to be retrieved, or null * if a column is not found. * * @return The DataGridColumn object that was found at the specified index. * * @see #getColumnIndex() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getColumnAt (index:uint) : DataGridColumn; + public function getColumnAt (index:uint) : DataGridColumn; /** * Retrieves the index of the column of the specified name, * or -1 if no match is found. * * @param name The data field of the column to be located. * * @return The index of the location at which the column of the * specified name is found. * * @see #getColumnAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getColumnIndex (name:String) : int; + public function getColumnIndex (name:String) : int; /** * Retrieves the number of columns in the DataGrid component. * * @return The number of columns contained in the DataGrid component. * * @includeExample examples/DataGrid.columns.2.as -noswf * @includeExample examples/DataGrid.columns.3.as -noswf * * @see #rowCount * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getColumnCount () : uint; + public function getColumnCount () : uint; /** * Resets the widths of the visible columns to the same size. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function spaceColumnsEqually () : void; + public function spaceColumnsEqually () : void; /** * Edits a given field or property in the DataGrid component. * * @param index The index of the data provider item to be edited. * * @param dataField The name of the field or property in the data provider item to be edited. * * @param data The new data value. * * @throws RangeError The specified index is less than 0 or greater than or equal to the * length of the data provider. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function editField (index:uint, dataField:String, data:Object) : void; + public function editField (index:uint, dataField:String, data:Object) : void; /** * The DataGrid component has multiple cells for any given item, so the itemToCellRenderer * method always returns null. * * @param item The item in the data provider. * * @return null. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function itemToCellRenderer (item:Object) : ICellRenderer; + public function itemToCellRenderer (item:Object) : ICellRenderer; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawList () : void; + protected function drawList () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateRendererStyles () : void; + protected function updateRendererStyles () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function removeCellRenderers () : void; + protected function removeCellRenderers () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function removeCellRenderersByColumn (col:DataGridColumn) : void; + protected function removeCellRenderersByColumn (col:DataGridColumn) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleCellRendererMouseEvent (event:MouseEvent) : void; + protected function handleCellRendererMouseEvent (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function isHovered (renderer:ICellRenderer) : Boolean; + protected function isHovered (renderer:ICellRenderer) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setHorizontalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setHorizontalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function columnItemToLabel (columnIndex:uint, item:Object) : String; + public function columnItemToLabel (columnIndex:uint, item:Object) : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function calculateColumnSizes () : void; + protected function calculateColumnSizes () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function calculateContentWidth () : void; + protected function calculateContentWidth () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleHeaderRendererClick (event:MouseEvent) : void; + protected function handleHeaderRendererClick (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function resizeColumn (columnIndex:int, w:Number) : void; + public function resizeColumn (columnIndex:int, w:Number) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function sortByColumn (index:int) : void; + protected function sortByColumn (index:int) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function createColumnsFromDataProvider () : void; + protected function createColumnsFromDataProvider () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getVisibleColumnIndex (column:DataGridColumn) : int; + protected function getVisibleColumnIndex (column:DataGridColumn) : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleHeaderResizeOver (event:MouseEvent) : void; + protected function handleHeaderResizeOver (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleHeaderResizeOut (event:MouseEvent) : void; + protected function handleHeaderResizeOut (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleHeaderResizeDown (event:MouseEvent) : void; + protected function handleHeaderResizeDown (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleHeaderResizeMove (event:MouseEvent) : void; + protected function handleHeaderResizeMove (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleHeaderResizeUp (event:MouseEvent) : void; + protected function handleHeaderResizeUp (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function showColumnStretchCursor (show:Boolean = true) : void; + protected function showColumnStretchCursor (show:Boolean = true) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function positionColumnStretchCursor (event:MouseEvent) : void; + protected function positionColumnStretchCursor (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setEditedItemPosition (coord:Object) : void; + protected function setEditedItemPosition (coord:Object) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function commitEditedItemPosition (coord:Object) : void; + protected function commitEditedItemPosition (coord:Object) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function itemEditorItemEditBeginningHandler (event:DataGridEvent) : void; + protected function itemEditorItemEditBeginningHandler (event:DataGridEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function itemEditorItemEditBeginHandler (event:DataGridEvent) : void; + protected function itemEditorItemEditBeginHandler (event:DataGridEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function itemEditorItemEditEndHandler (event:DataGridEvent) : void; + protected function itemEditorItemEditEndHandler (event:DataGridEvent) : void; /** * @private (protected) * When we get focus, focus an item renderer. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusInHandler (event:FocusEvent) : void; + protected function focusInHandler (event:FocusEvent) : void; /** * @private (protected) * When we lose focus, close the editor. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusOutHandler (event:FocusEvent) : void; + protected function focusOutHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function editorMouseDownHandler (event:MouseEvent) : void; + protected function editorMouseDownHandler (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function editorKeyDownHandler (event:KeyboardEvent) : void; + protected function editorKeyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * Determines the next item renderer to navigate to using the Tab key. * If the item renderer to be focused falls out of range (the end or beginning * of the grid) then move focus outside the grid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function findNextItemRenderer (shiftKey:Boolean) : Boolean; + protected function findNextItemRenderer (shiftKey:Boolean) : Boolean; /** * @private (protected) * Find the next item renderer down from the currently edited item renderer, and focus it. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function findNextEnterItemRenderer (event:KeyboardEvent) : void; + protected function findNextEnterItemRenderer (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function mouseFocusChangeHandler (event:MouseEvent) : void; + protected function mouseFocusChangeHandler (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyFocusChangeHandler (event:FocusEvent) : void; + protected function keyFocusChangeHandler (event:FocusEvent) : void; /** * @private * Hides the itemEditorInstance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function itemEditorFocusOutHandler (event:FocusEvent) : void; + private function itemEditorFocusOutHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function deactivateHandler (event:Event) : void; + protected function deactivateHandler (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function mouseDownHandler (event:MouseEvent) : void; + protected function mouseDownHandler (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function mouseUpHandler (event:MouseEvent) : void; + protected function mouseUpHandler (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleCellRendererClick (event:MouseEvent) : void; + protected function handleCellRendererClick (event:MouseEvent) : void; /** * Uses the editor specified by the itemEditor property to * create an item editor for the item renderer at the column and row index * identified by the editedItemPosition property. * *

    This method sets the editor instance as the itemEditorInstance * property.

    * *

    You can call this method from the event listener for the itemEditBegin * event. To create an editor from other code, set the editedItemPosition * property to generate the itemEditBegin event.

    * * @param colIndex The column index of the item to be edited in the data provider. * @param rowIndex The row index of the item to be edited in the data provider. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function createItemEditor (colIndex:uint, rowIndex:uint) : void; + public function createItemEditor (colIndex:uint, rowIndex:uint) : void; /** * Closes an item editor that is currently open on an item renderer. This method is * typically called from the event listener for the itemEditEnd event, * after a call is made to the preventDefault() method to prevent the * default event listener from executing. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function destroyItemEditor () : void; + public function destroyItemEditor () : void; /** * @private (protected) * This method is called after the user finishes editing an item. * It dispatches the itemEditEnd event to start the process * of copying the edited data from * the itemEditorInstance to the data provider and hiding the itemEditorInstance. * returns true if nobody called the preventDefault() method. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function endEdit (reason:String) : Boolean; + protected function endEdit (reason:String) : Boolean; /** * Get the instance of a cell renderer at the specified position * in the DataGrid. * *

    Note: This method returns null * for positions that are not visible (i.e. scrolled out of the * view).

    * * @param row A row index. * @param column A column index. * * @return The ICellRenderer object at the specified position, or * null if no cell renderer exists at that position. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getCellRendererAt (row:uint, column:uint) : ICellRenderer; + public function getCellRendererAt (row:uint, column:uint) : ICellRenderer; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function itemRendererContains (renderer:Object, object:DisplayObject) : Boolean; + protected function itemRendererContains (renderer:Object, object:DisplayObject) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleDataChange (event:DataChangeEvent) : void; + protected function handleDataChange (event:DataChangeEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * Moves the selection in a horizontal direction in response * to the user selecting items using the left-arrow or right-arrow * keys and modifiers such as the Shift and Ctrl keys. * *

    Not implemented in List because the default list * is single column and therefore doesn't scroll horizontally.

    * * @param code The key that was pressed (e.g. Keyboard.LEFT) * @param shiftKey true if the shift key was held down when * the keyboard key was pressed. * @param ctrlKey true if the ctrl key was held down when * the keyboard key was pressed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function moveSelectionHorizontally (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function moveSelectionHorizontally (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * Moves the selection in a vertical direction in response * to the user selecting items using the up-arrow or down-arrow * Keys and modifiers such as the Shift and Ctrl keys. * * @param code The key that was pressed (e.g. Keyboard.DOWN) * @param shiftKey true if the shift key was held down when * the keyboard key was pressed. * @param ctrlKey true if the ctrl key was held down when * the keyboard key was pressed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function moveSelectionVertically (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function moveSelectionVertically (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @copy fl.controls.SelectableList#scrollToIndex() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function scrollToIndex (newCaretIndex:int) : void; + public function scrollToIndex (newCaretIndex:int) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function scrollToPosition (rowIndex:int, columnIndex:int) : void; + protected function scrollToPosition (rowIndex:int, columnIndex:int) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function doKeySelection (newCaretIndex:int, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function doKeySelection (newCaretIndex:int, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; - } -} + protected function initializeAccessibility () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/Label.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/Label.as index 87dbd90a8c..8a5f868296 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/Label.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/Label.as @@ -1,148 +1,148 @@ -package fl.controls -{ - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.TextEvent; - import fl.controls.TextInput; - import flash.text.TextField; - import flash.text.TextFieldAutoSize; - import flash.text.TextFieldType; - import flash.text.TextFormat; - +package fl.controls +{ + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.TextEvent; + import fl.controls.TextInput; + import flash.text.TextField; + import flash.text.TextFieldAutoSize; + import flash.text.TextFieldType; + import flash.text.TextFormat; + /** * Dispatched after there is a change in the width or height of the component. *

    Note: This event does not occur if you use ActionScript code to change the label text.

    * * @eventType fl.events.ComponentEvent.RESIZE * * @includeExample examples/Label.resize.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="resize", type="fl.events.ComponentEvent")] + [Event(name="resize", type="fl.events.ComponentEvent")] /** * @copy fl.controls.LabelButton#style:embedFonts * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="embedFonts", type="Boolean")] - + [Style(name="embedFonts", type="Boolean")] + /** * A Label component displays one or more lines of plain or * HTML-formatted text that can be formatted for alignment and * size. Label components do not have borders and cannot receive * focus. * *

    A live preview of each Label instance reflects the changes * that were made to parameters in the Property inspector or Component * inspector during authoring. Because a Label component does not have a border, * the only way to see the live preview for a Label instance is to set * its text property. The autoSize property is not supported * in live preview.

    * * @includeExample examples/LabelExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class Label extends UIComponent - { + public class Label extends UIComponent + { /** * A reference to the internal text field of the Label component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var textField : TextField; + public var textField : TextField; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var actualWidth : Number; + protected var actualWidth : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var actualHeight : Number; + protected var actualHeight : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var defaultLabel : String; + protected var defaultLabel : String; /** * @private (protected) */ - protected var _savedHTML : String; + protected var _savedHTML : String; /** * @private (protected) */ - protected var _html : Boolean; + protected var _html : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * Gets or sets the plain text to be displayed by the Label component. * *

    Note that characters that represent HTML markup have no special * meaning in the string and will appear as they were entered.

    * *

    To display text that contains HTML tags, use the htmlText * property. The HTML replaces any text that you set by using the htmlText * property, and the text property returns a plain text version of * the HTML text, with the HTML tags removed.

    * *

    If the text property is changed from the default value in the * property inspector, it takes precedence over the htmlText * property in the property inspector.

    * * @default "Label" * * @see #htmlText * @see flash.text.TextField#text * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get text () : String; + public function get text () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set text (value:String) : void; + public function set text (value:String) : void; /** * Gets or sets the text to be displayed by the Label component, including * HTML markup that expresses the styles of that text. You can specify HTML * text in this property by using the subset of HTML tags that are supported * by the TextField object. * *

    If the default value of the text property is changed in the * Property inspector, this changed value takes precedence over any value in the * htmlText property field in the Property inspector. To use the * htmlText property in the Property inspector, the text property * field must contain the value Label, exactly as shown. When coding with * ActionScript, you do not need to set the value of the text property; the * default value is Label.

    * * @default "" * * @see #text * @see flash.text.TextField#htmlText * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get htmlText () : String; + public function get htmlText () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set htmlText (value:String) : void; + public function set htmlText (value:String) : void; /** * Gets or sets a value that indicates whether extra white space such as spaces * and line breaks should be removed from a Label component that contains HTML text. * A value of true indicates that white space is to be removed; a * value of false indicates that it remains. * *

    The condenseWhite property affects only text that was set by * using the htmlText property, not the text property. * If you set text by using the text property, the condenseWhite * property is ignored.

    * *

    If you set the condenseWhite property to true, * you must use standard HTML commands, such as <br> and <p>, to break * the lines of the text in the text field.

    * * @default false * * @includeExample examples/Label.condenseWhite.1.as -noswf * * @see #htmlText * @see flash.text.TextField#condenseWhite * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get condenseWhite () : Boolean; + public function get condenseWhite () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set condenseWhite (value:Boolean) : void; + public function set condenseWhite (value:Boolean) : void; /** * Gets or sets a value that indicates whether the text can be selected. A value * of true indicates that it can be selected; a value of false * indicates that it cannot. * *

    Text that can be selected can be copied from the Label component by the user.

    * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectable () : Boolean; + public function get selectable () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectable (value:Boolean) : void; + public function set selectable (value:Boolean) : void; /** * Gets or sets a value that indicates whether the text field supports word wrapping. * A value of true indicates that it does; a value of false * indicates that it does not. * * @default false * * @includeExample examples/Label.wordWrap.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get wordWrap () : Boolean; + public function get wordWrap () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set wordWrap (value:Boolean) : void; + public function set wordWrap (value:Boolean) : void; /** * Gets or sets a string that indicates how a label is sized and aligned to * fit the value of its text property. The following are * valid values: *
      *
    • TextFieldAutoSize.NONE: The label is not resized or aligned to fit the text.
    • *
    • TextFieldAutoSize.LEFT: The right and bottom sides of the label are resized to fit the text. * The left and top sides are not resized.
    • *
    • TextFieldAutoSize.CENTER: The left and right sides of the label resize to fit the text. * The horizontal center of the label stays anchored at its original horizontal * center position.
    • *
    • TextFieldAutoSize.RIGHT: The left and bottom sides of the label are resized to fit * the text. The top and right sides are not resized.
    • *
    * * @default TextFieldAutoSize.NONE * * @includeExample examples/Label.autoSize.1.as -noswf * * @see flash.text.TextFieldAutoSize TextFieldAutoSize * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get autoSize () : String; + public function get autoSize () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set autoSize (value:String) : void; + public function set autoSize (value:String) : void; /** * @copy fl.core.UIComponent#width * * @see #height * @see fl.core.UIComponent#setSize() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get width () : Number; + public function get width () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set width (value:Number) : void; + public function set width (value:Number) : void; /** * @copy fl.core.UIComponent#height * * @see #width * @see fl.core.UIComponent#setSize() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get height () : Number; - + public function get height () : Number; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() UIComponent#setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new Label component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function Label (); + public function Label (); /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSize (width:Number, height:Number) : void; + public function setSize (width:Number, height:Number) : void; /** * @private (protected) */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawTextFormat () : void; + protected function drawTextFormat () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; - } -} + protected function drawLayout () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/LabelButton.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/LabelButton.as index fd68f3b5cf..b6bfea48a8 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/LabelButton.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/LabelButton.as @@ -1,238 +1,238 @@ -package fl.controls -{ - import fl.controls.BaseButton; - import fl.controls.ButtonLabelPlacement; - import fl.controls.TextInput; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - import fl.managers.IFocusManagerComponent; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.display.DisplayObject; - import flash.display.Sprite; - import flash.geom.Point; - import flash.text.TextField; - import flash.text.TextFieldType; - import flash.text.TextFormat; - import flash.ui.Keyboard; - +package fl.controls +{ + import fl.controls.BaseButton; + import fl.controls.ButtonLabelPlacement; + import fl.controls.TextInput; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + import fl.managers.IFocusManagerComponent; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.geom.Point; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFormat; + import flash.ui.Keyboard; + /** * Dispatched after the toggle button receives input from * a mouse device or from the spacebar. * * @eventType flash.events.MouseEvent.CLICK * * @includeExample examples/LabelButton.click.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="click", type="flash.events.MouseEvent")] + [Event(name="click", type="flash.events.MouseEvent")] /** * Dispatched after the label value changes. * * @eventType fl.events.ComponentEvent.LABEL_CHANGE * * @includeExample examples/LabelButton.labelChange.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="labelChange", type="fl.events.ComponentEvent")] + [Event(name="labelChange", type="fl.events.ComponentEvent")] /** * Name of the class to use as the skin for the background and border * when the button is not selected and is disabled. * * @default Button_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledSkin", type="Class")] + [Style(name="disabledSkin", type="Class")] /** * Name of the class to use as the skin for the background and border * when the button is not selected and the mouse is not over the component. * * @default Button_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * Name of the class to use as the skin for the background and border * when the button is not selected and the mouse button is down. * * @default Button_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downSkin", type="Class")] + [Style(name="downSkin", type="Class")] /** * Name of the class to use as the skin for the background and border * when the button is not selected and the mouse is over the component. * * @default Button_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="overSkin", type="Class")] + [Style(name="overSkin", type="Class")] /** * Name of the class to use as the skin for the background and border * when a toggle button is selected and disabled. * * @default Button_selectedDisabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDisabledSkin", type="Class")] + [Style(name="selectedDisabledSkin", type="Class")] /** * Name of the class to use as the skin for the background and border * when a toggle button is selected and the mouse is not over the component. * * @default Button_selectedUpSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedUpSkin", type="Class")] + [Style(name="selectedUpSkin", type="Class")] /** * Name of the class to use as the skin for the background and border * when a toggle button is selected and the mouse button is down. * * @default Button_selectedDownSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDownSkin", type="Class")] + [Style(name="selectedDownSkin", type="Class")] /** * Name of the class to use as the skin for the background and border * when a toggle button is selected and the mouse is over the component. * * @default Button_selectedOverSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedOverSkin", type="Class")] + [Style(name="selectedOverSkin", type="Class")] /** * The spacing between the text and the edges of the component, and the * spacing between the text and the icon, in pixels. * * @default 5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] + [Style(name="textPadding", type="Number", format="Length")] /** * @copy fl.controls.BaseButton#style:repeatDelay * * @default 500 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatDelay", type="Number", format="Time")] + [Style(name="repeatDelay", type="Number", format="Time")] /** * @copy fl.controls.BaseButton#style:repeatInterval * * @default 35 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatInterval", type="Number", format="Time")] + [Style(name="repeatInterval", type="Number", format="Time")] /** * Name of the class to use as the icon when a toggle button is not selected * and the mouse is not over the button. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="icon", type="Class")] + [Style(name="icon", type="Class")] /** * Name of the class to use as the icon when a toggle button is not selected and the mouse is not over the button. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upIcon", type="Class")] + [Style(name="upIcon", type="Class")] /** * Name of the class to use as the icon when the button is not selected and the mouse button is down. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downIcon", type="Class")] + [Style(name="downIcon", type="Class")] /** * Name of the class to use as the icon when the button is not selected and the mouse is over the component. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="overIcon", type="Class")] + [Style(name="overIcon", type="Class")] /** * Name of the class to use as the icon when the button is not disabled. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledIcon", type="Class")] + [Style(name="disabledIcon", type="Class")] /** * Name of the class to use as the icon when the button is selected and disabled. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDisabledIcon", type="Class")] + [Style(name="selectedDisabledIcon", type="Class")] /** * Name of the class to use as the icon when the button is selected and the mouse button is up. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedUpIcon", type="Class")] + [Style(name="selectedUpIcon", type="Class")] /** * Name of the class to use as the icon when the button is selected and the mouse button is down. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDownIcon", type="Class")] + [Style(name="selectedDownIcon", type="Class")] /** * Name of the class to use as the icon when the button is selected and the mouse is over the component. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedOverIcon", type="Class")] + [Style(name="selectedOverIcon", type="Class")] /** * Indicates whether embedded font outlines are used to render the text field. * If this value is true, Flash Player renders the text field * by using embedded font outlines. If this value is false, * Flash Player renders the text field by using device fonts. * *

    If you set the embedFonts property to true * for a text field, you must specify a font for that text by using the * font property of a TextFormat object that is applied to the text field. * If the specified font is not embedded in the SWF file, the text is not displayed.

    * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="embedFonts", type="Boolean")] - + [Style(name="embedFonts", type="Boolean")] + /** * The LabelButton class is an abstract class that extends the * BaseButton class by adding a label, an icon, and toggle functionality. * The LabelButton class is subclassed by the Button, CheckBox, RadioButton, and * CellRenderer classes. * *

    The LabelButton component is used as a simple button class that can be * combined with custom skin states that support ScrollBar buttons, NumericStepper * buttons, ColorPicker swatches, and so on.

    * * @includeExample examples/LabelButtonExample.as -noswf * @includeExample examples/IconWithToolTip.as * * @see fl.controls.BaseButton * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class LabelButton extends BaseButton implements IFocusManagerComponent - { + public class LabelButton extends BaseButton implements IFocusManagerComponent + { /** * A reference to the component's internal text field. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var textField : TextField; + public var textField : TextField; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _labelPlacement : String; + protected var _labelPlacement : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _toggle : Boolean; + protected var _toggle : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var icon : DisplayObject; + protected var icon : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var oldMouseState : String; + protected var oldMouseState : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _label : String; + protected var _label : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var mode : String; + protected var mode : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * Gets or sets the text label for the component. By default, the label * text appears centered on the button. * *

    Note: Setting this property triggers the labelChange * event object to be dispatched.

    * * @default "Label" * * @see #event:labelChange * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get label () : String; + public function get label () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set label (value:String) : void; + public function set label (value:String) : void; /** * Position of the label in relation to a specified icon. * *

    In ActionScript, you can use the following constants to set this property:

    * *
      *
    • ButtonLabelPlacement.RIGHT
    • *
    • ButtonLabelPlacement.LEFT
    • *
    • ButtonLabelPlacement.BOTTOM
    • *
    • ButtonLabelPlacement.TOP
    • *
    * * @default ButtonLabelPlacement.RIGHT * * @includeExample examples/LabelButton.labelPlacement.1.as -noswf * * @see ButtonLabelPlacement * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelPlacement () : String; + public function get labelPlacement () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelPlacement (value:String) : void; + public function set labelPlacement (value:String) : void; /** * Gets or sets a Boolean value that indicates whether a button * can be toggled. A value of true indicates that it * can; a value of false indicates that it cannot. * *

    If this value is true, clicking the button * toggles it between selected and unselected states. You can get * or set this state programmatically by using the selected * property.

    * *

    If this value is false, the button does not * stay pressed after the user releases it. In this case, its * selected property is always false.

    * *

    Note: When the toggle is set to false, * selected is forced to false because only * toggle buttons can be selected.

    * * @default false * * @includeExample examples/LabelButton.toggle.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get toggle () : Boolean; + public function get toggle () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set toggle (value:Boolean) : void; + public function set toggle (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether * a toggle button is toggled in the on or off position. * A value of true indicates that it is * toggled in the on position; a value of false indicates * that it is toggled in the off position. This property can be * set only if the toggle property is set to true. * *

    For a CheckBox component, this value indicates whether the box * displays a check mark. For a RadioButton component, this value * indicates whether the component is selected.

    * *

    The user can change this property by clicking the component, * but you can also set this property programmatically.

    * *

    If the toggle property is set to true, * changing this property also dispatches a change event.

    * * @default false * * @includeExample examples/LabelButton.toggle.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selected () : Boolean; + public function get selected () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selected (value:Boolean) : void; - + public function set selected (value:Boolean) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new LabelButton component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function LabelButton (); + public function LabelButton (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function toggleSelected (event:MouseEvent) : void; + protected function toggleSelected (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawIcon () : void; + protected function drawIcon () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawTextFormat () : void; + protected function drawTextFormat () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setEmbedFont (); + protected function setEmbedFont (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyUpHandler (event:KeyboardEvent) : void; + protected function keyUpHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; - } -} + protected function initializeAccessibility () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/List.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/List.as index fae002bc09..8f9b48fc45 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/List.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/List.as @@ -1,173 +1,173 @@ -package fl.controls -{ - import fl.data.DataProvider; - import fl.controls.listClasses.CellRenderer; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.listClasses.ListData; - import fl.controls.ScrollPolicy; - import fl.controls.SelectableList; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.DataChangeType; - import fl.events.DataChangeEvent; - import fl.events.ListEvent; - import fl.events.ScrollEvent; - import fl.managers.IFocusManagerComponent; - import flash.display.DisplayObject; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.ui.Keyboard; - import flash.utils.Dictionary; - import flash.geom.Rectangle; - +package fl.controls +{ + import fl.data.DataProvider; + import fl.controls.listClasses.CellRenderer; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.listClasses.ListData; + import fl.controls.ScrollPolicy; + import fl.controls.SelectableList; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.DataChangeType; + import fl.events.DataChangeEvent; + import fl.events.ListEvent; + import fl.events.ScrollEvent; + import fl.managers.IFocusManagerComponent; + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.ui.Keyboard; + import flash.utils.Dictionary; + import flash.geom.Rectangle; + /** * The List component displays list-based information and is ideally suited * for the display of arrays of information. * *

    The List component consists of items, rows, and a data provider, which are * described as follows:

    *
      *
    • Item: An ActionScript object that usually contains a descriptive label * property and a data property that stores the data associated with that item.
    • *
    • Row: A component that is used to display the item.
    • *
    • Data provider: A component that models the items that the List component displays.
    • *
    * *

    By default, the List component uses the CellRenderer class to supply the rows in * which list items are displayed. You can create these rows programmatically; this * is usually done by subclassing the CellRenderer class. The CellRenderer class * implements the ICellRenderer interface, which provides the set of properties and * methods that the List component uses to manipulate its rows and to send data and state information * to each row for display. This includes information about data sizing and selection.

    * *

    The List component provides methods that act on its data provider--for example, the * addItem() and removeItem() methods. You can use these and * other methods to manipulate the data of any array that exists in the same frame as * a List component and then broadcast the changes to multiple views. If a List component * is not provided with an external data provider, these methods automatically create an * instance of a data provider and expose it through the List.dataProvider * property. The List component renders each row by using a Sprite that implements the * ICellRenderer interface. To specify this renderer, use the List.cellRenderer * property. You can also build an Array instance or get one from a server and use it as a * data model for multiple lists, combo boxes, data grids, and so on.

    * * @includeExample examples/ListExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class List extends SelectableList implements IFocusManagerComponent - { + public class List extends SelectableList implements IFocusManagerComponent + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _rowHeight : Number; + protected var _rowHeight : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _cellRenderer : Object; + protected var _cellRenderer : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _labelField : String; + protected var _labelField : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _labelFunction : Function; + protected var _labelFunction : Function; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _iconField : String; + protected var _iconField : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _iconFunction : Function; + protected var _iconFunction : Function; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * Gets or sets the name of the field in the dataProvider object * to be displayed as the label for the TextInput field and drop-down list. * *

    By default, the component displays the label property * of each dataProvider item. If the dataProvider * items do not contain a label property, you can set the * labelField property to use a different property.

    * *

    Note: The labelField property is not used * if the labelFunction property is set to a callback function.

    * * @default "label" * * @see #labelFunction * * @includeExample examples/List.labelField.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelField () : String; + public function get labelField () : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelField (value:String) : void; + public function set labelField (value:String) : void; /** * Gets or sets the function to be used to obtain the label for the item. * *

    By default, the component displays the label property * for a dataProvider item. But some data sets may not have * a label field or may not have a field whose value * can be used as a label without modification. For example, a given data * set might store full names but maintain them in lastName and * firstName fields. In such a case, this property could be * used to set a callback function that concatenates the values of the * lastName and firstName fields into a full * name string to be displayed.

    * *

    Note: The labelField property is not used * if the labelFunction property is set to a callback function.

    * * @default null * * @includeExample examples/List.labelFunction.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelFunction () : Function; + public function get labelFunction () : Function; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelFunction (value:Function) : void; + public function set labelFunction (value:Function) : void; /** * Gets or sets the item field that provides the icon for the item. * *

    Note: The iconField is not used * if the iconFunction property is set to a callback function.

    * * @default "icon" * * @includeExample examples/List.iconField.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get iconField () : String; + public function get iconField () : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set iconField (value:String) : void; + public function set iconField (value:String) : void; /** * Gets or sets the function to be used to obtain the icon for the item. * *

    Note: The iconField is not used * if the iconFunction property is set to a callback function.

    * * @default null * * @includeExample examples/List.iconFunction.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get iconFunction () : Function; + public function get iconFunction () : Function; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set iconFunction (value:Function) : void; + public function set iconFunction (value:Function) : void; /** * Gets or sets the number of rows that are at least partially visible in the * list. * * @includeExample examples/SelectableList.rowCount.1.as -noswf * @includeExample examples/List.rowCount.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowCount () : uint; + public function get rowCount () : uint; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set rowCount (value:uint) : void; + public function set rowCount (value:uint) : void; /** * Gets or sets the height of each row in the list, in pixels. * * @default 20 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowHeight () : Number; + public function get rowHeight () : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set rowHeight (value:Number) : void; - + public function set rowHeight (value:Number) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new List component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function List (); + public function List (); /** * @copy fl.controls.SelectableList#scrollToIndex() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function scrollToIndex (newCaretIndex:int) : void; + public function scrollToIndex (newCaretIndex:int) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function calculateAvailableHeight () : Number; + protected function calculateAvailableHeight () : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setHorizontalScrollPosition (value:Number, fireEvent:Boolean = false) : void; + protected function setHorizontalScrollPosition (value:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawList () : void; + protected function drawList () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * Moves the selection in a horizontal direction in response * to the user selecting items using the left-arrow or right-arrow * keys and modifiers such as the Shift and Ctrl keys. * *

    Not implemented in List because the default list * is single column and therefore doesn't scroll horizontally.

    * * @param code The key that was pressed (e.g. Keyboard.LEFT) * * @param shiftKey true if the shift key was held down when * the keyboard key was pressed. * * @param ctrlKey true if the ctrl key was held down when * the keyboard key was pressed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function moveSelectionHorizontally (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function moveSelectionHorizontally (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * Moves the selection in a vertical direction in response * to the user selecting items using the up-arrow or down-arrow * Keys and modifiers such as the Shift and Ctrl keys. * * @param code The key that was pressed (e.g. Keyboard.DOWN) * * @param shiftKey true if the shift key was held down when * the keyboard key was pressed. * * @param ctrlKey true if the ctrl key was held down when * the keyboard key was pressed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function moveSelectionVertically (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function moveSelectionVertically (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function doKeySelection (newCaretIndex:int, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function doKeySelection (newCaretIndex:int, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * Retrieves the string that the renderer displays for the given data object * based on the labelField and labelFunction properties. * *

    Note: The labelField is not used * if the labelFunction property is set to a callback function.

    * * @param item The object to be rendered. * * @return The string to be displayed based on the data. * * @internal var label:String = myList.itemToLabel(data); * * @includeExample examples/List.itemToLabel.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function itemToLabel (item:Object) : String; + public function itemToLabel (item:Object) : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; - } -} + protected function initializeAccessibility () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/NumericStepper.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/NumericStepper.as index ec36b2483c..ff945ff9ac 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/NumericStepper.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/NumericStepper.as @@ -1,266 +1,266 @@ -package fl.controls -{ - import fl.controls.BaseButton; - import fl.controls.TextInput; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - import fl.managers.IFocusManagerComponent; - import flash.display.DisplayObject; - import flash.events.Event; - import flash.events.FocusEvent; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.events.TextEvent; - import flash.ui.Keyboard; - +package fl.controls +{ + import fl.controls.BaseButton; + import fl.controls.TextInput; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + import fl.managers.IFocusManagerComponent; + import flash.display.DisplayObject; + import flash.events.Event; + import flash.events.FocusEvent; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.events.TextEvent; + import flash.ui.Keyboard; + /** * The class that provides the skin for the down arrow when it is disabled. * * @default NumericStepperDownArrow_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowDisabledSkin", type="Class")] + [Style(name="downArrowDisabledSkin", type="Class")] /** * The class that provides the skin for the down arrow when it is in a down state. * * @default NumericStepperDownArrow_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowDownSkin", type="Class")] + [Style(name="downArrowDownSkin", type="Class")] /** * The class that provides the skin for the down arrow when the mouse is over the component. * * @default NumericStepperDownArrow_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowOverSkin", type="Class")] + [Style(name="downArrowOverSkin", type="Class")] /** * The class that provides the skin for the down arrow when it is in its default state. * * @default NumericStepperDownArrow_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowUpSkin", type="Class")] + [Style(name="downArrowUpSkin", type="Class")] /** * The class that provides the skin for the up arrow when it is disabled. * * @default NumericStepperUpArrow_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowDisabledSkin", type="Class")] + [Style(name="upArrowDisabledSkin", type="Class")] /** * The class that provides the skin for the up arrow when it is in the down state. * * @default NumericStepperUpArrow_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowDownSkin", type="Class")] + [Style(name="upArrowDownSkin", type="Class")] /** * The class that provides the skin for the down arrow during mouse over. * * @default NumericStepperUpArrow_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowOverSkin", type="Class")] + [Style(name="upArrowOverSkin", type="Class")] /** * The class that provides the skin for the up arrow when it is in the up state. * * @default NumericStepperUpArrow_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowUpSkin", type="Class")] + [Style(name="upArrowUpSkin", type="Class")] /** * The class that provides the skin for the text input box. * * @default NumericStepper_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="TextInput_upskin", type="Class")] + [Style(name="TextInput_upskin", type="Class")] /** * The skin used for the up arrow when it is in an up state. * * @default NumericStepper_disabledSkin * * @internal [kenos] Is this description correct? Most of the skins are provides by classes and this looks * more like some of the width or height specifiers. The style name also doesn't seem to * match the description. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="TextInput_disabledSkin", type="Number", format="Length")] + [Style(name="TextInput_disabledSkin", type="Number", format="Length")] /** * @copy fl.controls.BaseButton#style:repeatDelay * * @default 500 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatDelay", type="Number", format="Time")] + [Style(name="repeatDelay", type="Number", format="Time")] /** * @copy fl.controls.BaseButton#style:repeatInterval * * @default 35 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatInterval", type="Number", format="Time")] + [Style(name="repeatInterval", type="Number", format="Time")] /** * @copy fl.controls.LabelButton#style:embedFonts * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="embedFonts", type="Boolean")] + [Style(name="embedFonts", type="Boolean")] /** * Dispatched when the user changes the value of the NumericStepper component. * *

    Note: This event is not dispatched if ActionScript * is used to change the value.

    * * @eventType flash.events.Event.CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change", type="flash.events.Event")] - + [Event(name="change", type="flash.events.Event")] + /** * The NumericStepper component displays an ordered set of numbers from which * the user can make a selection. This component includes a single-line field * for text input and a pair of arrow buttons that can be used to step through * the set of values. The Up and Down arrow keys can also be used to view the * set of values. The NumericStepper component dispatches a change * event after there is a change in its current value. This component also contains * the value property; you can use this property to obtain the current * value of the component. * * @includeExample examples/NumericStepperExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class NumericStepper extends UIComponent implements IFocusManagerComponent - { + public class NumericStepper extends UIComponent implements IFocusManagerComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var inputField : TextInput; + protected var inputField : TextInput; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var upArrow : BaseButton; + protected var upArrow : BaseButton; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var downArrow : BaseButton; + protected var downArrow : BaseButton; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _maximum : Number; + protected var _maximum : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _minimum : Number; + protected var _minimum : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _value : Number; + protected var _value : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _stepSize : Number; + protected var _stepSize : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _precision : Number; + protected var _precision : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected static const DOWN_ARROW_STYLES : Object; + protected static const DOWN_ARROW_STYLES : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected const UP_ARROW_STYLES : Object; + protected const UP_ARROW_STYLES : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected const TEXT_INPUT_STYLES : Object; - + protected const TEXT_INPUT_STYLES : Object; + /** * @copy fl.core.UIComponent#enabled * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function get enabled () : Boolean; + function get enabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets the maximum value in the sequence of numeric values. * * @default 10 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maximum () : Number; + public function get maximum () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maximum (value:Number) : void; + public function set maximum (value:Number) : void; /** * Gets or sets the minimum number in the sequence of numeric values. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get minimum () : Number; + public function get minimum () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set minimum (value:Number) : void; + public function set minimum (value:Number) : void; /** * Gets the next value in the sequence of values. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get nextValue () : Number; + public function get nextValue () : Number; /** * Gets the previous value in the sequence of values. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get previousValue () : Number; + public function get previousValue () : Number; /** * Gets or sets a nonzero number that describes the unit of change between * values. The value property is a multiple of this number * less the minimum. The NumericStepper component rounds the resulting value to the * nearest step size. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get stepSize () : Number; + public function get stepSize () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set stepSize (value:Number) : void; + public function set stepSize (value:Number) : void; /** * Gets or sets the current value of the NumericStepper component. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get value () : Number; + public function get value () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set value (value:Number) : void; + public function set value (value:Number) : void; /** * Gets a reference to the TextInput component that the NumericStepper * component contains. Use this property to access and manipulate the * underlying TextInput component. For example, you can use this * property to change the current selection in the text box or to * restrict the characters that the text box accepts. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get textField () : TextInput; + public function get textField () : TextInput; /** * @copy fl.controls.TextArea#imeMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get imeMode () : String; + public function get imeMode () : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set imeMode (value:String) : void; - + public function set imeMode (value:String) : void; + /** * Creates a new NumericStepper component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function NumericStepper (); + public function NumericStepper (); /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setValue (value:Number, fireEvent:Boolean = true) : void; + protected function setValue (value:Number, fireEvent:Boolean = true) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function stepperPressHandler (event:ComponentEvent) : void; + protected function stepperPressHandler (event:ComponentEvent) : void; /** * @copy fl.core.UIComponent#drawFocus() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawFocus (event:Boolean) : void; + public function drawFocus (event:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusOutHandler (event:FocusEvent) : void; + protected function focusOutHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onTextChange (event:Event) : void; + protected function onTextChange (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function passEvent (event:Event) : void; + protected function passEvent (event:Event) : void; /** * Sets focus to the component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setFocus () : void; + public function setFocus () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function isOurFocus (target:DisplayObject) : Boolean; + protected function isOurFocus (target:DisplayObject) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setStyles () : void; + protected function setStyles () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function inRange (num:Number) : Boolean; + protected function inRange (num:Number) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function inStep (num:Number) : Boolean; + protected function inStep (num:Number) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getValidValue (num:Number) : Number; + protected function getValidValue (num:Number) : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getPrecision () : Number; - } -} + protected function getPrecision () : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBar.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBar.as index 737fffd46c..2b7e9b3fc7 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBar.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBar.as @@ -1,239 +1,239 @@ -package fl.controls -{ - import fl.controls.progressBarClasses.IndeterminateBar; - import fl.controls.ProgressBarDirection; - import fl.controls.ProgressBarMode; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import flash.display.DisplayObject; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.EventDispatcher; - import flash.events.ProgressEvent; - +package fl.controls +{ + import fl.controls.progressBarClasses.IndeterminateBar; + import fl.controls.ProgressBarDirection; + import fl.controls.ProgressBarMode; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.EventDispatcher; + import flash.events.ProgressEvent; + /** * Dispatched when the load operation completes. * * @eventType flash.events.Event.COMPLETE * * @includeExample examples/ProgressBar.complete.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("complete", type="flash.events.Event")] + [Event("complete", type="flash.events.Event")] /** * Dispatched as content loads in event mode or polled mode. * * @eventType flash.events.ProgressEvent.PROGRESS * * @includeExample examples/ProgressBar.complete.1.as -noswf * * @see ProgressBarMode#EVENT ProgressBarMode.EVENT * @see ProgressBarMode#POLLED ProgressBarMode.POLLED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("progress", type="flash.events.ProgressEvent")] + [Event("progress", type="flash.events.ProgressEvent")] /** * Name of the class to use as the default icon. Setting any other icon * style overrides this setting. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="icon", type="Class")] + [Style(name="icon", type="Class")] /** * Name of the class to use as the progress indicator track. * * @default ProgressBar_trackSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackSkin", type="Class")] + [Style(name="trackSkin", type="Class")] /** * Name of the class to use as the determinate progress bar. * * @default ProgressBar_barSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="barSkin", type="Class")] + [Style(name="barSkin", type="Class")] /** * Name of the class to use as the indeterminate progress bar. This is passed to the * indeterminate bar renderer, which is specified by the indeterminateBar * style. * * @default ProgressBar_indeterminateSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="indeterminateSkin", type="Class")] + [Style(name="indeterminateSkin", type="Class")] /** * The class to use as a renderer for the indeterminate bar animation. * This is an advanced style. * * @default fl.controls.progressBarClasses.IndeterminateBar * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="indeterminateBar", type="Class")] + [Style(name="indeterminateBar", type="Class")] /** * The padding that separates the progress bar indicator from the track, in pixels. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="barPadding", type="Number", format="Length")] - + [Style(name="barPadding", type="Number", format="Length")] + /** * The ProgressBar component displays the progress of content that is * being loaded. The ProgressBar is typically used to display the status of * images, as well as portions of applications, while they are loading. * The loading process can be determinate or indeterminate. A determinate * progress bar is a linear representation of the progress of a task over * time and is used when the amount of content to load is known. An indeterminate * progress bar has a striped fill and a loading source of unknown size. * * @includeExample examples/ProgressBarExample.as * * @see ProgressBarDirection * @see ProgressBarMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ProgressBar extends UIComponent - { + public class ProgressBar extends UIComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var track : DisplayObject; + protected var track : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var determinateBar : DisplayObject; + protected var determinateBar : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var indeterminateBar : UIComponent; + protected var indeterminateBar : UIComponent; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _direction : String; + protected var _direction : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _indeterminate : Boolean; + protected var _indeterminate : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _mode : String; + protected var _mode : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _minimum : Number; + protected var _minimum : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _maximum : Number; + protected var _maximum : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _value : Number; + protected var _value : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _source : Object; + protected var _source : Object; /** * @private (protected) */ - protected var _loaded : Number; + protected var _loaded : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * Indicates the fill direction for the progress bar. A value of * ProgressBarDirection.RIGHT indicates that the progress * bar is filled from left to right. A value of ProgressBarDirection.LEFT * indicates that the progress bar is filled from right to left. * * @default ProgressBarDirection.RIGHT * * @includeExample examples/ProgressBar.direction.1.as -noswf * * @see ProgressBarDirection * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get direction () : String; + public function get direction () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set direction (value:String) : void; + public function set direction (value:String) : void; /** * Gets or sets a value that indicates the type of fill that the progress * bar uses and whether the loading source is known or unknown. A value of * true indicates that the progress bar has a striped fill * and a loading source of unknown size. A value of false * indicates that the progress bar has a solid fill and a loading source * of known size. * *

    This property can only be set when the progress bar mode * is set to ProgressBarMode.MANUAL.

    * * @default true * * @see #mode * @see ProgressBarMode * @see fl.controls.progressBarClasses.IndeterminateBar IndeterminateBar * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get indeterminate () : Boolean; + public function get indeterminate () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set indeterminate (value:Boolean) : void; + public function set indeterminate (value:Boolean) : void; /** * Gets or sets the minimum value for the progress bar when the * ProgressBar.mode property is set to ProgressBarMode.MANUAL. * * @default 0 * * @see #maximum * @see #percentComplete * @see #value * @see ProgressBarMode#MANUAL * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get minimum () : Number; + public function get minimum () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set minimum (value:Number) : void; + public function set minimum (value:Number) : void; /** * Gets or sets the maximum value for the progress bar when the * ProgressBar.mode property is set to ProgressBarMode.MANUAL. * * @default 0 * * @see #minimum * @see #percentComplete * @see #value * @see ProgressBarMode#MANUAL * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maximum () : Number; + public function get maximum () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maximum (value:Number) : void; + public function set maximum (value:Number) : void; /** * Gets or sets a value that indicates the amount of progress that has * been made in the load operation. This value is a number between the * minimum and maximum values. * * @default 0 * * @see #maximum * @see #minimum * @see #percentComplete * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get value () : Number; + public function get value () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set value (value:Number) : void; + public function set value (value:Number) : void; /** * @private (internal) */ - public function set sourceName (name:String) : void; + public function set sourceName (name:String) : void; /** * Gets or sets a reference to the content that is being loaded and for * which the ProgressBar is measuring the progress of the load operation. * A typical usage of this property is to set it to a UILoader component. * *

    Use this property only in event mode and polled mode.

    * * @default null * * @includeExample examples/ProgressBar.source.1.as -noswf * @includeExample examples/ProgressBar.source.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get source () : Object; + public function get source () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set source (value:Object) : void; + public function set source (value:Object) : void; /** * Gets a number between 0 and 100 that indicates the percentage * of the content has already loaded. * *

    To change the percentage value, use the setProgress() method.

    * * @default 0 * * @includeExample examples/ProgressBar.percentComplete.1.as -noswf * @includeExample examples/ProgressBar.percentComplete.2.as -noswf * * @see #maximum * @see #minimum * @see #setProgress() * @see #value * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get percentComplete () : Number; + public function get percentComplete () : Number; /** * Gets or sets the method to be used to update the progress bar. * *

    The following values are valid for this property:

    *
      *
    • ProgressBarMode.EVENT
    • *
    • ProgressBarMode.POLLED
    • *
    • ProgressBarMode.MANUAL
    • *
    * *

    Event mode and polled mode are the most common modes. In event mode, * the source property specifies loading content that generates * progress and complete events; you should use * a UILoader object in this mode. In polled mode, the source * property specifies loading content, such as a custom class, that exposes * bytesLoaded and bytesTotal properties. Any object * that exposes these properties can be used as a source in polled mode.

    * *

    You can also use the ProgressBar component in manual mode by manually * setting the maximum and minimum properties and * making calls to the ProgressBar.setProgress() method.

    * * @default ProgressBarMode.EVENT * * @see ProgressBarMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get mode () : String; + public function get mode () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set mode (value:String) : void; - + public function set mode (value:String) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new ProgressBar component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ProgressBar (); + public function ProgressBar (); /** * Sets the state of the bar to reflect the amount of progress made when * using manual mode. The value argument is assigned to the * value property and the maximum argument is * assigned to the maximum property. The minimum * property is not altered. * * @param value A value describing the progress that has been made. * * @param maximum The maximum progress value of the progress bar. * * @see #maximum * @see #value * @see ProgressBarMode#MANUAL ProgressBarMode.manual * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setProgress (value:Number, maximum:Number) : void; + public function setProgress (value:Number, maximum:Number) : void; /** * Resets the progress bar for a new load operation. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function reset () : void; + public function reset () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function _setProgress (value:Number, maximum:Number, fireEvent:Boolean = false) : void; + protected function _setProgress (value:Number, maximum:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setIndeterminate (value:Boolean) : void; + protected function setIndeterminate (value:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function resetProgress () : void; + protected function resetProgress () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setupSourceEvents () : void; + protected function setupSourceEvents () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function cleanupSourceEvents () : void; + protected function cleanupSourceEvents () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function pollSource (event:Event) : void; + protected function pollSource (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleProgress (event:ProgressEvent) : void; + protected function handleProgress (event:ProgressEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleComplete (event:Event) : void; + protected function handleComplete (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawTrack () : void; + protected function drawTrack () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBars () : void; + protected function drawBars () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawDeterminateBar () : void; + protected function drawDeterminateBar () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; - } -} + protected function configUI () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBarDirection.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBarDirection.as index 272063bfc1..de370f4c06 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBarDirection.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBarDirection.as @@ -1,18 +1,18 @@ -package fl.controls -{ +package fl.controls +{ /** * The ProgressBarDirection class defines the values for the direction * property of the ProgressBar class. * * @see ProgressBar#direction ProgressBar.direction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ProgressBarDirection - { + public class ProgressBarDirection + { /** * Fill the progress bar from left to right. * * @see ProgressBar#direction ProgressBar.direction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const RIGHT : String = "right"; + public static const RIGHT : String = "right"; /** * Fill the progress bar from right to left. * * @see ProgressBar#direction ProgressBar.direction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const LEFT : String = "left"; - - } -} + public static const LEFT : String = "left"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBarMode.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBarMode.as index 43d844efba..4050f6a2aa 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBarMode.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ProgressBarMode.as @@ -1,22 +1,22 @@ -package fl.controls -{ +package fl.controls +{ /** * The ProgressBarMode class defines the values for the mode * property of the ProgressBar class. * * @see ProgressBar#mode ProgressBar.mode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ProgressBarMode - { + public class ProgressBarMode + { /** * Manually update the status of the ProgressBar component. In this mode, you specify the * minimum and maximum properties and use the * setProgress() method to specify the status. * * @includeExample examples/ProgressBar.percentComplete.1.as -noswf * * @see ProgressBar#maximum ProgressBar.maximum * @see ProgressBar#minimum ProgressBar.minimum * @see ProgressBar#setProgress() ProgressBar.setProgress() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const MANUAL : String = "manual"; + public static const MANUAL : String = "manual"; /** * The component specified by the source property must dispatch * progress and complete * events. The ProgressBar uses these events to update its status. * * @includeExample examples/ProgressBarMode.EVENT.1.as -noswf * * @see fl.containers.ScrollPane#event:complete ScrollPane complete event * @see fl.containers.ScrollPane#event:progress ScrollPane progress event * @see fl.containers.UILoader#event:complete UILoader complete event * @see fl.containers.UILoader#event:progress UILoader progress event * @see flash.display.LoaderInfo#event:complete LoaderInfo complete event * @see flash.display.LoaderInfo#event:progress LoaderInfo progress event * @see flash.media.Sound#event:complete Sound complete event * @see flash.media.Sound#event:progress Sound progress event * @see flash.net.FileReference#event:complete FileReference complete event * @see flash.net.FileReference#event:progress FileReference progress event * @see flash.net.URLLoader#event:complete URLLoader complete event * @see flash.net.URLLoader#event:progress URLLoader progress event * @see flash.net.URLStream#event:complete URLStream complete event * @see flash.net.URLStream#event:progress URLStream progress event * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const EVENT : String = "event"; + public static const EVENT : String = "event"; /** * Progress is updated by polling the source. The source * property must specify an object that exposes the bytesLoaded * and bytesTotal properties. * * @includeExample examples/ProgressBarMode.POLLED.1.as -noswf * * @see fl.containers.ScrollPane#bytesLoaded ScrollPane.bytesLoaded * @see fl.containers.ScrollPane#bytesTotal ScrollPane.bytesTotal * @see fl.containers.UILoader#bytesLoaded UILoader.bytesLoaded * @see fl.containers.UILoader#bytesTotal UILoader.bytesTotal * @see flash.media.Sound#bytesLoaded Sound.bytesLoaded * @see flash.media.Sound#bytesTotal Sound.bytesTotal * @see flash.net.NetStream#bytesLoaded NetStream.bytesLoaded * @see flash.net.NetStream#bytesTotal NetStream.bytesTotal * @see flash.net.URLLoader#bytesLoaded URLLoader.bytesLoaded * @see flash.net.URLLoader#bytesTotal URLLoader.bytesTotal * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const POLLED : String = "polled"; - - } -} + public static const POLLED : String = "polled"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/RadioButton.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/RadioButton.as index cad3b91612..9f8c46d74c 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/RadioButton.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/RadioButton.as @@ -1,204 +1,204 @@ -package fl.controls -{ - import fl.controls.ButtonLabelPlacement; - import fl.controls.LabelButton; - import fl.controls.RadioButtonGroup; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.managers.IFocusManager; - import fl.managers.IFocusManagerGroup; - import flash.display.DisplayObject; - import flash.display.Graphics; - import flash.display.Shape; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.ui.Keyboard; - +package fl.controls +{ + import fl.controls.ButtonLabelPlacement; + import fl.controls.LabelButton; + import fl.controls.RadioButtonGroup; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.managers.IFocusManager; + import fl.managers.IFocusManagerGroup; + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.Shape; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.ui.Keyboard; + /** * Dispatched when the radio button instance's selected property changes. * * @includeExample examples/RadioButton.change.1.as -noswf * * @eventType flash.events.Event.CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change" , type="flash.events.Event")] + [Event(name="change" , type="flash.events.Event")] /** * Dispatched when the user clicks the radio button with the mouse or spacebar. * * @includeExample examples/RadioButton.change.1.as -noswf * * @eventType flash.events.MouseEvent.CLICK * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="click" , type="flash.events.MouseEvent")] + [Event(name="click" , type="flash.events.MouseEvent")] /** * @copy fl.controls.LabelButton#style:icon * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="icon", type="Class")] + [Style(name="icon", type="Class")] /** * @copy fl.controls.LabelButton#style:upIcon * * @default RadioButton_upIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upIcon", type="Class")] + [Style(name="upIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:downIcon * * @default RadioButton_downIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downIcon", type="Class")] + [Style(name="downIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:overIcon * * @default RadioButton_overIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="overIcon", type="Class")] + [Style(name="overIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:disabledIcon * * @default RadioButton_disabledIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledIcon", type="Class")] + [Style(name="disabledIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDisabledIcon * * @default RadioButton_selectedDisabledIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDisabledIcon", type="Class")] + [Style(name="selectedDisabledIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedUpIcon * * @default RadioButton_selectedUpIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedUpIcon", type="Class")] + [Style(name="selectedUpIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDownIcon * * @default RadioButton_selectedDownIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDownIcon", type="Class")] + [Style(name="selectedDownIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedOverIcon * * @default RadioButton_selectedOverIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedOverIcon", type="Class")] + [Style(name="selectedOverIcon", type="Class")] /** * @copy fl.controls.LabelButton#style:textPadding * * @default 5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] - + [Style(name="textPadding", type="Number", format="Length")] + /** * The RadioButton component lets you force a user to make a single * selection from a set of choices. This component must be used in a * group of at least two RadioButton instances. Only one member of * the group can be selected at any given time. Selecting one radio * button in a group deselects the currently selected radio button * in the group. You set the groupName parameter to indicate which * group a radio button belongs to. When the user clicks or tabs into a RadioButton * component group, only the selected radio button receives focus. * *

    A radio button can be enabled or disabled. A disabled radio button does not receive mouse or * keyboard input.

    * * @see RadioButtonGroup * * @includeExample examples/RadioButtonExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class RadioButton extends LabelButton implements IFocusManagerGroup - { + public class RadioButton extends LabelButton implements IFocusManagerGroup + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _value : Object; + protected var _value : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * The RadioButtonGroup object to which this RadioButton component instance belongs. */ - protected var _group : RadioButtonGroup; + protected var _group : RadioButtonGroup; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var defaultGroupName : String; + protected var defaultGroupName : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * A radio button is a toggle button; its toggle property is set to * true in the constructor and cannot be changed. * * @throws Error This property cannot be set on the RadioButton. * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get toggle () : Boolean; + public function get toggle () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set toggle (value:Boolean) : void; + public function set toggle (value:Boolean) : void; /** * A radio button never auto-repeats by definition, so the autoRepeat property is set to * false in the constructor and cannot be changed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get autoRepeat () : Boolean; + public function get autoRepeat () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set autoRepeat (value:Boolean) : void; + public function set autoRepeat (value:Boolean) : void; /** * Indicates whether a radio button is currently selected (true) or deselected (false). * You can only set this value to true; setting it to false has no effect. To * achieve the desired effect, select a different radio button in the same radio button group. * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selected () : Boolean; + public function get selected () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selected (value:Boolean) : void; + public function set selected (value:Boolean) : void; /** * The group name for a radio button instance or group. You can use this property to get * or set a group name for a radio button instance or for a radio button group. * * @default "RadioButtonGroup" * * @includeExample examples/RadioButton.groupName.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get groupName () : String; + public function get groupName () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set groupName (group:String) : void; + public function set groupName (group:String) : void; /** * The RadioButtonGroup object to which this RadioButton belongs. * * @includeExample examples/RadioButton.group.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get group () : RadioButtonGroup; + public function get group () : RadioButtonGroup; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set group (name:RadioButtonGroup) : void; + public function set group (name:RadioButtonGroup) : void; /** * A user-defined value that is associated with a radio button. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get value () : Object; + public function get value () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set value (val:Object) : void; - + public function set value (val:Object) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new RadioButton component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function RadioButton (); + public function RadioButton (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * Shows or hides the focus indicator around this component instance. * * @param focused Show or hide the focus indicator. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawFocus (focused:Boolean) : void; + public function drawFocus (focused:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleChange (event:Event) : void; + protected function handleChange (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleClick (event:MouseEvent) : void; + protected function handleClick (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBackground () : void; + protected function drawBackground () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; + protected function initializeAccessibility () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyUpHandler (event:KeyboardEvent) : void; + protected function keyUpHandler (event:KeyboardEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function setPrev (moveSelection:Boolean = true) : void; + private function setPrev (moveSelection:Boolean = true) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function setNext (moveSelection:Boolean = true) : void; + private function setNext (moveSelection:Boolean = true) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function setThis () : void; - } -} + private function setThis () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/RadioButtonGroup.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/RadioButtonGroup.as index 0f1268136d..4dd9b8a47d 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/RadioButtonGroup.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/RadioButtonGroup.as @@ -1,101 +1,101 @@ -package fl.controls -{ - import fl.controls.RadioButton; - import flash.utils.Dictionary; - import flash.events.EventDispatcher; - import flash.events.Event; - +package fl.controls +{ + import fl.controls.RadioButton; + import flash.utils.Dictionary; + import flash.events.EventDispatcher; + import flash.events.Event; + /** * Dispatched when the selected RadioButton instance in a group changes. * * @includeExample examples/RadioButtonGroup.change.1.as -noswf * @eventType flash.events.Event.CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change", type="flash.events.Event")] + [Event(name="change", type="flash.events.Event")] /** * Dispatched when a RadioButton instance is clicked. * * @eventType flash.events.MouseEvent.CLICK * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="click", type="flash.events.MouseEvent")] - + [Event(name="click", type="flash.events.MouseEvent")] + /** * The RadioButtonGroup class defines a group of RadioButton components * to act as a single component. When one radio button is selected, no other * radio buttons from the same group can be selected. * * @see RadioButton * @see RadioButton#group RadioButton.group * * @includeExample examples/RadioButtonGroupExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class RadioButtonGroup extends EventDispatcher - { + public class RadioButtonGroup extends EventDispatcher + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var groups : Object; + private static var groups : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var groupCount : uint; + private static var groupCount : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _name : String; + protected var _name : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var radioButtons : Array; + protected var radioButtons : Array; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _selection : RadioButton; - + protected var _selection : RadioButton; + /** * Gets the instance name of the radio button. * * @default "RadioButtonGroup" * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get name () : String; + public function get name () : String; /** * Gets or sets a reference to the radio button that is currently selected * from the radio button group. * * @includeExample examples/RadioButtonGroup.selection.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selection () : RadioButton; + public function get selection () : RadioButton; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selection (value:RadioButton) : void; + public function set selection (value:RadioButton) : void; /** * Gets or sets the selected radio button's value property. * If no radio button is currently selected, this property is null. * * @includeExample examples/RadioButtonGroup.selectedData.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedData () : Object; + public function get selectedData () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectedData (value:Object) : void; + public function set selectedData (value:Object) : void; /** * Gets the number of radio buttons in this radio button group. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get numRadioButtons () : int; - + public function get numRadioButtons () : int; + /** * Retrieves a reference to the specified radio button group. * * @param name The name of the group for which to retrieve a reference. * * @return A reference to the specified RadioButtonGroup. * * @includeExample examples/RadioButtonGroup.getGroup.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getGroup (name:String) : RadioButtonGroup; + public static function getGroup (name:String) : RadioButtonGroup; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function registerGroup (group:RadioButtonGroup) : void; + private static function registerGroup (group:RadioButtonGroup) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function cleanUpGroups () : void; + private static function cleanUpGroups () : void; /** * Creates a new RadioButtonGroup instance. * This is usually done automatically when a radio button is instantiated. * * @param name The name of the radio button group. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function RadioButtonGroup (name:String); + public function RadioButtonGroup (name:String); /** * Adds a radio button to the internal radio button array for use with * radio button group indexing, which allows for the selection of a single radio button * in a group of radio buttons. This method is used automatically by radio buttons, * but can also be manually used to explicitly add a radio button to a group. * * @param radioButton The RadioButton instance to be added to the current radio button group. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addRadioButton (radioButton:RadioButton) : void; + public function addRadioButton (radioButton:RadioButton) : void; /** * Clears the RadioButton instance from the internal list of radio buttons. * * @param radioButton The RadioButton instance to remove. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeRadioButton (radioButton:RadioButton) : void; + public function removeRadioButton (radioButton:RadioButton) : void; /** * Returns the index of the specified RadioButton instance. * * @param radioButton The RadioButton instance to locate in the current RadioButtonGroup. * * @return The index of the specified RadioButton component, or -1 if the specified RadioButton was not found. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getRadioButtonIndex (radioButton:RadioButton) : int; + public function getRadioButtonIndex (radioButton:RadioButton) : int; /** * Retrieves the RadioButton component at the specified index location. * * @param index The index of the RadioButton component in the RadioButtonGroup component, * where the index of the first component is 0. * * @return The specified RadioButton component. * * @throws RangeError The specified index is less than 0 or greater than or equal to the length of the data provider. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getRadioButtonAt (index:int) : RadioButton; - } -} + public function getRadioButtonAt (index:int) : RadioButton; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollBar.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollBar.as index 7b2b4da291..8ac43e773f 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollBar.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollBar.as @@ -1,304 +1,304 @@ -package fl.controls -{ - import fl.controls.BaseButton; - import fl.controls.LabelButton; - import fl.controls.ScrollBarDirection; - import fl.core.UIComponent; - import fl.core.InvalidationType; - import fl.events.ComponentEvent; - import fl.events.ScrollEvent; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.MouseEvent; - import flash.events.TimerEvent; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.utils.Timer; - import fl.controls.TextInput; - +package fl.controls +{ + import fl.controls.BaseButton; + import fl.controls.LabelButton; + import fl.controls.ScrollBarDirection; + import fl.core.UIComponent; + import fl.core.InvalidationType; + import fl.events.ComponentEvent; + import fl.events.ScrollEvent; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.MouseEvent; + import flash.events.TimerEvent; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.utils.Timer; + import fl.controls.TextInput; + /** * Dispatched when the ScrollBar instance's scrollPosition property changes. * * @eventType fl.events.ScrollEvent.SCROLL * * @see #scrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="scroll", type="fl.events.ScrollEvent"))] + [Event(name="scroll", type="fl.events.ScrollEvent"))] /** * Name of the class to use as the skin for the down arrow button of the scroll bar * when it is disabled. If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height (for horizontal scroll bars) * or width (for vertical scroll bars) as the track. * * @default ScrollArrowDown_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowDisabledSkin", type="Class")] + [Style(name="downArrowDisabledSkin", type="Class")] /** * Name of the class to use as the skin for the down arrow button of the scroll bar * when you click the arrow button. If you change the skin, either graphically or * programmatically, you should ensure that the new skin is the same height (for * horizontal scroll bars) or width (for vertical scroll bars) as the track. * * @default ScrollArrowDown_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowDownSkin", type="Class")] + [Style(name="downArrowDownSkin", type="Class")] /** * Name of the class to use as the skin for the down arrow button of the scroll bar * when the mouse pointer is over the arrow button. If you change the skin, either * graphically or programmatically, you should ensure that the new skin is the same * height (for horizontal scroll bars) or width (for vertical scroll bars) as the track. * * @default ScrollArrowDown_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowOverSkin", type="Class")] + [Style(name="downArrowOverSkin", type="Class")] /** * Name of the class to use as the skin for the down arrow button of the scroll bar. * If you change the skin, either graphically or programmatically, you should ensure * that the new skin is the same height (for horizontal scroll bars) or width (for * vertical scroll bars) as the track. * * @default ScrollArrowDown_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downArrowUpSkin", type="Class")] + [Style(name="downArrowUpSkin", type="Class")] /** * The skin that is used to indicate the disabled state of the thumb. * * @default ScrollThumb_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbDisabledSkin", type="Class")] + [Style(name="thumbDisabledSkin", type="Class")] /** * Name of the class to use as the skin for the thumb of the scroll bar when you * click the thumb. * * @default ScrollThumb_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbDownSkin", type="Class")] + [Style(name="thumbDownSkin", type="Class")] /** * Name of the class to use as the skin for the thumb of the scroll bar when the * mouse pointer is over the thumb. * * @default ScrollThumb_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbOverSkin", type="Class")] + [Style(name="thumbOverSkin", type="Class")] /** * Name of the class to use as the skin used for the thumb of the scroll * bar. * * @default ScrollThumb_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbUpSkin", type="Class")] + [Style(name="thumbUpSkin", type="Class")] /** * The skin that is used to indicate a disabled track. * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackDisabledSkin", type="Class")] + [Style(name="trackDisabledSkin", type="Class")] /** * The skin that is used to indicate the down state of a disabled skin. * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackDownSkin", type="Class")] + [Style(name="trackDownSkin", type="Class")] /** * The skin that is used to indicate the mouseover state for the scroll track. * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackOverSkin", type="Class")] + [Style(name="trackOverSkin", type="Class")] /** * The skin used to indicate the mouse up state for the scroll track. * * @default ScrollTrack_Skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="trackUpSkin", type="Class")] + [Style(name="trackUpSkin", type="Class")] /** * Name of the class to use as the skin for the up arrow button of the scroll bar * when it is disabled. If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height (for horizontal scroll bars) * or width (for vertical scroll bars) as the track. * * @default ScrollArrowUp_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowDisabledSkin", type="Class")] + [Style(name="upArrowDisabledSkin", type="Class")] /** * Name of the class to use as the skin for the up arrow button of the scroll bar when * you click the arrow button. If you change the skin, either graphically or programmatically, * you should ensure that the new skin is the same height (for horizontal scroll bars) or width * (for vertical scroll bars) as the track. * * @default ScrollArrowUp_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowDownSkin", type="Class")] + [Style(name="upArrowDownSkin", type="Class")] /** * Name of the class to use as the skin for the up arrow button of the scroll bar when the * mouse pointer is over the arrow button. If you change the skin, either graphically or * programmatically, you should ensure that the new skin is the same height (for horizontal * scroll bars) or width (for vertical scroll bars) as the track. * * @default ScrollArrowUp_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowOverSkin", type="Class")] + [Style(name="upArrowOverSkin", type="Class")] /** * Name of the class to use as the skin for the up arrow button of the scroll bar. If you * change the skin, either graphically or programmatically, you should ensure that the new * skin is the same height (for horizontal scroll bars) or width (for vertical scroll bars) * as the track. * * @default ScrollArrowUp_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upArrowUpSkin", type="Class")] + [Style(name="upArrowUpSkin", type="Class")] /** * Name of the class to use as the icon for the thumb of the scroll bar. * * @default ScrollBar_thumbIcon * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="thumbIcon", type="Class")] + [Style(name="thumbIcon", type="Class")] /** * @copy fl.controls.BaseButton#style:repeatDelay * * @default 500 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatDelay", type="Number", format="Time")] + [Style(name="repeatDelay", type="Number", format="Time")] /** * @copy fl.controls.BaseButton#style:repeatInterval * * @default 35 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="repeatInterval", type="Number", format="Time")] - + [Style(name="repeatInterval", type="Number", format="Time")] + /** * The ScrollBar component provides the end user with a way to control the * portion of data that is displayed when there is too much data to * fit in the display area. The scroll bar consists of four parts: * two arrow buttons, a track, and a thumb. The position of the * thumb and display of the buttons depends on the current state of * the scroll bar. The scroll bar uses four parameters to calculate * its display state: a minimum range value; a maximum range value; * a current position that must be within the range values; and a * viewport size that must be equal to or less than the range and * represents the number of items in the range that can be * displayed at the same time. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ScrollBar extends UIComponent - { + public class ScrollBar extends UIComponent + { /** * @private (internal) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const WIDTH : Number = 15; + public static const WIDTH : Number = 15; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _pageSize : Number; + private var _pageSize : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _pageScrollSize : Number; + private var _pageScrollSize : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _lineScrollSize : Number; + private var _lineScrollSize : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _minScrollPosition : Number; + private var _minScrollPosition : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _maxScrollPosition : Number; + private var _maxScrollPosition : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _scrollPosition : Number; + private var _scrollPosition : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _direction : String; + private var _direction : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var thumbScrollOffset : Number; + private var thumbScrollOffset : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var inDrag : Boolean; + protected var inDrag : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var upArrow : BaseButton; + protected var upArrow : BaseButton; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var downArrow : BaseButton; + protected var downArrow : BaseButton; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var thumb : LabelButton; + protected var thumb : LabelButton; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var track : BaseButton; + protected var track : BaseButton; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected static const DOWN_ARROW_STYLES : Object; + protected static const DOWN_ARROW_STYLES : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected const THUMB_STYLES : Object; + protected const THUMB_STYLES : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected const TRACK_STYLES : Object; + protected const TRACK_STYLES : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected const UP_ARROW_STYLES : Object; - + protected const UP_ARROW_STYLES : Object; + /** * @copy fl.core.UIComponent#width * * @see #height * @see #setSize() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get width () : Number; + public function get width () : Number; /** * @copy fl.core.UIComponent#height * * @see #setSize() * @see #width * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get height () : Number; + public function get height () : Number; /** * Gets or sets a Boolean value that indicates whether the scroll bar is enabled. * A value of true indicates that the scroll bar is enabled; a value of * false indicates that it is not. * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get enabled () : Boolean; + public function get enabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets the current scroll position and updates the position * of the thumb. The scrollPosition value represents a relative position between * the minScrollPosition and maxScrollPosition values. * * @default 0 * * @see #setScrollProperties() * @see #minScrollPosition * @see #maxScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scrollPosition () : Number; + public function get scrollPosition () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scrollPosition (newScrollPosition:Number) : void; + public function set scrollPosition (newScrollPosition:Number) : void; /** * Gets or sets a number that represents the minimum scroll position. The * scrollPosition value represents a relative position between the * minScrollPosition and the maxScrollPosition values. * This property is set by the component that contains the scroll bar, * and is usually zero. * * @default 0 * * @see #setScrollProperties() * @see #maxScrollPosition * @see #scrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get minScrollPosition () : Number; + public function get minScrollPosition () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set minScrollPosition (value:Number) : void; + public function set minScrollPosition (value:Number) : void; /** * Gets or sets a number that represents the maximum scroll position. The * scrollPosition value represents a relative position between the * minScrollPosition and the maxScrollPosition values. * This property is set by the component that contains the scroll bar, * and is the maximum value. Usually this property describes the number * of pixels between the bottom of the component and the bottom of * the content, but this property is often set to a different value to change the * behavior of the scrolling. For example, the TextArea component sets this * property to the maxScrollH value of the text field, so that the * scroll bar scrolls appropriately by line of text. * * @default 0 * * @see #setScrollProperties() * @see #minScrollPosition * @see #scrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxScrollPosition () : Number; + public function get maxScrollPosition () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maxScrollPosition (value:Number) : void; + public function set maxScrollPosition (value:Number) : void; /** * Gets or sets the number of lines that a page contains. The lineScrollSize * is measured in increments between the minScrollPosition and * the maxScrollPosition. If this property is 0, the scroll bar * will not scroll. * * @default 10 * * @see #maxScrollPosition * @see #minScrollPosition * @see #setScrollProperties() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get pageSize () : Number; + public function get pageSize () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set pageSize (value:Number) : void; + public function set pageSize (value:Number) : void; /** * Gets or sets a value that represents the increment by which the page is scrolled * when the scroll bar track is pressed. The pageScrollSize value is * measured in increments between the minScrollPosition and the * maxScrollPosition values. If this value is set to 0, the value of the * pageSize property is used. * * @default 0 * * @see #maxScrollPosition * @see #minScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get pageScrollSize () : Number; + public function get pageScrollSize () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set pageScrollSize (value:Number) : void; + public function set pageScrollSize (value:Number) : void; /** * Gets or sets a value that represents the increment by which to scroll the page * when the scroll bar track is pressed. The pageScrollSize is measured * in increments between the minScrollPosition and the maxScrollPosition * values. If this value is set to 0, the value of the pageSize property is used. * * @default 0 * * @see #maxScrollPosition * @see #minScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get lineScrollSize () : Number; + public function get lineScrollSize () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set lineScrollSize (value:Number) : void; + public function set lineScrollSize (value:Number) : void; /** * Gets or sets a value that indicates whether the scroll bar scrolls horizontally or vertically. * Valid values are ScrollBarDirection.HORIZONTAL and * ScrollBarDirection.VERTICAL. * * @default ScrollBarDirection.VERTICAL * * @see fl.controls.ScrollBarDirection ScrollBarDirection * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get direction () : String; + public function get direction () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set direction (value:String) : void; - + public function set direction (value:String) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * @copy fl.core.UIComponent#setSize() * * @see #height * @see #width * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSize (width:Number, height:Number) : void; + public function setSize (width:Number, height:Number) : void; /** * Sets the range and viewport size of the ScrollBar component. The ScrollBar * component updates the state of the arrow buttons and size of the scroll * thumb accordingly. All of the scroll properties are relative to the * scale of the minScrollPosition and the maxScrollPosition. * Each number between the maximum and minumum values represents one scroll position. * * @param pageSize Size of one page. Determines the size of the thumb, and the increment by which the scroll bar moves when the arrows are clicked. * @param minScrollPosition Bottom of the scrolling range. * @param maxScrollPosition Top of the scrolling range. * @param pageScrollSize Increment to move when a track is pressed, in pixels. * * @see #maxScrollPosition * @see #minScrollPosition * @see #pageScrollSize * @see #pageSize * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setScrollProperties (pageSize:Number, minScrollPosition:Number, maxScrollPosition:Number, pageScrollSize:Number = 0) : void; + public function setScrollProperties (pageSize:Number, minScrollPosition:Number, maxScrollPosition:Number, pageScrollSize:Number = 0) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function scrollPressHandler (event:ComponentEvent) : void; + protected function scrollPressHandler (event:ComponentEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function thumbPressHandler (event:MouseEvent) : void; + protected function thumbPressHandler (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleThumbDrag (event:MouseEvent) : void; + protected function handleThumbDrag (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function thumbReleaseHandler (event:MouseEvent) : void; + protected function thumbReleaseHandler (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setScrollPosition (newScrollPosition:Number, fireEvent:Boolean = true) : void; + public function setScrollPosition (newScrollPosition:Number, fireEvent:Boolean = true) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setStyles () : void; + protected function setStyles () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateThumb () : void; - } -} + protected function updateThumb () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollBarDirection.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollBarDirection.as index 1631775a0f..901ba09716 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollBarDirection.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollBarDirection.as @@ -1,18 +1,18 @@ -package fl.controls -{ +package fl.controls +{ /** * Defines the values for the direction property of the ScrollBar component. * * @see ScrollBar#direction ScrollBar.direction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ScrollBarDirection - { + public class ScrollBarDirection + { /** * Indicates that the ScrollBar component instance is used for vertical scrolling. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const VERTICAL : String = "vertical"; + public static const VERTICAL : String = "vertical"; /** * Indicates that the ScrollBar component instance is used for horizontal scrolling. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const HORIZONTAL : String = "horizontal"; - - } -} + public static const HORIZONTAL : String = "horizontal"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollPolicy.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollPolicy.as index 1f945cc643..275e761df4 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollPolicy.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/ScrollPolicy.as @@ -1,22 +1,22 @@ -package fl.controls -{ +package fl.controls +{ /** * Values for the horizontalScrollPolicy and verticalScrollPolicy * properties of the BaseScrollPane class. * * @see fl.containers.BaseScrollPane#horizontalScrollPolicy BaseScrollPane.horizontalScrollPolicy * @see fl.containers.BaseScrollPane#verticalScrollPolicy BaseScrollPane.verticalScrollPolicy * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ScrollPolicy - { + public class ScrollPolicy + { /** * Always show the scroll bar. The size of the scroll bar is automatically * added to the size of the owner's contents to determine the size of the * owner if explicit sizes are not specified. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ON : String = "on"; + public static const ON : String = "on"; /** * Show the scroll bar if the children exceed the owner's dimensions. * The size of the owner is not adjusted to account for the scroll bars * when they appear, so this may cause the scroll bar to obscure the contents * of the component or container. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const AUTO : String = "auto"; + public static const AUTO : String = "auto"; /** * Never show the scroll bar. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const OFF : String = "off"; - - } -} + public static const OFF : String = "off"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/SelectableList.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/SelectableList.as index 5fbc3254ca..9b4c2d33d2 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/SelectableList.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/SelectableList.as @@ -1,406 +1,406 @@ -package fl.controls -{ - import fl.containers.BaseScrollPane; - import fl.controls.listClasses.CellRenderer; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.listClasses.ListData; - import fl.controls.ScrollPolicy; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.data.DataProvider; - import fl.data.SimpleCollectionItem; - import fl.events.DataChangeEvent; - import fl.events.DataChangeType; - import fl.events.ListEvent; - import fl.events.ScrollEvent; - import fl.managers.IFocusManagerComponent; - import flash.display.DisplayObject; - import flash.display.Sprite; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.ui.Keyboard; - import flash.utils.Dictionary; - +package fl.controls +{ + import fl.containers.BaseScrollPane; + import fl.controls.listClasses.CellRenderer; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.listClasses.ListData; + import fl.controls.ScrollPolicy; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.data.DataProvider; + import fl.data.SimpleCollectionItem; + import fl.events.DataChangeEvent; + import fl.events.DataChangeType; + import fl.events.ListEvent; + import fl.events.ScrollEvent; + import fl.managers.IFocusManagerComponent; + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.ui.Keyboard; + import flash.utils.Dictionary; + /** * Dispatched when the user rolls the pointer off of an item in the component. * * @eventType fl.events.ListEvent.ITEM_ROLL_OUT * * @see #event:itemRollOver * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemRollOut", type="fl.events.ListEvent")] + [Event(name="itemRollOut", type="fl.events.ListEvent")] /** * Dispatched when the user rolls the pointer over an item in the component. * * @eventType fl.events.ListEvent.ITEM_ROLL_OVER * * @see #event:itemRollOut * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemRollOver", type="fl.events.ListEvent")] + [Event(name="itemRollOver", type="fl.events.ListEvent")] /** * Dispatched when the user rolls the pointer over the component. * * @eventType flash.events.MouseEvent.ROLL_OVER * * @see #event:rollOut * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="rollOver", type="flash.events.MouseEvent")] + [Event(name="rollOver", type="flash.events.MouseEvent")] /** * Dispatched when the user rolls the pointer off of the component. * * @eventType flash.events.MouseEvent.ROLL_OUT * * @see #event:rollOver * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="rollOut", type="flash.events.MouseEvent")] + [Event(name="rollOut", type="flash.events.MouseEvent")] /** * Dispatched when the user clicks an item in the component. * *

    The click event is dispatched before the value * of the component is changed. To identify the row and column that were clicked, * use the properties of the event object; do not use the selectedIndex * and selectedItem properties.

    * * @eventType fl.events.ListEvent.ITEM_CLICK * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemClick", type="fl.events.ListEvent")] + [Event(name="itemClick", type="fl.events.ListEvent")] /** * Dispatched when the user clicks an item in the component twice in * rapid succession. Unlike the click event, the doubleClick event is * dispatched after the selectedIndex of the component is * changed. * * @eventType fl.events.ListEvent.ITEM_DOUBLE_CLICK * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="itemDoubleClick", type="fl.events.ListEvent")] + [Event(name="itemDoubleClick", type="fl.events.ListEvent")] /** * Dispatched when a different item is selected in the list. * * @eventType flash.events.Event.CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change", type="flash.events.Event")] + [Event(name="change", type="flash.events.Event")] /** * Dispatched when the user scrolls horizontally or vertically. * * @eventType fl.events.ScrollEvent.SCROLL * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="scroll", type="fl.events.ScrollEvent")] + [Event(name="scroll", type="fl.events.ScrollEvent")] /** * The class that provides the skin for the background of the component. * * @default List_skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="skin", type="Class")] + [Style(name="skin", type="Class")] /** * The class that provides the cell renderer for each item in the component. * * @default fl.contols.listClasses.CellRenderer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="cellRenderer", type="Class")] + [Style(name="cellRenderer", type="Class")] /** * The alpha value to set the list to when the enabled property is false. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledAlpha", type="Number")] + [Style(name="disabledAlpha", type="Number")] /** * The padding that separates the border of the list from its contents, in pixels. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="contentPadding", type="Number", format="Length")] - + [Style(name="contentPadding", type="Number", format="Length")] + /** * The SelectableList is the base class for all list-based components--for * example, the List, TileList, DataGrid, and ComboBox components. * This class provides methods and properties that are used for the * rendering and layout of rows, and to set scroll bar styles and data * providers. * *

    Note: This class does not create a component; * it is exposed only so that it can be extended.

    * * @see fl.controls.DataGrid * @see fl.controls.List * @see fl.controls.TileList * @see fl.data.DataProvider * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class SelectableList extends BaseScrollPane implements IFocusManagerComponent - { + public class SelectableList extends BaseScrollPane implements IFocusManagerComponent + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var listHolder : Sprite; + protected var listHolder : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var list : Sprite; + protected var list : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _dataProvider : DataProvider; + protected var _dataProvider : DataProvider; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var activeCellRenderers : Array; + protected var activeCellRenderers : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var availableCellRenderers : Array; + protected var availableCellRenderers : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var renderedItems : Dictionary; + protected var renderedItems : Dictionary; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var invalidItems : Dictionary; + protected var invalidItems : Dictionary; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _horizontalScrollPosition : Number; + protected var _horizontalScrollPosition : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _verticalScrollPosition : Number; + protected var _verticalScrollPosition : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _allowMultipleSelection : Boolean; + protected var _allowMultipleSelection : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _selectable : Boolean; + protected var _selectable : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _selectedIndices : Array; + protected var _selectedIndices : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var caretIndex : int; + protected var caretIndex : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var lastCaretIndex : int; + protected var lastCaretIndex : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var preChangeItems : Array; + protected var preChangeItems : Array; /** * @private */ - private var collectionItemImport : SimpleCollectionItem; + private var collectionItemImport : SimpleCollectionItem; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var rendererStyles : Object; + protected var rendererStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var updatedRendererStyles : Object; + protected var updatedRendererStyles : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * Creates the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets the data model of the list of items to be viewed. A data provider * can be shared by multiple list-based components. Changes to the data provider * are immediately available to all components that use it as a data source. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get dataProvider () : DataProvider; + public function get dataProvider () : DataProvider; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set dataProvider (value:DataProvider) : void; + public function set dataProvider (value:DataProvider) : void; /** * Gets or sets the number of pixels that the list scrolls to the right when the * horizontalScrollPolicy property is set to ScrollPolicy.ON. * * @see fl.containers.BaseScrollPane#horizontalScrollPosition * @see fl.containers.BaseScrollPane#maxVerticalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxHorizontalScrollPosition () : Number; + public function get maxHorizontalScrollPosition () : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maxHorizontalScrollPosition (value:Number) : void; + public function set maxHorizontalScrollPosition (value:Number) : void; /** * Gets the number of items in the data provider. * * @includeExample examples/SelectableList.length.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get length () : uint; + public function get length () : uint; /** * Gets a Boolean value that indicates whether more than one list item * can be selected at a time. A value of true indicates that * multiple selections can be made at one time; a value of false * indicates that only one item can be selected at one time. * * @default false * * @includeExample examples/List.allowMultipleSelection.1.as -noswf * * @see #selectable * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get allowMultipleSelection () : Boolean; + public function get allowMultipleSelection () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set allowMultipleSelection (value:Boolean) : void; + public function set allowMultipleSelection (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether the items in the list * can be selected. A value of true indicates that the list items * can be selected; a value of false indicates that they cannot be. * * @default true * * @see #allowMultipleSelection * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectable () : Boolean; + public function get selectable () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectable (value:Boolean) : void; + public function set selectable (value:Boolean) : void; /** * Gets or sets the index of the item that is selected in a single-selection * list. A single-selection list is a list in which only one item can be selected * at a time. * *

    A value of -1 indicates that no item is selected; if multiple selections * are made, this value is equal to the index of the item that was selected last in * the group of selected items.

    * *

    When ActionScript is used to set this property, the item at the specified index * replaces the current selection. When the selection is changed programmatically, * a change event object is not dispatched.

    * * @see #selectedIndices * @see #selectedItem * * @includeExample examples/SelectableList.selectedIndex.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedIndex () : int; + public function get selectedIndex () : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectedIndex (value:int) : void; + public function set selectedIndex (value:int) : void; /** * Gets or sets an array that contains the items that were selected from * a multiple-selection list. * *

    To replace the current selection programmatically, you can make an * explicit assignment to this property. You can clear the current selection * by setting this property to an empty array or to a value of undefined. * If no items are selected from the list of items, this property is * undefined.

    * *

    The sequence of values in the array reflects the order in which the items * were selected from the multiple-selection list. For example, if you click the second * item from the list, then the third item, and finally the first item, this property * contains an array of values in the following sequence: [1,2,0].

    * * @see #allowMultipleSelection * @see #selectedIndex * @see #selectedItems * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedIndices () : Array; + public function get selectedIndices () : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectedIndices (value:Array) : void; + public function set selectedIndices (value:Array) : void; /** * Gets or sets the item that was selected from a single-selection list. For a * multiple-selection list in which multiple items are selected, this property * contains the item that was selected last. * *

    If no selection is made, the value of this property is null.

    * * @see #selectedIndex * @see #selectedItems * * @includeExample examples/SelectableList.selectedIndex.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedItem () : Object; + public function get selectedItem () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectedItem (value:Object) : void; + public function set selectedItem (value:Object) : void; /** * Gets or sets an array that contains the objects for the * items that were selected from the multiple-selection list. * *

    For a single-selection list, the value of this property is an * array containing the one selected item. In a single-selection * list, the allowMultipleSelection property is set to * false.

    * * @includeExample examples/SelectableList.selectedItems.1.as -noswf * * @see #allowMultipleSelection * @see #selectedIndices * @see #selectedItem * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectedItems () : Array; + public function get selectedItems () : Array; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selectedItems (value:Array) : void; + public function set selectedItems (value:Array) : void; /** * Gets the number of rows that are at least partially visible in the list. * *

    Note: This property must be overridden in any class that extends SelectableList.

    * * @includeExample examples/SelectableList.rowCount.1.as -noswf * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowCount () : uint; - + public function get rowCount () : uint; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new SelectableList instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function SelectableList (); + public function SelectableList (); /** * Clears the currently selected item in the list and sets the selectedIndex property to -1. * * @includeExample examples/List.clearSelection.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clearSelection () : void; + public function clearSelection () : void; /** * Retrieves the ICellRenderer for a given item object, if there is one. * This method always returns null. * * @param item The item in the data provider. * * @return A value of null. * * @includeExample examples/SelectableList.itemToCellRenderer.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function itemToCellRenderer (item:Object) : ICellRenderer; + public function itemToCellRenderer (item:Object) : ICellRenderer; /** * Appends an item to the end of the list of items. * *

    An item should contain label and data * properties; however, items that contain other properties can also * be added to the list. By default, the label property of * an item is used to display the label of the row; the data * property is used to store the data of the row.

    * * @param item The item to be added to the data provider. * * @see #addItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addItem (item:Object) : void; + public function addItem (item:Object) : void; /** * Inserts an item into the list at the specified index location. The indices of * items at or after the specified index location are incremented by 1. * * @param item The item to be added to the list. * * @param index The index at which to add the item. * * @throws RangeError The specified index is less than 0 or greater than or equal to the length of the data provider. * * @see #addItem() * @see #replaceItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addItemAt (item:Object, index:uint) : void; + public function addItemAt (item:Object, index:uint) : void; /** * Removes all items from the list. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeAll () : void; + public function removeAll () : void; /** * Retrieves the item at the specified index. * * @param index The index of the item to be retrieved. * * @return The object at the specified index location. * * @throws RangeError The specified index is less than 0 or greater than or equal to the length of the data provider. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getItemAt (index:uint) : Object; + public function getItemAt (index:uint) : Object; /** * Removes the specified item from the list. * * @param item The item to be removed. * * @return The item that was removed. * * @throws RangeError The item could not be found. * * @see #removeAll() * @see #removeItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeItem (item:Object) : Object; + public function removeItem (item:Object) : Object; /** * Removes the item at the specified index position. The indices of * items after the specified index location are decremented by 1. * * @param index The index of the item in the data provider to be removed. * * @return The item that was removed. * * @see #removeAll() * @see #removeItem() * @see #replaceItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeItemAt (index:uint) : Object; + public function removeItemAt (index:uint) : Object; /** * Replaces the item at the specified index location with another item. * This method modifies the data provider of the List component. If * the data provider is shared with other components, the data that is * provided to those components is also updated. * * @param item The item to replace the item at the specified index location. * * @param index The index position of the item to be replaced. * * @return The item that was replaced. * * @throws RangeError The specified index is less than 0 or greater than or equal to the length of the data provider. * * @see #removeItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function replaceItemAt (item:Object, index:uint) : Object; + public function replaceItemAt (item:Object, index:uint) : Object; /** * Invalidates the whole list, forcing the list items to be redrawn. * * @see #invalidateItem() * @see #invalidateItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function invalidateList () : void; + public function invalidateList () : void; /** * Invalidates a specific item renderer. * * @param item The item in the data provider to invalidate. * * @see #invalidateItemAt() * @see #invalidateList() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] This doesn't make sense. It says the method invalidates an item renderer, * but the param description for item says that it receives "the data provider to invalidate." * Isn't the item renderer distinct from the item? There is a similar problem in the next method. */ - public function invalidateItem (item:Object) : void; + public function invalidateItem (item:Object) : void; /** * Invalidates the renderer for the item at the specified index. * * @param index The index of the item in the data provider to invalidate. * * @see #invalidateItem() * @see #invalidateList() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] This method appears to invalid an item, but it is described as * invalidating an item renderer. What is correct? */ - public function invalidateItemAt (index:uint) : void; + public function invalidateItemAt (index:uint) : void; /** * Sorts the elements of the current data provider. This method * performs a sort based on the Unicode values of the elements. ASCII is a * subset of Unicode. * * @param sortArgs The arguments against which to sort. * * @return The return value depends on whether any parameters are passed to * this method. For more information, see the Array.sort() method. * Note that this method returns 0 when the sortArgs parameter * is set to Array.UNIQUESORT. * * @see #sortItemsOn() * @see Array#sort() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function sortItems (...sortArgs:Array) : *; + public function sortItems (...sortArgs:Array) : *; /** * Sorts the elements of the current data provider by one or more * of its fields. * * @param field The field on which to sort. * @param options Sort arguments that are used to override the default sort behavior. * Separate two or more arguments with the bitwise OR (|) operator. * * @return The return value depends on whether any parameters are passed to this * method. For more information, see the Array.sortOn() method. * Note that this method returns 0 when the sortOption parameter * is set to Array.UNIQUESORT. * * @includeExample examples/SelectableList.sortItemsOn.1.as -noswf * * @see #sortItems() * @see fl.data.DataProvider#sortOn() DataProvider.sortOn() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function sortItemsOn (field:String, options:Object = null) : *; + public function sortItemsOn (field:String, options:Object = null) : *; /** * Checks whether the specified item is selected in the list. * * @param item The item to check. * * @return This method returns true if the specified item is selected; * otherwise, if the specified item has a value of null or is not * included in the list, this method returns false. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function isItemSelected (item:Object) : Boolean; + public function isItemSelected (item:Object) : Boolean; /** * Scrolls the list to the item at the location indicated by * the current value of the selectedIndex property. * * @see #selectedIndex * @see #scrollToIndex() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function scrollToSelected () : void; + public function scrollToSelected () : void; /** * Scrolls the list to the item at the specified index. If the index * is out of range, the scroll position does not change. * * @param newCaretIndex The index location to scroll to. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function scrollToIndex (newCaretIndex:int) : void; + public function scrollToIndex (newCaretIndex:int) : void; /** * Returns the index of the next item in the dataProvider in which * the label's first character matches a specified string character. * If the search reaches the end of the dataProvider without searching * all the items, it will loop back to the start. The search does not * include the startIndex. * * @param firstLetter The string character to search for * @param startIndex The index in the dataProvider to start at. * * @return The index of the next item in the dataProvider. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getNextIndexAtLetter (firstLetter:String, startIndex:int = -1) : int; + public function getNextIndexAtLetter (firstLetter:String, startIndex:int = -1) : int; /** * Retrieves the string that the renderer displays for the given data object * based on the label properties of the object. This method * is intended to be overwritten in sub-components. For example, List has * a labelField and a labelFunction to derive the * label. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function itemToLabel (item:Object) : String; + public function itemToLabel (item:Object) : String; /** * Sets a style on the renderers in the list. * * @param name The name of the style to be set. * @param style The value of the style to be set. * * @includeExample examples/SelectableList.setRendererStyle.1.as -noswf * @includeExample examples/SelectableList.setRendererStyle.2.as -noswf * @includeExample examples/SelectableList.setRendererStyle.3.as -noswf * @includeExample examples/SelectableList.setRendererStyle.4.as -noswf * * @see #clearRendererStyle() * @see #getRendererStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setRendererStyle (name:String, style:Object, column:uint = 0) : void; + public function setRendererStyle (name:String, style:Object, column:uint = 0) : void; /** * Retrieves a style that is set on the renderers in the list. * * @param name The name of the style to be retrieved. * @param style The value of the style to be retrieved. * * @see #clearRendererStyle() * @see #setRendererStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getRendererStyle (name:String, column:int = -1) : Object; + public function getRendererStyle (name:String, column:int = -1) : Object; /** * Clears a style that is set on the renderers in the list. * * @param name The name of the style to be cleared. * * @see #getRendererStyle() * @see #setRendererStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clearRendererStyle (name:String, column:int = -1) : void; + public function clearRendererStyle (name:String, column:int = -1) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function _invalidateList () : void; + protected function _invalidateList () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleDataChange (event:DataChangeEvent) : void; + protected function handleDataChange (event:DataChangeEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleCellRendererMouseEvent (event:MouseEvent) : void; + protected function handleCellRendererMouseEvent (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleCellRendererClick (event:MouseEvent) : void; + protected function handleCellRendererClick (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleCellRendererChange (event:Event) : void; + protected function handleCellRendererChange (event:Event) : void; /** * @private (protected) */ - protected function handleCellRendererDoubleClick (event:MouseEvent) : void; + protected function handleCellRendererDoubleClick (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setHorizontalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setHorizontalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateRendererStyles () : void; + protected function updateRendererStyles () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawList () : void; + protected function drawList () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * Moves the selection in a horizontal direction in response * to the user selecting items using the left-arrow or right-arrow * keys and modifiers such as the Shift and Ctrl keys. * *

    Not implemented in List because the default list * is single column and therefore doesn't scroll horizontally.

    * * @param code The key that was pressed (e.g. Keyboard.LEFT) * * @param shiftKey true if the shift key was held down when * the keyboard key was pressed. * * @param ctrlKey true if the ctrl key was held down when * the keyboard key was pressed * */ - protected function moveSelectionHorizontally (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function moveSelectionHorizontally (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * Moves the selection in a vertical direction in response * to the user selecting items using the up-arrow or down-arrow * Keys and modifiers such as the Shift and Ctrl keys. * * @param code The key that was pressed (e.g. Keyboard.DOWN) * * @param shiftKey true if the shift key was held down when * the keyboard key was pressed. * * @param ctrlKey true if the ctrl key was held down when * the keyboard key was pressed * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function moveSelectionVertically (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function moveSelectionVertically (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; + protected function initializeAccessibility () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function onPreChange (event:DataChangeEvent) : void; - } -} + protected function onPreChange (event:DataChangeEvent) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/SliderDirection.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/SliderDirection.as index 27b09820c2..97d094e161 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/SliderDirection.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/SliderDirection.as @@ -1,18 +1,18 @@ -package fl.controls -{ +package fl.controls +{ /** * The orientation of the Slider component. * * @see Slider#direction Slider.direction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class SliderDirection - { + public class SliderDirection + { /** * Position the Slider component on the horizontal axis. * * @includeExample examples/SliderDirection.HORIZONTAL.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var HORIZONTAL : String; + public static var HORIZONTAL : String; /** * Position the Slider component on the vertical axis. * * @includeExample examples/SliderDirection.VERTICAL.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var VERTICAL : String; - - } -} + public static var VERTICAL : String; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TextArea.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TextArea.as index 7b81292148..d939e957ba 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TextArea.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TextArea.as @@ -1,387 +1,387 @@ -package fl.controls -{ - import fl.controls.ScrollBar; - import fl.controls.UIScrollBar; - import fl.controls.ScrollPolicy; - import fl.controls.TextInput; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - import fl.events.ScrollEvent; - import fl.managers.IFocusManager; - import fl.managers.IFocusManagerComponent; - import flash.display.DisplayObject; - import flash.events.Event; - import flash.events.TextEvent; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.events.FocusEvent; - import flash.system.IME; - import flash.text.TextField; - import flash.text.TextFieldType; - import flash.text.TextFormat; - import flash.text.TextLineMetrics; - import flash.ui.Keyboard; - +package fl.controls +{ + import fl.controls.ScrollBar; + import fl.controls.UIScrollBar; + import fl.controls.ScrollPolicy; + import fl.controls.TextInput; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + import fl.events.ScrollEvent; + import fl.managers.IFocusManager; + import fl.managers.IFocusManagerComponent; + import flash.display.DisplayObject; + import flash.events.Event; + import flash.events.TextEvent; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.events.FocusEvent; + import flash.system.IME; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFormat; + import flash.text.TextLineMetrics; + import flash.ui.Keyboard; + /** * Dispatched when the text in the TextArea component changes. * * @eventType flash.events.Event.CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change", type="flash.events.Event")] + [Event(name="change", type="flash.events.Event")] /** * Dispatched when the user enters, deletes, * or pastes text into the component. * * @eventType flash.events.TextEvent.TEXT_INPUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="textInput", type="flash.events.TextEvent")] + [Event(name="textInput", type="flash.events.TextEvent")] /** * Dispatched when the user presses the Enter key while in the component. * * @eventType fl.events.ComponentEvent.ENTER * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] Does "in the control" here mean that the control has focus? */ - [Event(name= "enter", type="fl.events.ComponentEvent")] + [Event(name= "enter", type="fl.events.ComponentEvent")] /** * Dispatched when the content is scrolled. * * @eventType fl.events.ScrollEvent.SCROLL * * @includeExample examples/TextArea.scroll.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="scroll", type="fl.events.ScrollEvent")] + [Event(name="scroll", type="fl.events.ScrollEvent")] /** * The class that provides the background for the TextArea * component. * * @default TextArea_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * The class that provides the background for the TextArea * component when its enabled property is set to false. * * @default TextArea_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledSkin", type="Class")] + [Style(name="disabledSkin", type="Class")] /** * The padding that separates the component border from the text, in pixels. * * @default 3 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] + [Style(name="textPadding", type="Number", format="Length")] /** * @copy fl.controls.LabelButton#style:embedFonts * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="embedFonts", type="Boolean")] - + [Style(name="embedFonts", type="Boolean")] + /** * The TextArea component is a multiline text field with a border * and optional scroll bars. The TextArea component supports * the HTML rendering capabilities of Adobe Flash Player. * * @includeExample examples/TextAreaExample.as * * @see TextInput * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class TextArea extends UIComponent implements IFocusManagerComponent - { + public class TextArea extends UIComponent implements IFocusManagerComponent + { /** * A reference to the internal text field of the TextArea component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var textField : TextField; + public var textField : TextField; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _editable : Boolean; + protected var _editable : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _wordWrap : Boolean; + protected var _wordWrap : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _horizontalScrollPolicy : String; + protected var _horizontalScrollPolicy : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _verticalScrollPolicy : String; + protected var _verticalScrollPolicy : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _horizontalScrollBar : UIScrollBar; + protected var _horizontalScrollBar : UIScrollBar; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _verticalScrollBar : UIScrollBar; + protected var _verticalScrollBar : UIScrollBar; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var background : DisplayObject; + protected var background : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _html : Boolean; + protected var _html : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _savedHTML : String; + protected var _savedHTML : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var textHasChanged : Boolean; + protected var textHasChanged : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected static const SCROLL_BAR_STYLES : Object; + protected static const SCROLL_BAR_STYLES : Object; /** * @private (internal) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * Gets a reference to the horizontal scroll bar. * * @see #verticalScrollBar * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollBar () : UIScrollBar; + public function get horizontalScrollBar () : UIScrollBar; /** * Gets a reference to the vertical scroll bar. * * @includeExample examples/TextArea.verticalScrollBar.1.as -noswf * * @see #horizontalScrollBar * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get verticalScrollBar () : UIScrollBar; + public function get verticalScrollBar () : UIScrollBar; /** * @copy fl.core.UIComponent#enabled * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get enabled () : Boolean; + public function get enabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets a string which contains the text that is currently in * the TextInput component. This property contains text that is unformatted * and does not have HTML tags. To retrieve this text formatted as HTML, use * the htmlText property. * * @default "" * * @see #htmlText * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get text () : String; + public function get text () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set text (value:String) : void; + public function set text (value:String) : void; /** * Gets or sets the HTML representation of the string that the text field contains. * * @default "" * * @includeExample examples/TextArea.htmlText.1.as -noswf * @includeExample examples/TextArea.htmlText.2.as -noswf * * @see #text * @see flash.text.TextField#htmlText TextField.htmlText * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get htmlText () : String; + public function get htmlText () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set htmlText (value:String) : void; + public function set htmlText (value:String) : void; /** * Gets or sets a Boolean value that indicates whether extra white space * is removed from a TextArea component that contains HTML text. Examples * of extra white space in the component include spaces and line breaks. * A value of true indicates that extra white space is removed; * a value of false indicates that extra white space is not removed. * *

    This property affects only text that is set by using the htmlText * property; it does not affect text that is set by using the text property. * If you use the text property to set text, the condenseWhite * property is ignored.

    * *

    If the condenseWhite property is set to true, you * must use standard HTML commands, such as <br> and <p>, to place line * breaks in the text field.

    * * @default false * * @includeExample examples/TextArea.condenseWhite.1.as -noswf * * @see flash.text.TextField#condenseWhite TextField.condenseWhite * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get condenseWhite () : Boolean; + public function get condenseWhite () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set condenseWhite (value:Boolean) : void; + public function set condenseWhite (value:Boolean) : void; /** * Gets or sets the scroll policy for the horizontal scroll bar. * This can be one of the following values: * *
      *
    • ScrollPolicy.ON: The horizontal scroll bar is always on.
    • *
    • ScrollPolicy.OFF: The scroll bar is always off.
    • *
    • ScrollPolicy.AUTO: The scroll bar turns on when it is needed.
    • *
    * * * @default ScrollPolicy.AUTO * * @includeExample examples/TextArea.horizontalScrollPolicy.1.as -noswf * * @see #verticalScrollPolicy * @see ScrollPolicy * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollPolicy () : String; + public function get horizontalScrollPolicy () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalScrollPolicy (value:String) : void; + public function set horizontalScrollPolicy (value:String) : void; /** * Gets or sets the scroll policy for the vertical scroll bar. * This can be one of the following values: * *
      *
    • ScrollPolicy.ON: The scroll bar is always on.
    • *
    • ScrollPolicy.OFF: The scroll bar is always off.
    • *
    • ScrollPolicy.AUTO: The scroll bar turns on when it is needed.
    • *
    * * @default ScrollPolicy.AUTO * * @includeExample examples/TextArea.verticalScrollPolicy.1.as -noswf * * @see #horizontalScrollPolicy * @see ScrollPolicy * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get verticalScrollPolicy () : String; + public function get verticalScrollPolicy () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set verticalScrollPolicy (value:String) : void; + public function set verticalScrollPolicy (value:String) : void; /** * Gets or sets the change in the position of the scroll bar thumb, in pixels, after * the user scrolls the text field horizontally. If this value is 0, the text * field was not horizontally scrolled. * * @default 0 * * @see #verticalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollPosition () : Number; + public function get horizontalScrollPosition () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalScrollPosition (value:Number) : void; + public function set horizontalScrollPosition (value:Number) : void; /** * Gets or sets the change in the position of the scroll bar thumb, in pixels, after * the user scrolls the text field vertically. If this value is 1, the text * field was not vertically scrolled. * * @default 1 * * @includeExample examples/TextArea.verticalScrollPosition.1.as -noswf * * @see #horizontalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get verticalScrollPosition () : Number; + public function get verticalScrollPosition () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set verticalScrollPosition (value:Number) : void; + public function set verticalScrollPosition (value:Number) : void; /** * Gets the width of the text, in pixels. * * @default 0 * * @includeExample examples/TextArea.textHeight.1.as -noswf * * @see #textHeight * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] Is this actually the width of the text field that contains the text? * The length of the line that is used to format the text? Similar comment for the below. */ - public function get textWidth () : Number; + public function get textWidth () : Number; /** * Gets the height of the text, in pixels. * * @default 0 * * @includeExample examples/TextArea.textHeight.1.as -noswf * * @see #textWidth * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get textHeight () : Number; + public function get textHeight () : Number; /** * Gets the count of characters that the TextArea component contains. * * @default 0 * * @see #maxChars * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get length () : Number; + public function get length () : Number; /** * Gets or sets the string of characters that the text field * accepts from a user. * *

    Note that characters that are not included in this string * are accepted in the text field if they are entered programmatically.

    * *

    The characters in the string are read from left to right. You can * specify a character range by using the hyphen (-) character.

    * *

    If the value of this property is null, the text field * accepts all characters. If this property is set to an empty string (""), * the text field accepts no characters.

    * *

    If the string begins with a caret (^) character, all characters * are initially accepted and succeeding characters in the string * are excluded from the set of accepted characters. If the string * does not begin with a caret (^) character, no characters are * initially accepted and succeeding characters in the string are * included in the set of accepted characters.

    * * @default null * * @see flash.text.TextField#restrict TextField.restrict * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] Peter, I don't understand the last paragraph above -- re the carets -- but, * if you understand it and think it is clear, it's probably just that I'm not * well enough acquainted with the use of the property. */ - public function get restrict () : String; + public function get restrict () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set restrict (value:String) : void; + public function set restrict (value:String) : void; /** * Gets or sets the maximum number of characters that a user can enter * in the text field. * * @default 0 * * @includeExample examples/TextArea.maxChars.1.as -noswf * * @see #length * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxChars () : int; + public function get maxChars () : int; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maxChars (value:int) : void; + public function set maxChars (value:int) : void; /** * Gets the maximum value of the horizontalScrollPosition property. * * @default 0 * * @see #horizontalScrollPosition * @see #maxVerticalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxHorizontalScrollPosition () : int; + public function get maxHorizontalScrollPosition () : int; /** * Gets the maximum value of the verticalScrollPosition property. * * @default 1 * * @see #verticalScrollPosition * @see #maxHorizontalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxVerticalScrollPosition () : int; + public function get maxVerticalScrollPosition () : int; /** * Gets or sets a Boolean value that indicates whether the text * wraps at the end of the line. A value of true * indicates that the text wraps; a value of false * indicates that the text does not wrap. * * @default true * * @see flash.text.TextField#wordWrap TextField.wordWrap * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get wordWrap () : Boolean; + public function get wordWrap () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set wordWrap (value:Boolean) : void; + public function set wordWrap (value:Boolean) : void; /** * Gets the index position of the first selected character in a selection of one or more * characters. * *

    The index position of a selected character is zero-based and calculated * from the first character that appears in the text area. If there is no selection, * this value is set to the position of the caret.

    * * @default 0 * * @see #selectionEndIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - public function get selectionBeginIndex () : int; + public function get selectionBeginIndex () : int; /** * Gets the index position of the last selected character in a selection of one or more * characters. * *

    The index position of a selected character is zero-based and calculated * from the first character that appears in the text area. If there is no selection, * this value is set to the position of the caret.

    * * @default 0 * * @see #selectionBeginIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - public function get selectionEndIndex () : int; + public function get selectionEndIndex () : int; /** * Gets or sets a Boolean value that indicates whether the TextArea component * instance is the text field for a password. A value of true * indicates that the current instance was created to contain a password; * a value of false indicates that it was not. * *

    If the value of this property is true, the characters * that the user enters in the text area cannot be seen. Instead, * an asterisk is displayed in place of each character that the * user enters. Additionally, the Cut and Copy commands and their keyboard * shortcuts are disabled to prevent the recovery of a password from * an unattended computer.

    * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get displayAsPassword () : Boolean; + public function get displayAsPassword () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set displayAsPassword (value:Boolean) : void; + public function set displayAsPassword (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether the user can * edit the text in the component. A value of true indicates * that the user can edit the text that the component contains; a value of false * indicates that it cannot. * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get editable () : Boolean; + public function get editable () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set editable (value:Boolean) : void; + public function set editable (value:Boolean) : void; /** * Gets or sets the mode of the input method editor (IME). The IME makes * it possible for users to use a QWERTY keyboard to enter characters from * the Chinese, Japanese, and Korean character sets. * *

    Flash sets the IME to the specified mode when the component gets focus, * and restores it to the original value after the component loses focus.

    * *

    The flash.system.IMEConversionMode class defines constants for * the valid values for this property. Set this property to null to * prevent the use of the IME with the component.

    * * @see flash.system.IMEConversionMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get imeMode () : String; + public function get imeMode () : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set imeMode (value:String) : void; + public function set imeMode (value:String) : void; /** * Gets or sets a Boolean value that indicates whether Flash Player * highlights a selection in the text field when the text field * does not have focus. * * If this value is set to true and the text field does not * have focus, Flash Player highlights the selection in gray. If this value * is set to false and the text field does not have focus, Flash * Player does not highlight the selection. * * @default false * * @see flash.text.TextField#alwaysShowSelection TextField.alwaysShowSelection * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get alwaysShowSelection () : Boolean; + public function get alwaysShowSelection () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set alwaysShowSelection (value:Boolean) : void; - + public function set alwaysShowSelection (value:Boolean) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() UIComponent.getStyle() * @see fl.core.UIComponent#setStyle() UIComponent.setStyle() * @see fl.managers.StyleManager StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getStyleDefinition () : Object; + public function getStyleDefinition () : Object; /** * Creates a new TextArea component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function TextArea (); + public function TextArea (); /** * @copy fl.core.UIComponent#drawFocus() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawFocus (draw:Boolean) : void; + public function drawFocus (draw:Boolean) : void; /** * Retrieves information about a specified line of text. * * @param lineIndex The line number for which information is to be retrieved. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getLineMetrics (lineIndex:int) : TextLineMetrics; + public function getLineMetrics (lineIndex:int) : TextLineMetrics; /** * Sets the range of a selection made in a text area that has focus. * The selection range begins at the index that is specified by the start * parameter, and ends at the index that is specified by the end parameter. * The selected text is treated as a zero-based string of characters in which * the first selected character is located at index 0, the second * character at index 1, and so on. * *

    This method has no effect if the text field does not have focus.

    * * @param setSelection The index location of the first character in the selection. * @param endIndex The index position of the last character in the selection. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal Doc team changed the first param name from beginIndex to setSelection * to temporarily resolve the conflict between param descriptions and * method signature. */ - public function setSelection (setSelection:int, endIndex:int) : void; + public function setSelection (setSelection:int, endIndex:int) : void; /** * Appends the specified string after the last character that the TextArea * component contains. This method is more efficient than concatenating two strings * by using an addition assignment on a text property--for example, * myTextArea.text += moreText. This method is particularly * useful when the TextArea component contains a significant amount of * content. * * @param text The string to be appended to the existing text. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function appendText (text:String) : void; + public function appendText (text:String) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateTextFieldType () : void; + protected function updateTextFieldType () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleKeyDown (event:KeyboardEvent) : void; + protected function handleKeyDown (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleChange (event:Event) : void; + protected function handleChange (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleTextInput (event:TextEvent) : void; + protected function handleTextInput (event:TextEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleScroll (event:ScrollEvent) : void; + protected function handleScroll (event:ScrollEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleWheel (event:MouseEvent) : void; + protected function handleWheel (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setEmbedFont (); + protected function setEmbedFont (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setStyles () : void; + protected function setStyles () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawTextFormat () : void; + protected function drawTextFormat () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBackground () : void; + protected function drawBackground () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function delayedLayoutUpdate (event:Event) : void; + protected function delayedLayoutUpdate (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateScrollBars (); + protected function updateScrollBars (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function needVScroll () : Boolean; + protected function needVScroll () : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function needHScroll () : Boolean; + protected function needHScroll () : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setTextSize (width:Number, height:Number, padding:Number) : void; + protected function setTextSize (width:Number, height:Number, padding:Number) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function isOurFocus (target:DisplayObject) : Boolean; + protected function isOurFocus (target:DisplayObject) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusInHandler (event:FocusEvent) : void; + protected function focusInHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusOutHandler (event:FocusEvent) : void; - } -} + protected function focusOutHandler (event:FocusEvent) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TextInput.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TextInput.as index 93292af0e5..78de1f83a7 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TextInput.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TextInput.as @@ -1,280 +1,280 @@ -package fl.controls -{ - import fl.controls.TextInput; - import fl.controls.TextArea; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ComponentEvent; - import fl.managers.IFocusManager; - import fl.managers.IFocusManagerComponent; - import flash.display.DisplayObject; - import flash.events.Event; - import flash.events.TextEvent; - import flash.events.Event; - import flash.events.FocusEvent; - import flash.events.KeyboardEvent; - import flash.system.IME; - import flash.text.TextField; - import flash.text.TextFieldType; - import flash.text.TextFormat; - import flash.text.TextLineMetrics; - import flash.ui.Keyboard; - +package fl.controls +{ + import fl.controls.TextInput; + import fl.controls.TextArea; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ComponentEvent; + import fl.managers.IFocusManager; + import fl.managers.IFocusManagerComponent; + import flash.display.DisplayObject; + import flash.events.Event; + import flash.events.TextEvent; + import flash.events.Event; + import flash.events.FocusEvent; + import flash.events.KeyboardEvent; + import flash.system.IME; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.text.TextFormat; + import flash.text.TextLineMetrics; + import flash.ui.Keyboard; + /** * Dispatched when user input changes text in the TextInput component. * *

    Note: This event does not occur if ActionScript * is used to change the text.

    * * @eventType flash.events.Event.CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="change", type="flash.events.Event")] + [Event(name="change", type="flash.events.Event")] /** * Dispatched when the user presses the Enter key. * * @eventType fl.events.ComponentEvent.ENTER * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="enter", type="fl.events.ComponentEvent")] + [Event(name="enter", type="fl.events.ComponentEvent")] /** * Dispatched when the user inputs text. * * @eventType flash.events.TextEvent.TEXT_INPUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="textInput", type="flash.events.TextEvent")] + [Event(name="textInput", type="flash.events.TextEvent")] /** * The name of the class to use as a background for the TextInput * component. * * @default TextInput_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * The padding that separates the component border from the text, in pixels. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] + [Style(name="textPadding", type="Number", format="Length")] /** * The name of the class to use as a background for the TextInput * component when its enabled property is set to false. * * @default TextInput_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledSkin", type="Class")] + [Style(name="disabledSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:embedFonts * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="embedFonts", type="Boolean")] - + [Style(name="embedFonts", type="Boolean")] + /** * The TextInput component is a single-line text component that * contains a native ActionScript TextField object. * *

    A TextInput component can be enabled or disabled in an application. * When the TextInput component is disabled, it cannot receive input * from mouse or keyboard. An enabled TextInput component implements focus, * selection, and navigation like an ActionScript TextField object.

    * *

    You can use styles to customize the TextInput component by * changing its appearance--for example, when it is disabled. * Some other customizations that you can apply to this component * include formatting it with HTML or setting it to be a * password field whose text must be hidden.

    * * @includeExample examples/TextInputExample.as * * @see TextArea * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class TextInput extends UIComponent implements IFocusManagerComponent - { + public class TextInput extends UIComponent implements IFocusManagerComponent + { /** * A reference to the internal text field of the TextInput component. * * @includeExample examples/TextInput.textField.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var textField : TextField; + public var textField : TextField; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _editable : Boolean; + protected var _editable : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var background : DisplayObject; + protected var background : DisplayObject; /** * @private (protected) */ - protected var _html : Boolean; + protected var _html : Boolean; /** * @private (protected) */ - protected var _savedHTML : String; + protected var _savedHTML : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * * The method to be used to create the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * Gets or sets a string which contains the text that is currently in * the TextInput component. This property contains text that is unformatted * and does not have HTML tags. To retrieve this text formatted as HTML, use * the htmlText property. * * @default "" * * @see #htmlText * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get text () : String; + public function get text () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set text (value:String) : void; + public function set text (value:String) : void; /** * @copy fl.core.UIComponent#enabled * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get enabled () : Boolean; + public function get enabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * @copy fl.controls.TextArea#imeMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get imeMode () : String; + public function get imeMode () : String; /** * @private (protected) */ - public function set imeMode (value:String) : void; + public function set imeMode (value:String) : void; /** * Gets or sets a Boolean value that indicates how a selection is * displayed when the text field does not have focus. * *

    When this value is set to true and the text field does * not have focus, Flash Player highlights the selection in the text field * in gray. When this value is set to false and the text field * does not have focus, Flash Player does not highlight the selection in the * text field.

    * * @default false * * @includeExample examples/TextInput.setSelection.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get alwaysShowSelection () : Boolean; + public function get alwaysShowSelection () : Boolean; /** * @private (setter) */ - public function set alwaysShowSelection (value:Boolean) : void; + public function set alwaysShowSelection (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether the text field * can be edited by the user. A value of true indicates * that the user can edit the text field; a value of false * indicates that the user cannot edit the text field. * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get editable () : Boolean; + public function get editable () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set editable (value:Boolean) : void; + public function set editable (value:Boolean) : void; /** * Gets or sets the position of the thumb of the horizontal scroll bar. * * @default 0 * * @includeExample examples/TextInput.horizontalScrollPosition.1.as -noswf * * @see #maxHorizontalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollPosition () : int; + public function get horizontalScrollPosition () : int; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalScrollPosition (value:int) : void; + public function set horizontalScrollPosition (value:int) : void; /** * Gets a value that describes the furthest position to which the text * field can be scrolled to the right. * * @default 0 * * @see #horizontalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxHorizontalScrollPosition () : int; + public function get maxHorizontalScrollPosition () : int; /** * Gets the number of characters in a TextInput component. * * @default 0 * * @includeExample examples/TextInput.maxChars.1.as -noswf * * @see #maxChars * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get length () : int; + public function get length () : int; /** * Gets or sets the maximum number of characters that a user can enter * in the text field. * * @default 0 * * @includeExample examples/TextInput.maxChars.1.as -noswf * * @see #length * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxChars () : int; + public function get maxChars () : int; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maxChars (value:int) : void; + public function set maxChars (value:int) : void; /** * Gets or sets a Boolean value that indicates whether the current TextInput * component instance was created to contain a password or to contain text. A value of * true indicates that the component instance is a password text * field; a value of false indicates that the component instance * is a normal text field. * *

    When this property is set to true, for each character that the * user enters into the text field, the TextInput component instance displays an asterisk. * Additionally, the Cut and Copy commands and their keyboard shortcuts are * disabled. These measures prevent the recovery of a password from an * unattended computer.

    * * @default false * * @includeExample examples/TextInput.displayAsPassword.1.as -noswf * * @see flash.text.TextField#displayAsPassword TextField.displayAsPassword * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get displayAsPassword () : Boolean; + public function get displayAsPassword () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set displayAsPassword (value:Boolean) : void; + public function set displayAsPassword (value:Boolean) : void; /** * Gets or sets the string of characters that the text field accepts from a user. * Note that characters that are not included in this string are accepted in the * text field if they are entered programmatically. * *

    The characters in the string are read from left to right. You can specify a * character range by using the hyphen (-) character.

    * *

    If the value of this property is null, the text field accepts all characters. * If this property is set to an empty string (""), the text field accepts no characters.

    * *

    If the string begins with a caret (^) character, all characters are initially * accepted and succeeding characters in the string are excluded from the set of * accepted characters. If the string does not begin with a caret (^) character, * no characters are initially accepted and succeeding characters in the string * are included in the set of accepted characters.

    * * @default null * * @see flash.text.TextField#restrict TextField.restrict * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get restrict () : String; + public function get restrict () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set restrict (value:String) : void; + public function set restrict (value:String) : void; /** * Gets the index value of the first selected character in a selection * of one or more characters. * *

    The index position of a selected character is zero-based and calculated * from the first character that appears in the text area. If there is no * selection, this value is set to the position of the caret.

    * * @default 0 * * @includeExample examples/TextInput.selectionBeginIndex.1.as -noswf * * @see #selectionEndIndex * @see #setSelection() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectionBeginIndex () : int; + public function get selectionBeginIndex () : int; /** * Gets the index position of the last selected character in a selection * of one or more characters. * *

    The index position of a selected character is zero-based and calculated * from the first character that appears in the text area. If there is no * selection, this value is set to the position of the caret.

    * * @default 0 * * @see #selectionBeginIndex * @see #setSelection() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selectionEndIndex () : int; + public function get selectionEndIndex () : int; /** * Gets or sets a Boolean value that indicates whether extra white space is * removed from a TextInput component that contains HTML text. Examples * of extra white space in the component include spaces and line breaks. * A value of true indicates that extra * white space is removed; a value of false indicates that extra * white space is not removed. * *

    This property affects only text that is set by using the htmlText * property; it does not affect text that is set by using the text property. * If you use the text property to set text, the condenseWhite * property is ignored.

    * *

    If the condenseWhite property is set to true, you * must use standard HTML commands, such as <br> and <p>, to place line * breaks in the text field.

    * * @default false * * @see flash.text.TextField#condenseWhite TextField.condenseWhite * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get condenseWhite () : Boolean; + public function get condenseWhite () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set condenseWhite (value:Boolean) : void; + public function set condenseWhite (value:Boolean) : void; /** * Contains the HTML representation of the string that the text field contains. * * @default "" * * @includeExample examples/TextInput.htmlText.1.as -noswf * * @see #text * @see flash.text.TextField#htmlText * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get htmlText () : String; + public function get htmlText () : String; /** * @private (setter) */ - public function set htmlText (value:String) : void; + public function set htmlText (value:String) : void; /** * The height of the text, in pixels. * * @default 0 * * @see #textWidth * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] What is the "height" of the text? Is this the vertical size of the text field that contains the text? * Same for the textWidth property below. */ - public function get textHeight () : Number; + public function get textHeight () : Number; /** * The width of the text, in pixels. * * @default 0 * * @includeExample examples/TextInput.textWidth.1.as -noswf * * @see #textHeight * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get textWidth () : Number; - + public function get textWidth () : Number; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new TextInput component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function TextInput (); + public function TextInput (); /** * @copy fl.core.UIComponent#drawFocus() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawFocus (draw:Boolean) : void; + public function drawFocus (draw:Boolean) : void; /** * Sets the range of a selection made in a text area that has focus. * The selection range begins at the index that is specified by the start * parameter, and ends at the index that is specified by the end parameter. * If the parameter values that specify the selection range are the same, * this method sets the text insertion point in the same way that the * caretIndex property does. * *

    The selected text is treated as a zero-based string of characters in which * the first selected character is located at index 0, the second * character at index 1, and so on.

    * *

    This method has no effect if the text field does not have focus.

    * * @param beginIndex The index location of the first character in the selection. * * @param endIndex The index location of the last character in the selection. * * @includeExample examples/TextInput.setSelection.1.as -noswf * @includeExample examples/TextInput.setSelection.2.as -noswf * * @see #selectionBeginIndex * @see #selectionEndIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSelection (beginIndex:int, endIndex:int) : void; + public function setSelection (beginIndex:int, endIndex:int) : void; /** * Retrieves information about a specified line of text. * * @param lineIndex The line number for which information is to be retrieved. * * @includeExample examples/TextInput.getLineMetrics.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getLineMetrics (index:int) : TextLineMetrics; + public function getLineMetrics (index:int) : TextLineMetrics; /** * Appends the specified string after the last character that the TextArea * contains. This method is more efficient than concatenating two strings * by using an addition assignment on a text property; for example, * myTextArea.text += moreText. This method is particularly * useful when the TextArea component contains a significant amount of * content. * * @param text The string to be appended to the existing text. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function appendText (text:String) : void; + public function appendText (text:String) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateTextFieldType () : void; + protected function updateTextFieldType () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleKeyDown (event:KeyboardEvent) : void; + protected function handleKeyDown (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleChange (event:Event) : void; + protected function handleChange (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleTextInput (event:TextEvent) : void; + protected function handleTextInput (event:TextEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setEmbedFont (); + protected function setEmbedFont (); /** * @private (protected) */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBackground () : void; + protected function drawBackground () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawTextFormat () : void; + protected function drawTextFormat () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setFocus () : void; + public function setFocus () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function isOurFocus (target:DisplayObject) : Boolean; + protected function isOurFocus (target:DisplayObject) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusInHandler (event:FocusEvent) : void; + protected function focusInHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusOutHandler (event:FocusEvent) : void; - } -} + protected function focusOutHandler (event:FocusEvent) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TileList.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TileList.as index 621fb299c9..a496cd8300 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TileList.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/TileList.as @@ -1,314 +1,314 @@ -package fl.controls -{ - import fl.controls.listClasses.CellRenderer; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.listClasses.ImageCell; - import fl.controls.listClasses.ListData; - import fl.controls.listClasses.TileListData; - import fl.controls.ScrollBar; - import fl.controls.ScrollBarDirection; - import fl.controls.ScrollPolicy; - import fl.controls.SelectableList; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.data.DataProvider; - import fl.data.TileListCollectionItem; - import fl.events.DataChangeEvent; - import fl.events.DataChangeType; - import fl.events.ListEvent; - import fl.events.ScrollEvent; - import fl.managers.IFocusManagerComponent; - import flash.display.DisplayObject; - import flash.display.Sprite; - import flash.events.MouseEvent; - import flash.events.Event; - import flash.events.KeyboardEvent; - import flash.ui.Keyboard; - import flash.utils.Dictionary; - +package fl.controls +{ + import fl.controls.listClasses.CellRenderer; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.listClasses.ImageCell; + import fl.controls.listClasses.ListData; + import fl.controls.listClasses.TileListData; + import fl.controls.ScrollBar; + import fl.controls.ScrollBarDirection; + import fl.controls.ScrollPolicy; + import fl.controls.SelectableList; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.data.DataProvider; + import fl.data.TileListCollectionItem; + import fl.events.DataChangeEvent; + import fl.events.DataChangeType; + import fl.events.ListEvent; + import fl.events.ScrollEvent; + import fl.managers.IFocusManagerComponent; + import flash.display.DisplayObject; + import flash.display.Sprite; + import flash.events.MouseEvent; + import flash.events.Event; + import flash.events.KeyboardEvent; + import flash.ui.Keyboard; + import flash.utils.Dictionary; + /** * The skin to be used as the background of the TileList component. * * @default TileList_skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="skin", type="Class")] + [Style(name="skin", type="Class")] /** * The cell renderer to be used to render each item in the TileList component. * * @default fl.contols.listClasses.ImageCell * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="cellRenderer", type="Class")] - + [Style(name="cellRenderer", type="Class")] + /** * The TileList class provides a grid of rows and columns that is typically used * to format and display images in a "tiled" format. The default cell renderer for * this component is the ImageCell class. An ImageCell cell renderer displays a * thumbnail image and a single-line label. To render a list-based cell in a * TileList component, use the CellRenderer class. * *

    To modify the padding that separates the cell border from the image, you * can globally set the imagePadding style, or set it on the ImageCell * class. Like other cell styles, the imagePadding style cannot be * set on the TileList component instance.

    * * @see fl.controls.listClasses.CellRenderer * @see fl.controls.listClasses.ImageCell * * @includeExample examples/TileListExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class TileList extends SelectableList implements IFocusManagerComponent - { + public class TileList extends SelectableList implements IFocusManagerComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _rowHeight : Number; + protected var _rowHeight : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _columnWidth : Number; + protected var _columnWidth : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _scrollDirection : String; + protected var _scrollDirection : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _scrollPolicy : String; + protected var _scrollPolicy : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _cellRenderer : Object; + protected var _cellRenderer : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var oldLength : uint; + protected var oldLength : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _labelField : String; + protected var _labelField : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _labelFunction : Function; + protected var _labelFunction : Function; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _iconField : String; + protected var _iconField : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _iconFunction : Function; + protected var _iconFunction : Function; /** * @private (protected) */ - protected var _sourceField : String; + protected var _sourceField : String; /** * @private (protected) */ - protected var _sourceFunction : Function; + protected var _sourceFunction : Function; /** * @private (protected) */ - protected var __rowCount : uint; + protected var __rowCount : uint; /** * @private (protected) */ - protected var __columnCount : uint; + protected var __columnCount : uint; /** * @private */ - private var collectionItemImport : TileListCollectionItem; + private var collectionItemImport : TileListCollectionItem; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * Method for creating the Accessibility class. * This method is called from UIComponent. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * @copy fl.controls.SelectableList#dataProvider * * @includeExample examples/TileList.dataProvider.1.as -noswf * @includeExample examples/TileList.dataProvider.2.as -noswf * @includeExample examples/TileList.dataProvider.3.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get dataProvider () : DataProvider; + public function get dataProvider () : DataProvider; /** * @private (setter) */ - public function set dataProvider (value:DataProvider) : void; + public function set dataProvider (value:DataProvider) : void; /** * Gets or sets a field in each item that contains a label for each tile. * *

    Note: The labelField is not used if * the labelFunction property is set to a callback function.

    * * @default "label" * * @includeExample examples/TileList.labelField.1.as -noswf * * @see #labelFunction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelField () : String; + public function get labelField () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelField (value:String) : void; + public function set labelField (value:String) : void; /** * Gets a function that indicates the fields of an item that provide the label text for a tile. * *

    Note: The labelField is not used if * the labelFunction property is set to a callback function.

    * * @default null * * @includeExample examples/TileList.labelFunction.1.as -noswf * * @see #labelField * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelFunction () : Function; + public function get labelFunction () : Function; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelFunction (value:Function) : void; + public function set labelFunction (value:Function) : void; /** * Gets or sets the item field that provides the icon for the item. * *

    Note: The iconField is not used * if the iconFunction property is set to a callback function.

    * *

    Icons can be classes or they can be symbols from the library that have a class name.

    * * @default null * * @includeExample examples/TileList.iconField.1.as -noswf * * @see #iconFunction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get iconField () : String; + public function get iconField () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set iconField (value:String) : void; + public function set iconField (value:String) : void; /** * Gets or sets the function to be used to obtain the icon for the item. * *

    Note: The iconField is not used if the * iconFunction property is set to a callback function.

    * *

    Icons can be classes, or they can be library items that have class names.

    * * @default null * * @includeExample examples/TileList.iconFunction.1.as -noswf * * @see #iconField * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get iconFunction () : Function; + public function get iconFunction () : Function; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set iconFunction (value:Function) : void; + public function set iconFunction (value:Function) : void; /** * Gets or sets the item field that provides the source path for a tile. * *

    Note: The sourceField is not used if the * sourceFunction property is set to a callback function.

    * * @default "source" * * @includeExample examples/TileList.sourceField.1.as -noswf * * @see #sourceFunction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - public function get sourceField () : String; + public function get sourceField () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set sourceField (value:String) : void; + public function set sourceField (value:String) : void; /** * Gets or sets the function to be used to obtain the source path for a tile. * *

    Note: The sourceField is not used if the * sourceFunction property is set to a callback function.

    * * @default null * * @includeExample examples/TileList.sourceFunction.1.as -noswf * * @see #sourceField * * @internal [peter] Check with Metaliq that this is still accurate. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get sourceFunction () : Function; + public function get sourceFunction () : Function; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set sourceFunction (value:Function) : void; + public function set sourceFunction (value:Function) : void; /** * Gets or sets the number of rows that are at least partially visible * in the list. * *

    Setting the rowCount property changes the height of the * list, but the TileList component does not maintain this value. It * is important to set the rowCount value after setting the * dataProvider and rowHeight values. The only * exception is if the rowCount is set with the Property * inspector; in this case, the property is maintained until the component * is first drawn.

    * * @default 0 * * @includeExample examples/TileList.rowCount.1.as -noswf * * @see #columnCount * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowCount () : uint; + public function get rowCount () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set rowCount (value:uint) : void; + public function set rowCount (value:uint) : void; /** * Gets or sets the height that is applied to each row in the list, in pixels. * * @default 50 * * @includeExample examples/TileList.rowHeight.1.as -noswf * * @see #columnWidth * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowHeight () : Number; + public function get rowHeight () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set rowHeight (value:Number) : void; + public function set rowHeight (value:Number) : void; /** * Gets or sets the number of columns that are at least partially visible in the * list. Setting the columnCount property changes the width of the list, * but the TileList component does not maintain this value. It is important to set the * columnCount value after setting the dataProvider * and rowHeight values. The only exception is if the rowCount * is set with the Property inspector; in this case, the property is maintained until the * component is first drawn. * * @default 0 * * @includeExample examples/TileList.columnCount.1.as -noswf * * @see #rowCount * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get columnCount () : uint; + public function get columnCount () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set columnCount (value:uint) : void; + public function set columnCount (value:uint) : void; /** * Gets or sets the width that is applied to a column in the list, in pixels. * * @default 50 * * @includeExample examples/TileList.columnWidth.1.as -noswf * * @see #rowHeight * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get columnWidth () : Number; + public function get columnWidth () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set columnWidth (value:Number) : void; + public function set columnWidth (value:Number) : void; /** * Gets the width of the content area, in pixels. This value is the component width * minus the combined width of the contentPadding value and vertical scroll bar, * if the vertical scroll bar is visible. * * @includeExample examples/TileList.innerWidth.1.as -noswf * * @see #innerHeight * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get innerWidth () : Number; + public function get innerWidth () : Number; /** * Gets the height of the content area, in pixels. This value is the component height * minus the combined height of the contentPadding value and horizontal * scroll bar height, if the horizontal scroll bar is visible. * * @see #innerWidth * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get innerHeight () : Number; + public function get innerHeight () : Number; /** * Gets or sets a value that indicates whether the TileList component scrolls * horizontally or vertically. A value of ScrollBarDirection.HORIZONTAL * indicates that the TileList component scrolls horizontally; a value of * ScrollBarDirection.VERTICAL indicates that the TileList component scrolls vertically. * * @default ScrollBarDirection.VERTICAL * * @includeExample examples/TileList.direction.1.as -noswf * * @see ScrollBarDirection * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get direction () : String; + public function get direction () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set direction (value:String) : void; + public function set direction (value:String) : void; /** * Gets or sets the scroll policy for the TileList component. This * value is used to specify the scroll policy for the scroll bar that * is set by the direction property. * *

    Note: The TileList component supports scrolling only in * one direction. Tiles are adjusted to fit into the viewable area of * the component, so that tiles are hidden in only one direction.

    * *

    The TileList component resizes to fit tiles only when the user * manually sets the size or when the user sets the rowCount * or columnCount properties.

    * *

    When this value is set to ScrollPolicy.AUTO, the * scroll bar is visible only when the TileList component must scroll * to show all the items.

    * * @default ScrollPolicy.AUTO * * @includeExample examples/TileList.scrollPolicy.1.as -noswf * * @see #columnCount * @see #rowCount * @see ScrollPolicy * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scrollPolicy () : String; + public function get scrollPolicy () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scrollPolicy (value:String) : void; + public function set scrollPolicy (value:String) : void; /** * @private (hidden) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get verticalScrollPolicy () : String; + public function get verticalScrollPolicy () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set verticalScrollPolicy (value:String) : void; + public function set verticalScrollPolicy (value:String) : void; /** * @private (hidden) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get horizontalScrollPolicy () : String; + public function get horizontalScrollPolicy () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set horizontalScrollPolicy (value:String) : void; + public function set horizontalScrollPolicy (value:String) : void; /** * Gets the maximum horizontal scroll position for the current content, in pixels. * * @see fl.containers.BaseScrollPane#horizontalScrollPosition * @see fl.containers.BaseScrollPane#maxVerticalScrollPosition * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get maxHorizontalScrollPosition () : Number; + public function get maxHorizontalScrollPosition () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maxHorizontalScrollPosition (value:Number) : void; - + public function set maxHorizontalScrollPosition (value:Number) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new List component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function TileList (); + public function TileList (); /** * @copy fl.controls.SelectableList#scrollToIndex() * * @includeExample examples/TileList.scrollToIndex.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function scrollToIndex (newCaretIndex:int) : void; + public function scrollToIndex (newCaretIndex:int) : void; /** * Retrieves the string that the renderer displays for a given data object * based on the labelField and labelFunction properties. * * @param item The Object to be rendered. * * @return The string to be displayed based on the data. * * @internal var label:String = myTileList.itemToLabel(data); * * @see #labelField * @see #labelFunction * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function itemToLabel (item:Object) : String; + public function itemToLabel (item:Object) : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setHorizontalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setHorizontalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; + protected function setVerticalScrollPosition (scroll:Number, fireEvent:Boolean = false) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawList () : void; + protected function drawList () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function calculateAvailableHeight () : Number; + protected function calculateAvailableHeight () : Number; /** * @private (protected) * Moves the selection in a vertical direction in response * to the user selecting items using the up-arrow or down-arrow * Keys and modifiers such as the Shift and Ctrl keys. * * @param code The key that was pressed (e.g. Keyboard.DOWN) * * @param shiftKey true if the shift key was held down when * the keyboard key was pressed. * * @param ctrlKey true if the ctrl key was held down when * the keyboard key was pressed * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function moveSelectionVertically (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function moveSelectionVertically (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * Moves the selection in a horizontal direction in response * to the user selecting items using the left-arrow or right-arrow * keys and modifiers such as the Shift and Ctrl keys. * *

    Not implemented in List because the default list * is single column and does not scroll horizontally.

    * * @param code The key that was pressed (e.g. Keyboard.LEFT) * * @param shiftKey true if the shift key was held down when * the keyboard key was pressed. * * @param ctrlKey true if the ctrl key was held down when * the keyboard key was pressed * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function moveSelectionHorizontally (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function moveSelectionHorizontally (code:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * Changes the selected index, or adds or subtracts the index and * all indices between when the shift key is used. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function doKeySelection (newCaretIndex:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; + protected function doKeySelection (newCaretIndex:uint, shiftKey:Boolean, ctrlKey:Boolean) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; - } -} + protected function initializeAccessibility () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/UIScrollBar.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/UIScrollBar.as index 699664c839..7894d4b417 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/UIScrollBar.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/UIScrollBar.as @@ -1,109 +1,109 @@ -package fl.controls -{ - import Error; - import fl.controls.ScrollBar; - import fl.controls.ScrollBarDirection; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import fl.events.ScrollEvent; - import flash.events.Event; - import flash.events.TextEvent; - import flash.text.TextField; - +package fl.controls +{ + import Error; + import fl.controls.ScrollBar; + import fl.controls.ScrollBarDirection; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import fl.events.ScrollEvent; + import flash.events.Event; + import flash.events.TextEvent; + import flash.text.TextField; + /** * The UIScrollBar class includes all of the scroll bar functionality, but * adds a scrollTarget() method so it can be attached * to a TextField component instance. * *

    Note: When you use ActionScript to update properties of * the TextField component that affect the text layout, you must call the * update() method on the UIScrollBar component instance to refresh its scroll * properties. Examples of text layout properties that belong to the TextField * component include width, height, and wordWrap.

    * * @includeExample examples/UIScrollBarExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class UIScrollBar extends ScrollBar - { + public class UIScrollBar extends ScrollBar + { /** * @private (private) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _scrollTarget : TextField; + protected var _scrollTarget : TextField; /** * @private (private) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var inEdit : Boolean; + protected var inEdit : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var inScroll : Boolean; + protected var inScroll : Boolean; /** * @private */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set minScrollPosition (minScrollPosition:Number) : void; + public function set minScrollPosition (minScrollPosition:Number) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set maxScrollPosition (maxScrollPosition:Number) : void; + public function set maxScrollPosition (maxScrollPosition:Number) : void; /** * Registers a TextField component instance with the ScrollBar component instance. * * @includeExample examples/UIScrollBar.scrollTarget.1.as -noswf * * @see #update() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scrollTarget () : TextField; + public function get scrollTarget () : TextField; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scrollTarget (target:TextField) : void; + public function set scrollTarget (target:TextField) : void; /** * @private (internal) * @internal For specifying in inspectable, and setting dropTarget * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scrollTargetName () : String; + public function get scrollTargetName () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scrollTargetName (target:String) : void; + public function set scrollTargetName (target:String) : void; /** * @copy fl.controls.ScrollBar#direction * * @default ScrollBarDirection.VERTICAL * * @includeExample examples/UIScrollBar.direction.1.as -noswf * @includeExample examples/UIScrollBar.direction.2.as -noswf * * @see ScrollBarDirection * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get direction () : String; + public function get direction () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set direction (dir:String) : void; - + public function set direction (dir:String) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new UIScrollBar component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function UIScrollBar (); + public function UIScrollBar (); /** * Forces the scroll bar to update its scroll properties immediately. * This is necessary after text in the specified scrollTarget text field * is added using ActionScript, and the scroll bar needs to be refreshed. * * @see #scrollTarget * * @includeExample examples/UIScrollBar.update.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function update () : void; + public function update () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateScrollTargetProperties () : void; + protected function updateScrollTargetProperties () : void; /** * @copy fl.controls.ScrollBar#setScrollProperties() * * @see ScrollBar#pageSize ScrollBar.pageSize * @see ScrollBar#minScrollPosition ScrollBar.minScrollPosition * @see ScrollBar#maxScrollPosition ScrollBar.maxScrollPosition * @see ScrollBar#pageScrollSize ScrollBar.pageScrollSize * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setScrollProperties (pageSize:Number, minScrollPosition:Number, maxScrollPosition:Number, pageScrollSize:Number = 0) : void; + public function setScrollProperties (pageSize:Number, minScrollPosition:Number, maxScrollPosition:Number, pageScrollSize:Number = 0) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setScrollPosition (scrollPosition:Number, fireEvent:Boolean = true) : void; + public function setScrollPosition (scrollPosition:Number, fireEvent:Boolean = true) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function updateTargetScroll (event:ScrollEvent = null) : void; + protected function updateTargetScroll (event:ScrollEvent = null) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleTargetChange (event:Event) : void; + protected function handleTargetChange (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleTargetScroll (event:Event) : void; - } -} + protected function handleTargetScroll (event:Event) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/DataGridCellEditor.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/DataGridCellEditor.as index 2cbe0aff15..0ed44ca211 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/DataGridCellEditor.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/DataGridCellEditor.as @@ -1,80 +1,80 @@ -package fl.controls.dataGridClasses -{ - import fl.controls.LabelButton; - import fl.controls.listClasses.ListData; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.TextInput; - import fl.core.UIComponent; - import flash.events.Event; - import flash.events.MouseEvent; - +package fl.controls.dataGridClasses +{ + import fl.controls.LabelButton; + import fl.controls.listClasses.ListData; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.TextInput; + import fl.core.UIComponent; + import flash.events.Event; + import flash.events.MouseEvent; + /** * @copy fl.core.UIComponent#style:textFormat * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textFormat", type="flash.text.TextFormat")] + [Style(name="textFormat", type="flash.text.TextFormat")] /** * Name of the class to use as the skin for the background and border * of the DataGridCellEditor. * * @default DataGridCellEditor_skin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:textPadding * * @default 1 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] - + [Style(name="textPadding", type="Number", format="Length")] + /** * The DataGridCellEditor class defines the default item editor for a * DataGrid control. You can override the default item editor by subclassing * the DataGridCellEditor class, or by creating your own cell editor class. * * @see fl.controls.listClasses.ICellRenderer * * @includeExample examples/DataGridCellEditorExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataGridCellEditor extends TextInput implements ICellRenderer - { + public class DataGridCellEditor extends TextInput implements ICellRenderer + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _listData : ListData; + protected var _listData : ListData; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _data : Object; + protected var _data : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * @copy fl.controls.listClasses.ICellRenderer#listData * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get listData () : ListData; + public function get listData () : ListData; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set listData (value:ListData) : void; + public function set listData (value:ListData) : void; /** * @copy fl.controls.listClasses.ICellRenderer#data * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get data () : Object; + public function get data () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set data (value:Object) : void; + public function set data (value:Object) : void; /** * Indicates whether the cell is included in the * indices that were selected by the owner. A value of true indicates * that the cell is included in the specified indices; a value of false * indicates that it is not. * *

    Note that this value cannot be changed in the DataGrid. * The DataGridCellEditor class implements the ICellRenderer interface, which specifies * that this value must be defined.

    * * @default false * * @see fl.controls.listClasses.ICellRenderer ICellRenderer * * @internal [kenos] If the getter always returns false, shouldn't we say so? I'd like to add such a sentence to the end * of the first paragraph. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selected () : Boolean; + public function get selected () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selected (value:Boolean) : void; - + public function set selected (value:Boolean) : void; + /** * Creates a new DataGridCellEditor instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function DataGridCellEditor (); + public function DataGridCellEditor (); /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * @copy fl.controls.listClasses.ICellRenderer#setMouseState() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setMouseState (state:String) : void; - } -} + public function setMouseState (state:String) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/DataGridColumn.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/DataGridColumn.as index 355105645e..97d0dd75fe 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/DataGridColumn.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/DataGridColumn.as @@ -1,192 +1,192 @@ -package fl.controls.dataGridClasses -{ - import fl.controls.DataGrid; - import fl.controls.listClasses.ICellRenderer; - import fl.core.InvalidationType; - import fl.controls.dataGridClasses.DataGridCellEditor; - +package fl.controls.dataGridClasses +{ + import fl.controls.DataGrid; + import fl.controls.listClasses.ICellRenderer; + import fl.core.InvalidationType; + import fl.controls.dataGridClasses.DataGridCellEditor; + /** * The DataGridColumn class describes a column in a DataGrid component. There * is one DataGridColumn object for every column that could be displayed on * the screen, even for columns that are currently hidden or off-screen. The * data provider items that belong to a DataGrid component can contain properties * that are not displayed; such properties do not require a DataGridColumn. * *

    You can specify the kind of component that displays the data for a DataGridColumn. * The characteristics that can be specified include the text that appears in the * column header and whether the column can be edited, sorted, or resized.

    * * @see fl.controls.DataGrid * * @includeExample examples/DataGridColumnExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataGridColumn - { + public class DataGridColumn + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _columnName : String; + private var _columnName : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _headerText : String; + private var _headerText : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _minWidth : Number; + private var _minWidth : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _width : Number; + private var _width : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _visible : Boolean; + private var _visible : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _cellRenderer : Object; + private var _cellRenderer : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _headerRenderer : Object; + private var _headerRenderer : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _labelFunction : Function; + private var _labelFunction : Function; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _sortCompareFunction : Function; + private var _sortCompareFunction : Function; /** * @private * Storage for the imeMode property. */ - private var _imeMode : String; + private var _imeMode : String; /** * @private (internal) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var owner : DataGrid; + public var owner : DataGrid; /** * @private (internal) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var colNum : Number; + public var colNum : Number; /** * @private (internal) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var explicitWidth : Number; + public var explicitWidth : Number; /** * Indicates whether the user can click on the header of the current column * to sort the data provider. A value of true indicates that * the column can be sorted by clicking on its header; a value of false * indicates that it cannot be sorted by clicking on its header. * * @default true * * @includeExample examples/DataGridColumn.sortable.1.as -noswf * @includeExample examples/DataGridColumn.sortable.2.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var sortable : Boolean; + public var sortable : Boolean; /** * Indicates whether the user is allowed to change the width of the * column. A value of true indicates that the user can * change the column width; a value of false indicates that * the user cannot change the column width. * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var resizable : Boolean; + public var resizable : Boolean; /** * Indicates whether the items in the column can be edited. A value of true * indicates that the column items can be edited; a value of false indicates * that they cannot be edited. * *

    If this property is set to true and the editable * property of the DataGrid is also true, the items in a column are * editable and can be individually edited by clicking an item * or by navigating to the item by using the Tab and arrow keys.

    * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var editable : Boolean; + public var editable : Boolean; /** * Indicates the class of the instances of the item editor to use for the * column, when it is editable. * * The type of this property can be Class, Sprite or String. * If the property type is String, the string value must be a * fully qualified class name. * * @default "fl.controls.dataGridClasses.DataGridCellEditor" * * @includeExample examples/DataGridColumn.itemEditor.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var itemEditor : Object; + public var itemEditor : Object; /** * Identifies the name of the property of the item editor that contains the new * data for the list item. * *

    For example, the default itemEditor is * TextInput, so the default value of the editorDataField * property is "text". This value specifies the * text property of the TextInput component.

    * * @default "text" * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var editorDataField : String; + public var editorDataField : String; /** * Identifies the name of the field or property in the data provider item * that is associated with the column. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var dataField : String; + public var dataField : String; /** * Indicates whether the DataGridColumn is to be sorted in ascending or * descending order. A value of true indicates that the * DataGridColumn is sorted in descending order; a value of false * indicates that the DataGridColum is sorted in ascending order. * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var sortDescending : Boolean; + public var sortDescending : Boolean; /** * One or more defined constants, identified by name or number and separated * by the bitwise OR (|) operator. These constants are used to specify * the sort operation. * * @default 0 * * @includeExample examples/DataGridColumn.sortOptions.1.as -noswf * * @see Array#sort() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var sortOptions : uint; + public var sortOptions : uint; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var forceImport : DataGridCellEditor; - + private var forceImport : DataGridCellEditor; + /** * The class that is used to render the items in this column. * * The type of this property can be Class, Sprite or String. * If the property type is String, the String value must be a * fully qualified class name. * * @default null * * @includeExample examples/DataGridColumn.cellRenderer.1.as -noswf * * @see #headerRenderer DataGridColumn.headerRenderer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get cellRenderer () : Object; + public function get cellRenderer () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set cellRenderer (value:Object) : void; + public function set cellRenderer (value:Object) : void; /** * The class that is used to render the header of this column. * *

    The type of this property can be Class, Sprite or String. * If the property type is String, the string value must be a * fully qualified class name.

    * * @default null * * @see #cellRenderer DataGridColumn.cellRenderer * @see HeaderRenderer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get headerRenderer () : Object; + public function get headerRenderer () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set headerRenderer (value:Object) : void; + public function set headerRenderer (value:Object) : void; /** * The column name to be displayed in the column header. * By default, the DataGrid component uses the value of the dataField * property as the column name. * * @includeExample examples/DataGridColumn.headerText.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get headerText () : String; + public function get headerText () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set headerText (value:String) : void; + public function set headerText (value:String) : void; /** * The mode of the input method editor (IME). The IME enables users to * enter text in Chinese, Japanese, and Korean. The flash.system.IMEConversionMode * class defines constants to be used as the valid values for this property. * *

    If this property is null, the mode of the IME is * set to the value of the imeMode property of the DataGrid * component.

    * * @default null * * @see flash.system.IMEConversionMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @internal [kenos] The IME probably allows users of a QWERTY keyboard to enter * characters from the Chinese, Japanese, and Korean *character sets*. You can * render Japanese words in Roman letters, if you like, on a QWERTY keyboard, * so the existing description here is probably not quite right. */ - public function get imeMode () : String; + public function get imeMode () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set imeMode (value:String) : void; + public function set imeMode (value:String) : void; /** * A function that determines the text to be displayed in this column. By default, the * column displays the text for the data field that matches the column name. * However, a column can also be used to display the text of more than one data field, * or to display content that is not in the proper format. This can be done by * using the labelFunction property to specify a callback function. * *

    If both the labelFunction and labelField properties * are defined, the labelFunction takes precedence.

    * * @default null * * @includeExample examples/DataGridColumn.labelFunction.1.as -noswf * @includeExample examples/DataGridColumn.sortCompareFunction.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get labelFunction () : Function; + public function get labelFunction () : Function; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set labelFunction (value:Function) : void; + public function set labelFunction (value:Function) : void; /** * The minimum width of the column, in pixels. * * @default 20 * * @includeExample examples/DataGridColumn.minWidth.1.as -noswf * * @see #width DataGridColumn.width * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get minWidth () : Number; + public function get minWidth () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set minWidth (value:Number) : void; + public function set minWidth (value:Number) : void; /** * A callback function that is called when sorting the data in * the column. If this property is not specified, the data is sorted by string * or number, depending on the sortOptions property. * When specified, the sortCompareFunction property allows you to create * your own custom sorting method for the current data grid column. * * @default null * * @see #sortOptions * * @includeExample examples/DataGridColumn.sortCompareFunction.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] More information here on what the callback is used to do? Sounds like * it supplants the sortOptions but is it used to specify any particular type of * sort? */ - public function get sortCompareFunction () : Function; + public function get sortCompareFunction () : Function; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set sortCompareFunction (value:Function) : void; + public function set sortCompareFunction (value:Function) : void; /** * Indicates whether the column is visible. A value of true indicates * that the column is visible; a value of false indicates that the column * is invisible. * * @includeExample examples/DataGridColumn.visible.1.as -noswf * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get visible () : Boolean; + public function get visible () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set visible (value:Boolean) : void; + public function set visible (value:Boolean) : void; /** * The width of the column, in pixels. * * @default 100 * * @see #minWidth DataGridColumn.minWidth * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get width () : Number; + public function get width () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set width (value:Number) : void; - + public function set width (value:Number) : void; + /** * Creates a new DataGridColumn instance. * * @param columnName The column name to display in the column header. If * no name is specified, the dataField value is used. * * @default null * * @see DataGridColumn#headerText * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function DataGridColumn (columnName:String = null); + public function DataGridColumn (columnName:String = null); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setWidth (value:Number) : void; + public function setWidth (value:Number) : void; /** * Returns the string that the item renderer displays for the given data object. * If the DataGridColumn or its DataGrid component has a non-null labelFunction * property, it applies the function to the data object. Otherwise, the method extracts * the contents of the field that is specified by the dataField property, or gets the * string value of the data object. If the method cannot convert the parameter to a string, * it returns a single space. * * @param data The Object to be rendered. * * @return Displayable string based on the specified data object. * * @internal * dg.addEventListener("itemClick", itemClickHandler); * function itemClickHandler(evt:ListEvent):void { * var col:DataGridColumn = dg.getColumnAt(evt.columnIndex); * trace(col.itemToLabel(evt.item)); * } * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function itemToLabel (data:Object) : String; + public function itemToLabel (data:Object) : String; /** * Returns a string representation of the DataGridColumn object. * * @return "[object DataGridColumn]" * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; - } -} + public function toString () : String; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/HeaderRenderer.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/HeaderRenderer.as index 412befcdd6..ae55b37c92 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/HeaderRenderer.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/dataGridClasses/HeaderRenderer.as @@ -1,62 +1,62 @@ -package fl.controls.dataGridClasses -{ - import fl.controls.ButtonLabelPlacement; - import fl.controls.LabelButton; - import fl.core.UIComponent; - import flash.events.Event; - import flash.events.MouseEvent; - +package fl.controls.dataGridClasses +{ + import fl.controls.ButtonLabelPlacement; + import fl.controls.LabelButton; + import fl.core.UIComponent; + import flash.events.Event; + import flash.events.MouseEvent; + /** * @copy fl.controls.LabelButton#style:selectedDisabledSkin * * @default HeaderRenderer_selectedDisabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDisabledSkin", type="Class")] + [Style(name="selectedDisabledSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedUpSkin * * @default HeaderRenderer_selectedUpSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedUpSkin", type="Class")] + [Style(name="selectedUpSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDownSkin * * @default HeaderRenderer_selectedDownSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDownSkin", type="Class")] + [Style(name="selectedDownSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedOverSkin * * @default HeaderRenderer_selectedOverSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedOverSkin", type="Class")] - + [Style(name="selectedOverSkin", type="Class")] + /** * The HeaderRenderer class displays the column header for the current * DataGrid column. This class extends the LabelButton class and adds a * column property that associates the current header with its * DataGrid column. * * @see fl.controls.DataGrid DataGrid * * @includeExample examples/HeaderRendererExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class HeaderRenderer extends LabelButton - { + public class HeaderRenderer extends LabelButton + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var _column : uint; + public var _column : uint; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * The index of the column that belongs to this HeaderRenderer instance. * *

    You do not need to know how to get or set this property * because it is internal. However, if you create your own * HeaderRenderer, be sure to expose it; the HeaderRenderer is used * by the DataGrid to maintain a reference between the header * and the related DataGridColumn.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal Adobe: [LM] Added more details. This *could* be marked (at)private. */ - public function get column () : uint; + public function get column () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set column (value:uint) : void; - + public function set column (value:uint) : void; + /** * Creates a new HeaderRenderer instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function HeaderRenderer (); + public function HeaderRenderer (); /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; - } -} + protected function drawLayout () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/CellRenderer.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/CellRenderer.as index 1c8eb63075..1c5529f8c6 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/CellRenderer.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/CellRenderer.as @@ -1,120 +1,120 @@ -package fl.controls.listClasses -{ - import fl.controls.ButtonLabelPlacement; - import fl.controls.listClasses.ListData; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.LabelButton; - import fl.core.UIComponent; - import flash.events.Event; - import flash.events.MouseEvent; - +package fl.controls.listClasses +{ + import fl.controls.ButtonLabelPlacement; + import fl.controls.listClasses.ListData; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.LabelButton; + import fl.core.UIComponent; + import flash.events.Event; + import flash.events.MouseEvent; + /** * @copy fl.controls.LabelButton#style:upSkin * * @default CellRenderer_upSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="upSkin", type="Class")] + [Style(name="upSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:downSkin * * @default CellRenderer_downSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="downSkin", type="Class")] + [Style(name="downSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:overSkin * * @default CellRenderer_overSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="overSkin", type="Class")] + [Style(name="overSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:disabledSkin * * @default CellRenderer_disabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledSkin", type="Class")] + [Style(name="disabledSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDisabledSkin * * @default CellRenderer_selectedDisabledSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDisabledSkin", type="Class")] + [Style(name="selectedDisabledSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedUpSkin * * @default CellRenderer_selectedUpSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedUpSkin", type="Class")] + [Style(name="selectedUpSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedDownSkin * * @default CellRenderer_selectedDownSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedDownSkin", type="Class")] + [Style(name="selectedDownSkin", type="Class")] /** * @copy fl.controls.LabelButton#style:selectedOverSkin * * @default CellRenderer_selectedOverSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedOverSkin", type="Class")] + [Style(name="selectedOverSkin", type="Class")] /** * @copy fl.core.UIComponent#style:textFormat * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textFormat", type="flash.text.TextFormat")] + [Style(name="textFormat", type="flash.text.TextFormat")] /** * @copy fl.core.UIComponent#style:disabledTextFormat * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledTextFormat", type="flash.text.TextFormat")] + [Style(name="disabledTextFormat", type="flash.text.TextFormat")] /** * @copy fl.controls.LabelButton#style:textPadding * * @default 5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] - + [Style(name="textPadding", type="Number", format="Length")] + /** * The CellRenderer class defines methods and properties for * list-based components to use to manipulate and display custom * cell content in each of their rows. A customized cell can contain * text, an existing component such as a CheckBox, or any class that * you create. The list-based components that use this class include * the List, DataGrid, TileList, and ComboBox components. * * @see ICellRenderer * * @includeExample examples/CellRendererExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class CellRenderer extends LabelButton implements ICellRenderer - { + public class CellRenderer extends LabelButton implements ICellRenderer + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _listData : ListData; + protected var _listData : ListData; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _data : Object; + protected var _data : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * @copy fl.controls.listClasses.ICellRenderer#listData * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get listData () : ListData; + public function get listData () : ListData; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set listData (value:ListData) : void; + public function set listData (value:ListData) : void; /** * @copy fl.controls.listClasses.ICellRenderer#data * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get data () : Object; + public function get data () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set data (value:Object) : void; + public function set data (value:Object) : void; /** * @copy fl.controls.listClasses.ICellRenderer#selected * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selected () : Boolean; + public function get selected () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selected (value:Boolean) : void; - + public function set selected (value:Boolean) : void; + /** * Creates a new CellRenderer instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function CellRenderer (); + public function CellRenderer (); /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Specifies the dimensions at which the data should be rendered. * These dimensions affect both the data and the cell that contains it; * the cell renderer uses them to ensure that the data fits the cell and * does not bleed into adjacent cells. * * @param width The width of the object, in pixels. * * @param height The height of the object, in pixels. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSize (width:Number, height:Number) : void; + public function setSize (width:Number, height:Number) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function toggleSelected (event:MouseEvent) : void; + protected function toggleSelected (event:MouseEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; - } -} + protected function drawLayout () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ICellRenderer.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ICellRenderer.as index 38b474235e..09bf306dbd 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ICellRenderer.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ICellRenderer.as @@ -1,52 +1,52 @@ -package fl.controls.listClasses -{ - import fl.controls.listClasses.ListData; - +package fl.controls.listClasses +{ + import fl.controls.listClasses.ListData; + /** * The ICellRenderer interface provides the methods and properties that a cell renderer requires. * All user defined cell renderers should implement this interface. All user defined cell renderers * must extend either the UIComponent class or a subclass of the UIComponent class. * * @includeExample examples/ICellRendererExample.as -noswf * @includeExample examples/MyRenderer.as * * @see CellRenderer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public interface ICellRenderer - { + public interface ICellRenderer + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set y (y:Number) : void; + public function set y (y:Number) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set x (x:Number) : void; + public function set x (x:Number) : void; /** * Gets or sets the list properties that are applied to the cell--for example, * the index and selected values. These list properties * are automatically updated after the cell is invalidated. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get listData () : ListData; + public function get listData () : ListData; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set listData (value:ListData) : void; + public function set listData (value:ListData) : void; /** * Gets or sets an Object that represents the data that is * associated with a component. When this value is set, the * component data is stored and the containing component is * invalidated. The invalidated component is then automatically * redrawn. * *

    The data property represents an object containing the item * in the DataProvider that the cell represents. Typically, the * data property contains standard properties, depending on the * component type. In CellRenderer in a List or ComboBox component * the data contains a label, icon, and data properties; a TileList: a * label and a source property; a DataGrid cell contains values * for each column. The data property can also contain user-specified * data relevant to the specific cell. Users can extend a CellRenderer * for a component to utilize different properties of the data * in the rendering of the cell.

    * *

    Additionally, the labelField, labelFunction, * iconField, iconFunction, sourceField, * and sourceFunction elements can be used to specify which properties * are used to draw the label, icon, and source respectively.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get data () : Object; + public function get data () : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set data (value:Object) : void; + public function set data (value:Object) : void; /** * Gets or sets a Boolean value that indicates whether the * current cell is selected. A value of true indicates * that the current cell is selected; a value of false * indicates that it is not. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selected () : Boolean; + public function get selected () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selected (value:Boolean) : void; - + public function set selected (value:Boolean) : void; + /** * Sets the size of the data according to the pixel values specified by the width * and height parameters. * * @param width The width to display the cell renderer at, in pixels. * * @param height The height to display the cell renderer at, in pixels. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSize (width:Number, height:Number) : void; + public function setSize (width:Number, height:Number) : void; /** * Sets the current cell to a specific mouse state. This method * is necessary for the DataGrid to set the mouse state on an entire * row when the user interacts with a single cell. * * @param state A string that specifies a mouse state, such as "up" or "over". * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setMouseState (state:String) : void; - } -} + public function setMouseState (state:String) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ImageCell.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ImageCell.as index 548131788e..5de3c3b062 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ImageCell.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ImageCell.as @@ -1,92 +1,92 @@ -package fl.controls.listClasses -{ - import fl.controls.listClasses.CellRenderer; - import fl.controls.listClasses.ICellRenderer; - import fl.controls.listClasses.ListData; - import fl.controls.listClasses.TileListData; - import fl.controls.TextInput; - import fl.containers.UILoader; - import fl.core.InvalidationType; - import fl.core.UIComponent; - import flash.display.Graphics; - import flash.display.Shape; - import flash.events.IOErrorEvent; - +package fl.controls.listClasses +{ + import fl.controls.listClasses.CellRenderer; + import fl.controls.listClasses.ICellRenderer; + import fl.controls.listClasses.ListData; + import fl.controls.listClasses.TileListData; + import fl.controls.TextInput; + import fl.containers.UILoader; + import fl.core.InvalidationType; + import fl.core.UIComponent; + import flash.display.Graphics; + import flash.display.Shape; + import flash.events.IOErrorEvent; + /** * The skin that is used to indicate the selected state. * * @default ImageCell_selectedSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="selectedSkin", type="Class")] + [Style(name="selectedSkin", type="Class")] /** * The padding that separates the edge of the cell from the edge of the text, * in pixels. * * @default 3 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textPadding", type="Number", format="Length")] + [Style(name="textPadding", type="Number", format="Length")] /** * The padding that separates the edge of the cell from the edge of the image, * in pixels. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="imagePadding", type="Number", format="Length")] + [Style(name="imagePadding", type="Number", format="Length")] /** * The opacity of the overlay behind the cell label. * * @default 0.7 * */ - [Style(name="textOverlayAlpha", type="Number", format="Length")] - + [Style(name="textOverlayAlpha", type="Number", format="Length")] + /** * The ImageCell is the default cell renderer for the TileList * component. An ImageCell class accepts label and * source properties, and displays a thumbnail and * single-line label. * *

    Note: When content is being loaded from a different * domain or sandbox, the properties of the content may be inaccessible * for security reasons. For more information about how domain security * affects the load process, see the Loader class.

    * * @see flash.display.Loader Loader * * @includeExample examples/ImageCellExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ImageCell extends CellRenderer implements ICellRenderer - { + public class ImageCell extends CellRenderer implements ICellRenderer + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var textOverlay : Shape; + protected var textOverlay : Shape; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var loader : UILoader; + protected var loader : UILoader; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * Gets or sets the list properties that are applied to the cell, for example, * the index and selected values. These list properties * are automatically updated after the cell is invalidated. * *

    Although the listData property returns an instance of ListData, in the * TileList cells receive an instance of TileListData instead, * which contains a source property.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get listData () : ListData; + public function get listData () : ListData; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set listData (value:ListData) : void; + public function set listData (value:ListData) : void; /** * Gets or sets an absolute or relative URL that identifies the * location of the SWF or image file to load, the class name * of a movie clip in the library, or a reference to a display * object. * *

    Valid image file formats include GIF, PNG, and JPEG.

    * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get source () : Object; + public function get source () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set source (value:Object) : void; - + public function set source (value:Object) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new ImageCell instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ImageCell (); + public function ImageCell (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawLayout () : void; + protected function drawLayout () : void; /** * @private (protected) */ - protected function handleErrorEvent (event:IOErrorEvent) : void; - } -} + protected function handleErrorEvent (event:IOErrorEvent) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ListData.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ListData.as index 1daaaa638e..469d8a405c 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ListData.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/ListData.as @@ -1,65 +1,65 @@ -package fl.controls.listClasses -{ - import fl.core.UIComponent; - +package fl.controls.listClasses +{ + import fl.core.UIComponent; + /** * ListData is a messenger class that holds information relevant to a specific * cell in a list-based component. This information includes the label and icon that are * associated with the cell; whether or not the cell is selected; and the position of * the cell in the list by row and column. * *

    A new ListData component is created for a cell renderer * each time it is invalidated.

    * * @includeExample examples/ListDataExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ListData - { + public class ListData + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _icon : Object; + protected var _icon : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _label : String; + protected var _label : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _owner : UIComponent; + protected var _owner : UIComponent; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _index : uint; + protected var _index : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _row : uint; + protected var _row : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _column : uint; - + protected var _column : uint; + /** * The label to be displayed in the cell. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get label () : String; + public function get label () : String; /** * A class that represents the icon for the item in the List component, * computed from the List class method. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] I think this could be more clear. What is "computed" from the * List class method? Also not sure I understand what method the * "List class method" is. Is what is "computed" an array location * for the specified item? */ - public function get icon () : Object; + public function get icon () : Object; /** * A reference to the List object that owns this item. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get owner () : UIComponent; + public function get owner () : UIComponent; /** * The index of the item in the data provider. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get index () : uint; + public function get index () : uint; /** * The row in which the data item is displayed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get row () : uint; + public function get row () : uint; /** * The column in which the data item is displayed. In a list, * this value is always 0. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get column () : uint; - + public function get column () : uint; + /** * Creates a new instance of the ListData class as specified by its parameters. * * @param label The label to be displayed in this cell. * * @param icon The icon to be displayed in this cell. * * @param owner The component that owns this cell. * * @param index The index of the item in the data provider. * * @param row The row in which this item is being displayed. In a List or * DataGrid, this value corresponds to the index. In a TileList, this * value may be different than the index. * * @param col The column in which this item is being displayed. In a List, * this value is always 0. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ListData (label:String, icon:Object, owner:UIComponent, index:uint, row:uint, col:uint = 0); - } -} + public function ListData (label:String, icon:Object, owner:UIComponent, index:uint, row:uint, col:uint = 0); + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/TileListData.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/TileListData.as index 5e80d74543..e6505066dd 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/TileListData.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/listClasses/TileListData.as @@ -1,26 +1,26 @@ -package fl.controls.listClasses -{ - import fl.controls.listClasses.ListData; - import fl.core.UIComponent; - +package fl.controls.listClasses +{ + import fl.controls.listClasses.ListData; + import fl.core.UIComponent; + /** * TileListData is a messenger class that holds information relevant to a specific * cell in the list-based TileListData component. This information includes the label * and image source that are associated with the cell; whether or not the cell is selected; * and the position of the cell in the list by row and column. * *

    A new TileListData component is created for a cell renderer * each time it is invalidated.

    * * @see fl.controls.listClasses.ListData ListData * * @includeExample examples/TileListDataExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class TileListData extends ListData - { + public class TileListData extends ListData + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _source : Object; - + protected var _source : Object; + /** * Gets or sets an absolute or relative URL that identifies the * location of the SWF or image file to load, the class name * of a movie clip in the library, or a reference to a display * object. The TileListData does not load the source, it only * passes the value of the source on to the ImageCell. * *

    Valid image file formats include GIF, PNG, and JPEG.

    * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get source () : Object; - + public function get source () : Object; + /** * Creates a new instance of the TileListData class as specified by its * parameters. The TileListData class inherits the properties of the ListData * class, and adds a source parameter for the path to the image that is * associated with the cell. * * @param label The label to be displayed in this cell. * @param icon The icon to be displayed in this cell. * @param source The path or class that is associated with the content to be displayed in the cell. * @param owner The component that owns this cell. * @param index The index of the item in the data provider. * @param row The row in which this item is being displayed. In a List or * DataGrid, this corresponds to the index. In a TileList it may be * different than the index. * @param col The column in which this item is being displayed. In a List * this will always be equal to 0. * * @see fl.controls.listClasses.ListData ListData * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function TileListData (label:String, icon:Object, source:Object, owner:UIComponent, index:uint, row:uint, col:uint = 0); - } -} + public function TileListData (label:String, icon:Object, source:Object, owner:UIComponent, index:uint, row:uint, col:uint = 0); + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/progressBarClasses/IndeterminateBar.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/progressBarClasses/IndeterminateBar.as index 2f1c039d94..7efcf9f4bd 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/progressBarClasses/IndeterminateBar.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/controls/progressBarClasses/IndeterminateBar.as @@ -1,93 +1,93 @@ -package fl.controls.progressBarClasses -{ - import fl.controls.ProgressBar; - import fl.core.UIComponent; - import fl.core.InvalidationType; - import flash.display.BitmapData; - import flash.display.DisplayObject; - import flash.display.Graphics; - import flash.display.Sprite; - import flash.events.Event; - +package fl.controls.progressBarClasses +{ + import fl.controls.ProgressBar; + import fl.core.UIComponent; + import fl.core.InvalidationType; + import flash.display.BitmapData; + import flash.display.DisplayObject; + import flash.display.Graphics; + import flash.display.Sprite; + import flash.events.Event; + /** * @copy fl.controls.ProgressBar#style:indeterminateSkin * * @default ProgressBar_indeterminateSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="indeterminateSkin", type="Class")] - + [Style(name="indeterminateSkin", type="Class")] + /** * The IndeterminateBar class handles the drawing of the progress bar component when the * size of the source that is being loaded is unknown. This class can be replaced with any * other UIComponent class to render the bar differently. The default implementation uses * the drawing API create a striped fill to indicate the progress of the load operation. * * @includeExample examples/IndeterminateBarExample.as * * @see fl.controls.ProgressBar * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class IndeterminateBar extends UIComponent - { + public class IndeterminateBar extends UIComponent + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var animationCount : uint; + protected var animationCount : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var bar : Sprite; + protected var bar : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var barMask : Sprite; + protected var barMask : Sprite; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var patternBmp : BitmapData; + protected var patternBmp : BitmapData; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; - + private static var defaultStyles : Object; + /** * Gets or sets a Boolean value that indicates whether the indeterminate bar is visible. * A value of true indicates that the indeterminate bar is visible; a value * of false indicates that it is not. * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get visible () : Boolean; + public function get visible () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set visible (value:Boolean) : void; - + public function set visible (value:Boolean) : void; + /** * @copy fl.core.UIComponent#getStyleDefinition() * * @includeExample ../../core/examples/UIComponent.getStyleDefinition.1.as -noswf * * @see fl.core.UIComponent#getStyle() * @see fl.core.UIComponent#setStyle() * @see fl.managers.StyleManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Creates a new instance of the IndeterminateBar component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function IndeterminateBar (); + public function IndeterminateBar (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function startAnimation () : void; + protected function startAnimation () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function stopAnimation () : void; + protected function stopAnimation () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function handleEnterFrame (event:Event) : void; + protected function handleEnterFrame (event:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawPattern () : void; + protected function drawPattern () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawMask () : void; + protected function drawMask () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function drawBar () : void; - } -} + protected function drawBar () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/core/InvalidationType.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/core/InvalidationType.as index 3c5a33b5b1..467baabca9 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/core/InvalidationType.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/core/InvalidationType.as @@ -1,42 +1,42 @@ -package fl.core -{ +package fl.core +{ /** * The InvalidationType class defines InvalidationType constants * that are used by the type property of an event object that is * dispatched after a component is invalidated. These constants are used * by component developers to specify the portion of the component that is to be redrawn * after the component is invalidated. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class InvalidationType - { + public class InvalidationType + { /** * The InvalidationType.ALL constant defines the value of the type * property of the event object that is dispatched to indicate that the component should * redraw itself entirely. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ALL : String = "all"; + public static const ALL : String = "all"; /** * The InvalidationType.SIZE constant defines the value of the type * property of the event object that is dispatched to indicate that the screen dimensions of * the component are invalid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] This one implies that the dimensions of the component on the screen * should be redrawn, but should say so if that is correct. */ - public static const SIZE : String = "size"; + public static const SIZE : String = "size"; /** * The InvalidationType.STYLES constant defines the value of the type * property of the event object that is dispatched to indicate that the styles of the component * are invalid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] Would it be correct to say "that the component should redraw its styles?" */ - public static const STYLES : String = "styles"; + public static const STYLES : String = "styles"; /** * The InvalidationType.RENDERER_STYLES constant defines the value of * the type property of the event object that is dispatched to indicate that * the renderer styles of the component are invalid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] Should this one say, "that the component should redraw its renderer styles?" */ - public static const RENDERER_STYLES : String = "rendererStyles"; + public static const RENDERER_STYLES : String = "rendererStyles"; /** * The InvalidationType.STATE constant defines the value of the type * property of the event object that is dispatched to indicate that the state of the component * is invalid. For example, this constant is used when the enabled state of a component * is no longer valid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] What would be redrawn for a component with an invalid state? */ - public static const STATE : String = "state"; + public static const STATE : String = "state"; /** * The InvalidationType.DATA constant defines the value of the type * property of the event object that is dispatched to indicate that the data that belongs to * a component is invalid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] For this one, would the data require refreshing? Recreation? Replacement? */ - public static const DATA : String = "data"; + public static const DATA : String = "data"; /** * The InvalidationType.SCROLL constant defines the value of the type * property of the event object that is dispatched to indicate that the scroll position of the * component is invalid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] When the scroll position should be redrawn? */ - public static const SCROLL : String = "scroll"; + public static const SCROLL : String = "scroll"; /** * The InvalidationType.SELECTED constant defines the value of the type * property of the event object that is dispatched to indicate that the selected * property of the component is invalid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] For this one, does the component need to be redrawn to remove the focus indicator? */ - public static const SELECTED : String = "selected"; - - } -} + public static const SELECTED : String = "selected"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/core/UIComponent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/core/UIComponent.as index 9db1ffca35..d49c868fef 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/core/UIComponent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/core/UIComponent.as @@ -1,448 +1,448 @@ -package fl.core -{ - import flash.display.DisplayObject; - import flash.display.DisplayObjectContainer; - import flash.display.InteractiveObject; - import flash.display.Sprite; - import flash.display.Stage; - import flash.events.Event; - import flash.events.EventPhase; - import flash.events.FocusEvent; - import flash.events.KeyboardEvent; - import flash.events.MouseEvent; - import flash.geom.Rectangle; - import flash.text.TextField; - import flash.text.TextFormat; - import flash.text.TextFormatAlign; - import flash.utils.Dictionary; - import flash.utils.getDefinitionByName; - import flash.utils.getQualifiedClassName; - import flash.system.Capabilities; - import flash.system.IME; - import flash.system.IMEConversionMode; - import flash.utils.getQualifiedClassName; - import fl.core.InvalidationType; - import fl.events.ComponentEvent; - import fl.managers.FocusManager; - import fl.managers.IFocusManager; - import fl.managers.IFocusManagerComponent; - import fl.managers.StyleManager; - +package fl.core +{ + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + import flash.display.InteractiveObject; + import flash.display.Sprite; + import flash.display.Stage; + import flash.events.Event; + import flash.events.EventPhase; + import flash.events.FocusEvent; + import flash.events.KeyboardEvent; + import flash.events.MouseEvent; + import flash.geom.Rectangle; + import flash.text.TextField; + import flash.text.TextFormat; + import flash.text.TextFormatAlign; + import flash.utils.Dictionary; + import flash.utils.getDefinitionByName; + import flash.utils.getQualifiedClassName; + import flash.system.Capabilities; + import flash.system.IME; + import flash.system.IMEConversionMode; + import flash.utils.getQualifiedClassName; + import fl.core.InvalidationType; + import fl.events.ComponentEvent; + import fl.managers.FocusManager; + import fl.managers.IFocusManager; + import fl.managers.IFocusManagerComponent; + import fl.managers.StyleManager; + /** * Dispatched after the component is moved. * * @eventType fl.events.ComponentEvent.MOVE * * @includeExample examples/UIComponent.MOVE.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="move", type="fl.events.ComponentEvent")] + [Event(name="move", type="fl.events.ComponentEvent")] /** * Dispatched after the component is resized. * * @eventType fl.events.ComponentEvent.RESIZE * * @includeExample examples/UIComponent.RESIZE.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="resize", type="fl.events.ComponentEvent")] + [Event(name="resize", type="fl.events.ComponentEvent")] /** * Dispatched after the component visibility changes from invisible to visible. * * @eventType fl.events.ComponentEvent.SHOW * * @includeExample examples/UIComponent.HIDE.1.as -noswf * * @see #event:hide * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="show", type="fl.events.ComponentEvent")] + [Event(name="show", type="fl.events.ComponentEvent")] /** * Dispatched after the component visibility changes from visible to invisible. * * @eventType fl.events.ComponentEvent.HIDE * * @includeExample examples/UIComponent.HIDE.1.as -noswf * * @see #event:show * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="hide", type="fl.events.ComponentEvent")] + [Event(name="hide", type="fl.events.ComponentEvent")] /** * The skin to be used to display focus indicators. * * @default focusRectSkin * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="focusRectSkin", type="Class")] + [Style(name="focusRectSkin", type="Class")] /** * The padding that separates the outside boundaries of the component from the * outside edges of the focus indicator, in pixels. * * @default 2 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="focusRectPadding", type="Number", format="Length")] + [Style(name="focusRectPadding", type="Number", format="Length")] /** * The TextFormat object to use to render the component label. * * @default TextFormat("_sans", 11, 0x000000, false, false, false, '', '', TextFormatAlign.LEFT, 0, 0, 0, 0) * * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="textFormat", type="flash.text.TextFormat")] + [Style(name="textFormat", type="flash.text.TextFormat")] /** * The TextFormat object to use to render the component label when the button is disabled. * * @default TextFormat("_sans", 11, 0x999999, false, false, false, '', '', TextFormatAlign.LEFT, 0, 0, 0, 0) * * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Style(name="disabledTextFormat", type="flash.text.TextFormat")] - + [Style(name="disabledTextFormat", type="flash.text.TextFormat")] + /** * The UIComponent class is the base class for all visual components, * both interactive and noninteractive. Interactive components are defined * as components that receive user input such as keyboard or mouse activity. * Noninteractive components are used to display data; they do not respond * to user interaction. The ProgressBar and UILoader components are examples * of noninteractive components. * *

    The Tab and arrow keys can be used to move focus to and over an interactive component; * an interactive component can accept low-level events such as input from mouse and keyboard * devices. An interactive component can also be disabled so that it cannot receive * mouse and keyboard input.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class UIComponent extends Sprite - { + public class UIComponent extends Sprite + { /** * The version number of the components. * * @includeExample examples/UIComponent.version.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var version : String; + public var version : String; /** * @private (internal) * Indicates whether the current execution stack is within a call later phase. * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var inCallLaterPhase : Boolean; + public static var inCallLaterPhase : Boolean; /** * @private * Used when components are nested, and we want the parent component to * handle draw focus, not the child. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var focusTarget : IFocusManagerComponent; + public var focusTarget : IFocusManagerComponent; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var isLivePreview : Boolean; + protected var isLivePreview : Boolean; /** * @private (testing) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var tempText : TextField; + private var tempText : TextField; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var instanceStyles : Object; + protected var instanceStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var sharedStyles : Object; + protected var sharedStyles : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var callLaterMethods : Dictionary; + protected var callLaterMethods : Dictionary; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var invalidateFlag : Boolean; + protected var invalidateFlag : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _enabled : Boolean; + protected var _enabled : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var invalidHash : Object; + protected var invalidHash : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var uiFocusRect : DisplayObject; + protected var uiFocusRect : DisplayObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var isFocused : Boolean; + protected var isFocused : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _focusEnabled : Boolean; + private var _focusEnabled : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _mouseFocusEnabled : Boolean; + private var _mouseFocusEnabled : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _width : Number; + protected var _width : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _height : Number; + protected var _height : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _x : Number; + protected var _x : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _y : Number; + protected var _y : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var startWidth : Number; + protected var startWidth : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var startHeight : Number; + protected var startHeight : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _imeMode : String; + protected var _imeMode : String; /** * @private (protected) */ - protected var _oldIMEMode : String; + protected var _oldIMEMode : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var errorCaught : Boolean; + protected var errorCaught : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _inspector : Boolean; + protected var _inspector : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var defaultStyles : Object; + private static var defaultStyles : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var focusManagers : Dictionary; + private static var focusManagers : Dictionary; /** * @private * @internal (Placeholder for mixin by UIComponentAccImpl) * * Creates the Accessibility class to be associated with the current component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static var createAccessibilityImplementation : Function; - + public static var createAccessibilityImplementation : Function; + /** * @private (internal) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get componentInspectorSetting () : Boolean; + public function get componentInspectorSetting () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set componentInspectorSetting (value:Boolean) : void; + public function set componentInspectorSetting (value:Boolean) : void; /** * Gets or sets a value that indicates whether the component can accept user interaction. * A value of true indicates that the component can accept user interaction; a * value of false indicates that it cannot. * *

    If you set the enabled property to false, the color of the * container is dimmed and user input is blocked (with the exception of the Label and ProgressBar components).

    * * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get enabled () : Boolean; + public function get enabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set enabled (value:Boolean) : void; + public function set enabled (value:Boolean) : void; /** * Gets or sets the width of the component, in pixels. * *

    Setting this property causes a resize event to be * dispatched. See the resize event for detailed information * about when it is dispatched.

    * *

    If the scaleX property of the component is not 1.0, * the width of the component that is obtained from its internal coordinates * will not match the width value from the parent coordinates. For example, * a component that is 100 pixels in width and has a scaleX of 2 * has a value of 100 pixels in the parent, but internally stores a value * indicating that it is 50 pixels wide.

    * * @see #height * @see #event:resize * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get width () : Number; + public function get width () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set width (value:Number) : void; + public function set width (value:Number) : void; /** * Gets or sets the height of the component, in pixels. * *

    Setting this property causes a resize event to be * dispatched. See the resize event for detailed information * about when it is dispatched.

    * *

    If the scaleY property of the component is not 1.0, * the height of the component that is obtained from its internal coordinates * will not match the height value from the parent coordinates. For example, * a component that is 100 pixels in height and has a scaleY of 2 * has a value of 100 pixels in the parent, but internally stores a value * indicating that it is 50 pixels in height.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get height () : Number; + public function get height () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set height (value:Number) : void; + public function set height (value:Number) : void; /** * Gets or sets the x coordinate that represents the position of the component along * the x axis within its parent container. This value is described in pixels and is * calculated from the left. * *

    Setting this property causes the ComponentEvent.MOVE event to be dispatched.

    * * @default 0 * * @see #move() * @see #y * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get x () : Number; + public function get x () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set x (value:Number) : void; + public function set x (value:Number) : void; /** * Gets or sets the y coordinate that represents the position of the component along * the y axis within its parent container. This value is described in pixels and is * calculated from the top. * *

    Setting this property causes the move event to be dispatched.

    * * @see #move() * @see #x * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] Should this have a default value of 0, like the x property? */ - public function get y () : Number; + public function get y () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set y (value:Number) : void; + public function set y (value:Number) : void; /** * Multiplies the current width of the component by a scale factor. * * @see #scaleY * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scaleX () : Number; + public function get scaleX () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scaleX (value:Number) : void; + public function set scaleX (value:Number) : void; /** * Multiplies the current height of the component by a scale factor. * * @see #scaleX * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scaleY () : Number; + public function get scaleY () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scaleY (value:Number) : void; + public function set scaleY (value:Number) : void; /** * Gets or sets a value that indicates whether the current component instance is visible. * A value of true indicates that the current component is visible; a value of * false indicates that it is not. * *

    When this property is set to true, the object dispatches a * show event. When this property is set to false, * the object dispatches a hide event. In either case, * the children of the object do not generate a show or * hide event unless the object specifically writes an * implementation to do so.

    * * @default true * * @see #event:hide * @see #event:show * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get visible () : Boolean; + public function get visible () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set visible (value:Boolean) : void; + public function set visible (value:Boolean) : void; /** * Gets or sets a Boolean value that indicates whether the component can receive focus * after the user clicks it. A value of true indicates that it can * receive focus; a value of false indicates that it cannot. * *

    If this property is false, focus is transferred to the first * parent whose mouseFocusEnabled property is set to true.

    * * @default true * * @see #mouseFocusEnabled * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal [kenos] This is described as being the same thing as the property * below. Is this correct? */ - public function get focusEnabled () : Boolean; + public function get focusEnabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set focusEnabled (b:Boolean) : void; + public function set focusEnabled (b:Boolean) : void; /** * Gets or sets a value that indicates whether the component can receive focus after * the user clicks it. A value of true indicates that it can receive * focus; a value of false indicates that it cannot. * *

    If this property is false, focus is transferred to the first * parent whose mouseFocusEnabled property is set to true.

    * * @default true * * @see #focusEnabled * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get mouseFocusEnabled () : Boolean; + public function get mouseFocusEnabled () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set mouseFocusEnabled (b:Boolean) : void; + public function set mouseFocusEnabled (b:Boolean) : void; /** * Gets or sets the FocusManager that controls focus for this component and its * peers. Each pop-up component maintains its own focus loop and FocusManager instance. * Use this property to access the correct FocusManager for this component. * * @return The FocusManager that is associated with the current component; otherwise * this property returns null. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get focusManager () : IFocusManager; + public function get focusManager () : IFocusManager; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set focusManager (f:IFocusManager) : void; - + public function set focusManager (f:IFocusManager) : void; + /** * Retrieves the default style map for the current component. The style map contains * the type that is appropriate for the component, depending on the style that * the component uses. For example, the disabledTextFormat style * contains a value of null or a TextFormat object. * You can use these styles and call setStyle() on the current * component. The following code overrides the default disabledTextFormat * style on the specified component: * componentInstance.setStyle("disabledTextFormat", new TextFormat()); * * @return Default styles object. * * @includeExample examples/UIComponent.getStyleDefinition.1.as -noswf * * @see #getStyle() * @see #setStyle() * @see fl.managers.StyleManager StyleManager * @internal [kenos] This is vague. What are "these styles" that you can use "and call setStyle * on the current component"? * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyleDefinition () : Object; + public static function getStyleDefinition () : Object; /** * Merges the styles from multiple classes into one object. * If a style is defined in multiple objects, the first occurrence * that is found is used. * * @param list A comma-delimited list of objects that contain the default styles to be merged. * * @return A default style object that contains the merged styles. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function mergeStyles (...list:Array) : Object; + public static function mergeStyles (...list:Array) : Object; /** * Creates a new UIComponent component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function UIComponent (); + public function UIComponent (); /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function beforeComponentParameters () : void; + protected function beforeComponentParameters () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function afterComponentParameters () : void; + protected function afterComponentParameters () : void; /** * Sets the component to the specified width and height. * * @param width The width of the component, in pixels. * * @param height The height of the component, in pixels. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSize (width:Number, height:Number) : void; + public function setSize (width:Number, height:Number) : void; /** * Sets a style property on this component instance. This style may * override a style that was set globally. * *

    Calling this method can result in decreased performance. * Use it only when necessary.

    * * @param style The name of the style property. * * @param value The value of the style. * * @includeExample examples/UIComponent.setStyle.1.as -noswf * @includeExample examples/UIComponent.setStyle.2.as -noswf * * @see #getStyle() * @see #clearStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setStyle (style:String, value:Object) : void; + public function setStyle (style:String, value:Object) : void; /** * Deletes a style property from this component instance. *

    This does not necessarily cause the getStyle() method * to return a value of undefined.

    * * @param style The name of the style property. * * @see #getStyle() * @see #setStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clearStyle (style:String) : void; + public function clearStyle (style:String) : void; /** * Retrieves a style property that is set in the style lookup * chain of the component. * *

    The type that this method returns varies depending on the style * property that the method retrieves. The range of possible types includes * Boolean; String; Number; int; a uint for an RGB color; a Class for a skin; * or any kind of object.

    * *

    If you call this method to retrieve a particular style property, * it will be of a known type that you can store in a variable of the * same type. Type casting is not necessary. Instead, a simple assignment * statement like the following will work:

    * * var backgroundColor:uint = getStyle("backgroundColor"); * *

    If the style property is not set in the style lookup chain, this method * returns a value of undefined. Note that undefined * is a special value that is not the same as false, "", NaN, * 0, or null. No valid style value is ever undefined. * You can use the static method StyleManager.isValidStyleValue() to * test whether a value was set.

    * * @param style The name of the style property. * * @return Style value. * * @includeExample examples/UIComponent.getStyle.1.as -noswf * * @see #clearStyle() * @see #setStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getStyle (style:String) : Object; + public function getStyle (style:String) : Object; /** * Moves the component to the specified position within its parent. This has * the same effect as changing the component location by setting its * x and y properties. Calling this method triggers * the ComponentEvent.MOVE event to be dispatched. * *

    To override the updateDisplayList() method in a * custom component, use the move() method instead * of setting the x and y properties. This is because * a call to the move() method causes a move event object * to be dispatched immediately after the move operation is complete. In contrast, * when you change the component location by setting the x and y * properties, the event object is dispatched on the next screen refresh.

    * * @param x The x coordinate value that specifies the position of the component within its * parent, in pixels. This value is calculated from the left. * * @param y The y coordinate value that specifies the position of the component within its * parent, in pixels. This value is calculated from the top. * * @see #x * @see #y * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function move (x:Number, y:Number) : void; + public function move (x:Number, y:Number) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getScaleY () : Number; + protected function getScaleY () : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setScaleY (value:Number) : void; + protected function setScaleY (value:Number) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getScaleX () : Number; + protected function getScaleX () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setScaleX (value:Number) : void; + protected function setScaleX (value:Number) : void; /** * Validates and updates the properties and layout of this object, redrawing it * if necessary. * *

    Properties that require substantial computation are normally not processed * until the script finishes executing. This is because setting one property could * require the processing of other properties. For example, setting the width * property may require that the widths of the children or parent of the object also * be recalculated. And if the script recalculates the width of the object more than * once, these interdependent properties may also require recalculating. Use this * method to manually override this behavior.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function validateNow () : void; + public function validateNow () : void; /** * Marks a property as invalid and redraws the component on the * next frame unless otherwise specified. * * @param property The property to be invalidated. * * @param callLater A Boolean value that indicates whether the * component should be redrawn on the next frame. The default * value is true. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function invalidate (property:String = InvalidationType.ALL, callLater:Boolean = true) : void; + public function invalidate (property:String = InvalidationType.ALL, callLater:Boolean = true) : void; /** * @private (internal) * * Sets the inherited style value to the specified style name and * invalidates the styles of the component. * * @param name Style name. * * @param style Style value. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSharedStyle (name:String, style:Object) : void; + public function setSharedStyle (name:String, style:Object) : void; /** * Shows or hides the focus indicator on this component. * *

    The UIComponent class implements this method by creating and positioning * an instance of the class that is specified by the focusSkin style.

    * * @param focused Indicates whether to show or hide the focus indicator. * If this value is true, the focus indicator is shown; if this value * is false, the focus indicator is hidden. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawFocus (focused:Boolean) : void; + public function drawFocus (focused:Boolean) : void; /** * Sets the focus to this component. The component may in turn give the focus * to a subcomponent. * *

    Note: Only the TextInput and TextArea components show * a focus indicator when this method sets the focus. All components show a focus * indicator when the user tabs to the component.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setFocus () : void; + public function setFocus () : void; /** * Retrieves the object that currently has focus. * *

    Note that this method does not necessarily return the component that * has focus. It may return the internal subcomponent of the component * that has focus. To get the component that has focus, use the * focusManager.focus property.

    * * @return The object that has focus; otherwise, this method returns null. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getFocus () : InteractiveObject; + public function getFocus () : InteractiveObject; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function setIMEMode (enabled:Boolean); + protected function setIMEMode (enabled:Boolean); /** * Initiates an immediate draw operation, without invalidating everything as invalidateNow does. * * @internal what is "invalidateNow"? i cannot find it in the API. * @internal [kenos] Additionally, is the immediate draw operation on this component and does invalidating * "everything" mean invalidating the entire component? * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawNow () : void; + public function drawNow () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function configUI () : void; + protected function configUI () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function checkLivePreview () : Boolean; + protected function checkLivePreview () : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function isInvalid (property:String, ...properties:Array) : Boolean; + protected function isInvalid (property:String, ...properties:Array) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function validate () : void; + protected function validate () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function draw () : void; + protected function draw () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getDisplayObjectInstance (skin:Object) : DisplayObject; + protected function getDisplayObjectInstance (skin:Object) : DisplayObject; /** * Returns the specified style for a component, considering all styles set on the global level, component level and instance level. * *

    For example, if a component has a style set at the global level to myStyle and you call * getStyle("myStyle") on an instance that does not have an instance setting, it returns null. If you call * getStyleValue("myStyle"), it returns "myStyle", because it is active at the global level.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getStyleValue (name:String) : Object; + protected function getStyleValue (name:String) : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function copyStylesToChild (child:UIComponent, styleMap:Object) : void; + protected function copyStylesToChild (child:UIComponent, styleMap:Object) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function callLater (fn:Function) : void; + protected function callLater (fn:Function) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function callLaterDispatcher (event:Event) : void; + private function callLaterDispatcher (event:Event) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function initializeFocusManager () : void; + private function initializeFocusManager () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function addedHandler (evt:Event) : void; + private function addedHandler (evt:Event) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function createFocusManager () : void; + protected function createFocusManager () : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function isOurFocus (target:DisplayObject) : Boolean; + protected function isOurFocus (target:DisplayObject) : Boolean; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusInHandler (event:FocusEvent) : void; + protected function focusInHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function focusOutHandler (event:FocusEvent) : void; + protected function focusOutHandler (event:FocusEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyDownHandler (event:KeyboardEvent) : void; + protected function keyDownHandler (event:KeyboardEvent) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function keyUpHandler (event:KeyboardEvent) : void; + protected function keyUpHandler (event:KeyboardEvent) : void; /** * @private (protected) * Triggers initialization of this component's accessibility code. * *

    This method is called from the constructor via ENTER_FRAME event * to initialize accessibility support for this component

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function hookAccessibility (event:Event) : void; + protected function hookAccessibility (event:Event) : void; /** * @private (protected) * Initializes this component's accessibility code. * *

    This method is called from the constructor to hook in the * component's accessibility code, which resides in a separate class * in the fl.accessibility package. * Each subclass that supports accessibility must override this method * because the hook-in process uses a different static variable * in each subclass.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function initializeAccessibility () : void; - } -} + protected function initializeAccessibility () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/DataProvider.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/DataProvider.as index a8f338ef4b..30f3215b84 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/DataProvider.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/DataProvider.as @@ -1,137 +1,137 @@ -package fl.data -{ - import flash.events.EventDispatcher; - import fl.events.DataChangeEvent; - import fl.events.DataChangeType; - import RangeError; - +package fl.data +{ + import flash.events.EventDispatcher; + import fl.events.DataChangeEvent; + import fl.events.DataChangeType; + import RangeError; + /** * Dispatched before the data is changed. * * @see #event:dataChange dataChange event * * @eventType fl.events.DataChangeEvent.PRE_DATA_CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="preDataChange", type="fl.events.DataChangeEvent")] + [Event(name="preDataChange", type="fl.events.DataChangeEvent")] /** * Dispatched after the data is changed. * * @see #event:preDataChange preDataChange event * * @eventType fl.events.DataChangeEvent.DATA_CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event(name="dataChange", type="fl.events.DataChangeEvent")] - + [Event(name="dataChange", type="fl.events.DataChangeEvent")] + /** * The DataProvider class provides methods and properties that allow you to query and modify * the data in any list-based component--for example, in a List, DataGrid, TileList, or ComboBox * component. * *

    A data provider is a linear collection of items that serve as a data source--for * example, an array. Each item in a data provider is an object or XML object that contains one or * more fields of data. You can access the items that are contained in a data provider by index, by * using the DataProvider.getItemAt() method.

    * * @includeExample examples/DataProviderExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataProvider extends EventDispatcher - { + public class DataProvider extends EventDispatcher + { /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var data : Array; - + protected var data : Array; + /** * The number of items that the data provider contains. * * @includeExample examples/DataProvider.length.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get length () : uint; - + public function get length () : uint; + /** * Creates a new DataProvider object using a list, XML instance or an array of data objects * as the data source. * * @param data The data that is used to create the DataProvider. * * @includeExample examples/DataProvider.constructor.1.as -noswf * @includeExample examples/DataProvider.constructor.2.as -noswf * @includeExample examples/DataProvider.constructor.3.as -noswf * @includeExample examples/DataProvider.constructor.4.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function DataProvider (value:Object = null); + public function DataProvider (value:Object = null); /** * Invalidates the item at the specified index. An item is invalidated after it is * changed; the DataProvider automatically redraws the invalidated item. * * @param index Index of the item to be invalidated. * * @throws RangeError The specified index is less than 0 or greater than * or equal to the length of the data provider. * * @see #invalidate() * @see #invalidateItem() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function invalidateItemAt (index:int) : void; + public function invalidateItemAt (index:int) : void; /** * Invalidates the specified item. An item is invalidated after it is * changed; the DataProvider automatically redraws the invalidated item. * * @param item Item to be invalidated. * * @see #invalidate() * @see #invalidateItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function invalidateItem (item:Object) : void; + public function invalidateItem (item:Object) : void; /** * Invalidates all the data items that the DataProvider contains and dispatches a * DataChangeEvent.INVALIDATE_ALL event. Items are invalidated after they * are changed; the DataProvider automatically redraws the invalidated items. * * @see #invalidateItem() * @see #invalidateItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function invalidate () : void; + public function invalidate () : void; /** * Adds a new item to the data provider at the specified index. * If the index that is specified exceeds the length of the data provider, * the index is ignored. * * @param item An object that contains the data for the item to be added. * * @param index The index at which the item is to be added. * * @throws RangeError The specified index is less than 0 or greater than or equal * to the length of the data provider. * * @see #addItem() * @see #addItems() * @see #addItemsAt() * @see #getItemAt() * @see #removeItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addItemAt (item:Object, index:uint) : void; + public function addItemAt (item:Object, index:uint) : void; /** * Appends an item to the end of the data provider. * * @param item The item to be appended to the end of the current data provider. * * @includeExample examples/DataProvider.constructor.1.as -noswf * * @see #addItemAt() * @see #addItems() * @see #addItemsAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addItem (item:Object) : void; + public function addItem (item:Object) : void; /** * Adds several items to the data provider at the specified index and dispatches * a DataChangeType.ADD event. * * @param items The items to be added to the data provider. * * @param index The index at which the items are to be inserted. * * @throws RangeError The specified index is less than 0 or greater than or equal * to the length of the data provider. * * @see #addItem() * @see #addItemAt() * @see #addItems() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addItemsAt (items:Object, index:uint) : void; + public function addItemsAt (items:Object, index:uint) : void; /** * Appends multiple items to the end of the DataProvider and dispatches * a DataChangeType.ADD event. The items are added in the order * in which they are specified. * * @param items The items to be appended to the data provider. * * @includeExample examples/DataProvider.addItems.1.as -noswf * * @see #addItem() * @see #addItemAt() * @see #addItemsAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addItems (items:Object) : void; + public function addItems (items:Object) : void; /** * Concatenates the specified items to the end of the current data provider. * This method dispatches a DataChangeType.ADD event. * * @param items The items to be added to the data provider. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * * @see #addItems() * @see #merge() * * @internal Is this method any different than addItems()? It's not clear. * I also thing "concatenates the items *to*" sounds odd. Perhaps * the concatenated items are added to the end of the data provider? */ - public function concat (items:Object) : void; + public function concat (items:Object) : void; /** * Appends the specified data into the data that the data provider * contains and removes any duplicate items. This method dispatches * a DataChangeType.ADD event. * * @param data Data to be merged into the data provider. * * @see #concat() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function merge (newData:Object) : void; + public function merge (newData:Object) : void; /** * Returns the item at the specified index. * * @param index Location of the item to be returned. * * @return The item at the specified index. * * @throws RangeError The specified index is less than 0 or greater than * or equal to the length of the data provider. * * @see #getItemIndex() * @see #removeItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getItemAt (index:uint) : Object; + public function getItemAt (index:uint) : Object; /** * Returns the index of the specified item. * * @param item The item to be located. * * @return The index of the specified item, or -1 if the specified item is not found. * * @see #getItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getItemIndex (item:Object) : int; + public function getItemIndex (item:Object) : int; /** * Removes the item at the specified index and dispatches a DataChangeType.REMOVE * event. * * @param index Index of the item to be removed. * * @return The item that was removed. * * @throws RangeError The specified index is less than 0 or greater than * or equal to the length of the data provider. * * @see #removeAll() * @see #removeItem() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeItemAt (index:uint) : Object; + public function removeItemAt (index:uint) : Object; /** * Removes the specified item from the data provider and dispatches a DataChangeType.REMOVE * event. * * @param item Item to be removed. * * @return The item that was removed. * * @see #removeAll() * @see #removeItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeItem (item:Object) : Object; + public function removeItem (item:Object) : Object; /** * Removes all items from the data provider and dispatches a DataChangeType.REMOVE_ALL * event. * * @see #removeItem() * @see #removeItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeAll () : void; + public function removeAll () : void; /** * Replaces an existing item with a new item and dispatches a DataChangeType.REPLACE * event. * * @param oldItem The item to be replaced. * * @param newItem The replacement item. * * @return The item that was replaced. * * @throws RangeError The item could not be found in the data provider. * * @see #replaceItemAt() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function replaceItem (newItem:Object, oldItem:Object) : Object; + public function replaceItem (newItem:Object, oldItem:Object) : Object; /** * Replaces the item at the specified index and dispatches a DataChangeType.REPLACE * event. * * @param newItem The replacement item. * * @param index The index of the item to be replaced. * * @return The item that was replaced. * * @throws RangeError The specified index is less than 0 or greater than * or equal to the length of the data provider. * * @see #replaceItem() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function replaceItemAt (newItem:Object, index:uint) : Object; + public function replaceItemAt (newItem:Object, index:uint) : Object; /** * Sorts the items that the data provider contains and dispatches a DataChangeType.SORT * event. * * @param sortArg The arguments to use for sorting. * * @return The return value depends on whether the method receives any arguments. * See the Array.sort() method for more information. * This method returns 0 when the sortOption property * is set to Array.UNIQUESORT. * * @see #sortOn() * @see Array#sort() Array.sort() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function sort (...sortArgs:Array) : *; + public function sort (...sortArgs:Array) : *; /** * Sorts the items that the data provider contains by the specified * field and dispatches a DataChangeType.SORT event. * The specified field can be a string, or an array of string values that * designate multiple fields to sort on in order of precedence. * * @param fieldName The item field by which to sort. This value can be a string * or an array of string values. * * @param options Options for sorting. * * @return The return value depends on whether the method receives any arguments. * For more information, see the Array.sortOn() method. * If the sortOption property is set to Array.UNIQUESORT, * this method returns 0. * * @see #sort() * @see Array#sortOn() Array.sortOn() * * @internal If an array of string values is passed, does the sort take place in * the order that the string values are specified? Also, it might be helpful if "options * for sorting" was more explicit. I wondered if that meant sort type, like merge sort * or bubble sort, for example, but when I looked up "uniquesort" it seemed like not. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function sortOn (fieldName:Object, options:Object = null) : *; + public function sortOn (fieldName:Object, options:Object = null) : *; /** * Creates a copy of the current DataProvider object. * * @return A new instance of this DataProvider object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : DataProvider; + public function clone () : DataProvider; /** * Creates an Array object representation of the data that the data provider contains. * * @return An Array object representation of the data that the data provider contains. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toArray () : Array; + public function toArray () : Array; /** * Creates a string representation of the data that the data provider contains. * * @return A string representation of the data that the data provider contains. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; + public function toString () : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function getDataFromObject (obj:Object) : Array; + protected function getDataFromObject (obj:Object) : Array; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function checkIndex (index:int, maximum:int) : void; + protected function checkIndex (index:int, maximum:int) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function dispatchChangeEvent (evtType:String, items:Array, startIndex:int, endIndex:int) : void; + protected function dispatchChangeEvent (evtType:String, items:Array, startIndex:int, endIndex:int) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected function dispatchPreChangeEvent (evtType:String, items:Array, startIndex:int, endIndex:int) : void; - } -} + protected function dispatchPreChangeEvent (evtType:String, items:Array, startIndex:int, endIndex:int) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/SimpleCollectionItem.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/SimpleCollectionItem.as index 41bcf8e8b7..10d231ef77 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/SimpleCollectionItem.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/SimpleCollectionItem.as @@ -1,26 +1,26 @@ -package fl.data -{ +package fl.data +{ /** * The SimpleCollectionItem class defines a single item in an inspectable * property that represents a data provider. A SimpleCollectionItem object * is a collection list item that contains only label and * data properties--for example, a ComboBox or List component. * * @internal Is this revised description correct? * Adobe: [LM} Yes, its ok. * * @includeExample examples/SimpleCollectionItemExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public dynamic class SimpleCollectionItem - { + public dynamic class SimpleCollectionItem + { /** * The label property of the object. * * The default value is label(n), where n is the ordinal index. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var label : String; + public var label : String; /** * The data property of the object. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var data : String; - + public var data : String; + /** * Creates a new SimpleCollectionItem object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function SimpleCollectionItem (); + public function SimpleCollectionItem (); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; - } -} + public function toString () : String; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/TileListCollectionItem.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/TileListCollectionItem.as index 1c5fc146a2..24a5f13de7 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/TileListCollectionItem.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/data/TileListCollectionItem.as @@ -1,26 +1,26 @@ -package fl.data -{ +package fl.data +{ /** * The TileListCollectionItem class defines a single item in an inspectable * property that represents a data provider. A TileListCollectionItem object * is a collection list item that contains only label and * source properties, and is primarily used in the TileList * component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public dynamic class TileListCollectionItem - { + public dynamic class TileListCollectionItem + { /** * The label property of the object. * * The default value is label(n), where n is the ordinal index. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var label : String; + public var label : String; /** * The source property of the object. This can be the path or a class * name of the image that is displayed in the image cell of the TileList. * * @default null * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var source : String; - + public var source : String; + /** * Creates a new TileListCollectionItem object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function TileListCollectionItem (); + public function TileListCollectionItem (); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; - } -} + public function toString () : String; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ColorPickerEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ColorPickerEvent.as index 4338d98f00..1deecad9c5 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ColorPickerEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ColorPickerEvent.as @@ -1,49 +1,49 @@ -package fl.events -{ - import flash.events.Event; - +package fl.events +{ + import flash.events.Event; + /** * The ColorPickerEvent class defines events that are associated with the ColorPicker component. * These include the following events: *
      *
    • ColorPickerEvent.CHANGE: dispatched when a user clicks a different color in the ColorPicker component.
    • *
    • ColorPickerEvent.ENTER: dispatched when a user presses the Enter key after entering a value in the text field of the ColorPicker component.
    • *
    • ColorPickerEvent.ITEM_ROLL_OUT: dispatched when the device pointer moves out of a color cell in the ColorPicker component.
    • *
    • ColorPickerEvent.ITEM_ROLL_OVER: dispatched when the device pointer moves over a color cell in the ColorPicker component.
    • *
    * * @see fl.controls.ColorPicker ColorPicker * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ColorPickerEvent extends Event - { + public class ColorPickerEvent extends Event + { /** * Defines the value of the type property for an itemRollOut * event object. * *

    This event has the following properties:

    * * * * * * * *
    PropertyValue
    bubblestrue
    cancelabletrue
    colorThe current color value of the ColorPicker component.
    currentTargetThe object that is actively processing the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemRollOut * * @see #ITEM_ROLL_OVER * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_ROLL_OUT : String = "itemRollOut"; + public static const ITEM_ROLL_OUT : String = "itemRollOut"; /** * Defines the value of the type property for an itemRollOver * event object. * *

    This event has the following properties:

    * * * * * * * *
    PropertyValue
    bubblestrue
    cancelabletrue
    colorThe current color value of the ColorPicker component.
    currentTargetThe object that is actively processing the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemRollOver * * @see #ITEM_ROLL_OUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_ROLL_OVER : String = "itemRollOver"; + public static const ITEM_ROLL_OVER : String = "itemRollOver"; /** * Defines the value of the type property of an enter * event object. * *

    This event has the following properties:

    * * * * * * * *
    PropertyValue
    bubblestrue
    cancelabletrue
    colorThe current color value of the ColorPicker component.
    currentTargetThe object that is actively processing the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType enter * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ENTER : String = "enter"; + public static const ENTER : String = "enter"; /** * Defines the value of the type property of the change * event object. * *

    This event has the following properties:

    * * * * * * * *
    PropertyValue
    bubblestrue
    cancelabletrue
    colorThe current color value of the ColorPicker component.
    currentTargetThe object that is actively processing the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @includeExample ../controls/examples/ColorPicker.hexValue.1.as -noswf * * @eventType change * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const CHANGE : String = "change"; + public static const CHANGE : String = "change"; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _color : uint; - + protected var _color : uint; + /** * Gets the color value that is associated with the event. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get color () : uint; - + public function get color () : uint; + /** * Creates a new ColorPickerEvent object. * * @param type Indicates the current event type. * * @param color Indicates the color that is associated with the current event. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ColorPickerEvent (type:String, color:uint); + public function ColorPickerEvent (type:String, color:uint); /** * Returns a string that contains all the properties of the ColorPickerEvent object. * * @return A string representation of the ColorPickerEvent object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; + public function toString () : String; /** * Creates a copy of the ColorPickerEvent object and sets the value of each parameter to match * the original. * * @return A copy of the ColorPickerEvent instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ComponentEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ComponentEvent.as index a77b863b71..56b4f960a2 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ComponentEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ComponentEvent.as @@ -1,52 +1,52 @@ -package fl.events -{ - import flash.events.Event; - +package fl.events +{ + import flash.events.Event; + /** * The ComponentEvent class defines events that are associated with the UIComponent class. * These include the following events: *
      *
    • ComponentEvent.BUTTON_DOWN: dispatched after a button is pressed.
    • *
    • ComponentEvent.ENTER: dispatched after the Enter key is pressed.
    • *
    • ComponentEvent.HIDE: dispatched after the visible property of a component is set to false.
    • *
    • ComponentEvent.LABEL_CHANGE: dispatched after the Enter key is pressed.
    • *
    • ComponentEvent.MOVE: dispatched after there is a change in the x or y properties that identify the component location.
    • *
    • ComponentEvent.RESIZE: dispatched after a component is resized.
    • *
    • ComponentEvent.SHOW: dispatched after the visible property of a component is set to true.
    • *
    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ComponentEvent extends Event - { + public class ComponentEvent extends Event + { /** * Defines the value of the type property of a buttonDown * event object. * *

    This event has the following properties:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    currentTargetThe object that is actively processing * the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType buttonDown * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const BUTTON_DOWN : String = "buttonDown"; + public static const BUTTON_DOWN : String = "buttonDown"; /** * Defines the value of the type property of a labelChange * event object. * *

    This event has the following properties:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    currentTargetThe object that is actively processing * the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType labelChange * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const LABEL_CHANGE : String = "labelChange"; + public static const LABEL_CHANGE : String = "labelChange"; /** * Defines the value of the type property of a hide * event object. * *

    This event has the following properties:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    currentTargetThe object that is actively processing * the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType hide * * @includeExample ../core/examples/UIComponent.HIDE.1.as -noswf * * @see #SHOW * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const HIDE : String = "hide"; + public static const HIDE : String = "hide"; /** * Defines the value of the type property of a show event * object. * *

    This event has the following properties:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    currentTargetThe object that is actively processing * the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType show * * @includeExample ../core/examples/UIComponent.HIDE.1.as -noswf * * @see #HIDE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const SHOW : String = "show"; + public static const SHOW : String = "show"; /** * Defines the value of the type property of a resize * event object. * *

    This event has the following properties:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    currentTargetThe object that is actively processing * the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType resize * * @includeExample ../core/examples/UIComponent.RESIZE.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const RESIZE : String = "resize"; + public static const RESIZE : String = "resize"; /** * Defines the value of the type property of a move * event object. * *

    This event has the following properties:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    currentTargetThe object that is actively processing * the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType move * * @includeExample ../core/examples/UIComponent.MOVE.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const MOVE : String = "move"; + public static const MOVE : String = "move"; /** * Defines the value of the type property of an enter * event object. * *

    This event has the following properties:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    currentTargetThe object that is actively processing * the event object with an event listener.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType enter * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ENTER : String = "enter"; - + public static const ENTER : String = "enter"; + /** * Creates a new ComponentEvent object that contains information about a component * event. A ComponentEvent object is passed as a parameter to an event listener. * * @param type The type of the event. Event listeners can access this information * through the type property of the event object. A component can * have the following types of events: ComponentEvent.BUTTON_DOWN, * ComponentEvent.ENTER, ComponentEvent.HIDE, * ComponentEvent.LABEL_CHANGE, ComponentEvent.MOVE, * ComponentEvent.RESIZE, ComponentEvent.SHOW. * * @param bubbles Determines whether the ComponentEvent object participates in the * bubbling phase of the event flow. Event listeners can access this information * through the bubbles property of the event object. * * @param cancelable Determines whether the ComponentEvent object can be canceled. Event * listeners can access this information through the cancelable property * of the event object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ComponentEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false); + public function ComponentEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false); /** * Returns a string that contains all the properties of the ComponentEvent object. The * string is in the following format: *

    [ComponentEvent type=value bubbles=value cancelable=value]

    * * @return A string representation of the ComponentEvent object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; + public function toString () : String; /** * Creates a copy of the ComponentEvent object and sets the value of each parameter to * match the original. * * @return A new ComponentEvent object with property values that match those of the * original. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataChangeEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataChangeEvent.as index 9080be3105..061ed055e7 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataChangeEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataChangeEvent.as @@ -1,65 +1,65 @@ -package fl.events -{ - import flash.events.Event; - +package fl.events +{ + import flash.events.Event; + /** * The DataChangeEvent class defines the event that is dispatched when the data * that is associated with a component changes. This event is used by the List, * DataGrid, TileList, and ComboBox components. * *

    This class provides the following event:

    *
      *
    • DataChangeEvent.DATA_CHANGE: dispatched when the component data changes.
    • *
    * * @includeExample examples/DataChangeEventExample.as * * @see DataChangeType * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataChangeEvent extends Event - { + public class DataChangeEvent extends Event + { /** * Defines the value of the type property of a dataChange * event object. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default behavior to cancel.
    changeTypeIdentifies the type of change that was made.
    currentTargetThe object that is actively processing * the event object with an event listener.
    endIndexIdentifies the index of the last changed item.
    itemsAn array that lists the items that were changed.
    startIndexIdentifies the index of the first changed item.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType dataChange * * @see #PRE_DATA_CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const DATA_CHANGE : String = "dataChange"; + public static const DATA_CHANGE : String = "dataChange"; /** * Defines the value of the type property of a preDataChange * event object. This event object is dispatched before a change is made to component data. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default behavior to cancel.
    changeTypeIdentifies the type of change to be made.
    currentTargetThe object that is actively processing * the event object with an event listener.
    endIndexIdentifies the index of the last item to be * changed.
    itemsAn array that lists the items to be changed.
    startIndexIdentifies the index of the first item to be * changed.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType preDataChange * * @see #DATA_CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const PRE_DATA_CHANGE : String = "preDataChange"; + public static const PRE_DATA_CHANGE : String = "preDataChange"; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _startIndex : uint; + protected var _startIndex : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _endIndex : uint; + protected var _endIndex : uint; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _changeType : String; + protected var _changeType : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _items : Array; - + protected var _items : Array; + /** * Gets the type of the change that triggered the event. The DataChangeType class * defines the possible values for this property. * * @see DataChangeType * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get changeType () : String; + public function get changeType () : String; /** * Gets an array that contains the changed items. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get items () : Array; + public function get items () : Array; /** * Gets the index of the first changed item in the array of items * that were changed. * * @see #endIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - public function get startIndex () : uint; + public function get startIndex () : uint; /** * Gets the index of the last changed item in the array of items * that were changed. * * @see #startIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get endIndex () : uint; - + public function get endIndex () : uint; + /** * Creates a new DataChangeEvent object with the specified parameters. * * @param eventType The type of change event. * * @param changeType The type of change that was made. The DataChangeType class defines the possible values for * this parameter. * * @param items A list of items that were changed. * * @param startIndex The index of the first item that was changed. * * @param endIndex The index of the last item that was changed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function DataChangeEvent (eventType:String, changeType:String, items:Array, startIndex:int = -1, endIndex:int = -1); + public function DataChangeEvent (eventType:String, changeType:String, items:Array, startIndex:int = -1, endIndex:int = -1); /** * Returns a string that contains all the properties of the DataChangeEvent object. The * string is in the following format: * *

    [DataChangeEvent type=value changeType=value * startIndex=value endIndex=value * bubbles=value cancelable=value]

    * * @return A string that contains all the properties of the DataChangeEvent object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; + public function toString () : String; /** * Creates a copy of the DataEvent object and sets the value of each parameter to match * that of the original. * * @return A new DataChangeEvent object with property values that match those of the * original. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataChangeType.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataChangeType.as index 326e443384..988e851481 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataChangeType.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataChangeType.as @@ -1,42 +1,42 @@ -package fl.events -{ +package fl.events +{ /** * The DataChangeType class defines constants for the DataChangeEvent.changeType * event. These constants are used by the DataChangeEvent class to identify the type * of change that was applied to the data in a list-based component such as a List, ComboBox, * TileList, or DataGrid. * * @see DataChangeEvent#changeType * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataChangeType - { + public class DataChangeType + { /** * A change was made to the component data. This value does not affect the * component data that it describes. * * @eventType change * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const CHANGE : String = "change"; + public static const CHANGE : String = "change"; /** * A change was made to the data contained in an item. * * @eventType invalidate * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const INVALIDATE : String = "invalidate"; + public static const INVALIDATE : String = "invalidate"; /** * The data set is invalid. * * @eventType invalidateAll * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const INVALIDATE_ALL : String = "invalidateAll"; + public static const INVALIDATE_ALL : String = "invalidateAll"; /** * Items were added to the data provider. * * @eventType add * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal The word "model" was replaced with "data provider" above. What should it say? * @internal If this indicates "one or more" items were added, we should use that string. */ - public static const ADD : String = "add"; + public static const ADD : String = "add"; /** * Items were removed from the data provider. * * @eventType remove * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal The word "model" was replaced with "data provider" above. What should it say? * @internal If this indicates "one or more" items were removed, we should use that string. */ - public static const REMOVE : String = "remove"; + public static const REMOVE : String = "remove"; /** * All items were removed from the data provider. * * @eventType removeAll * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal The word "model" was replaced with "data provider" above. What should it say? */ - public static const REMOVE_ALL : String = "removeAll"; + public static const REMOVE_ALL : String = "removeAll"; /** * The items in the data provider were replaced by new items. * * @eventType replace * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal I used "data provider" here instead of the word "model". Correct? */ - public static const REPLACE : String = "replace"; + public static const REPLACE : String = "replace"; /** * The data provider was sorted. This constant is used to indicate * a change in the order of the data, not a change in * the data itself. * * @eventType sort * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal The word "model" was replaced with "data provider" above. What should it say? */ - public static const SORT : String = "sort"; - - } -} + public static const SORT : String = "sort"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataGridEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataGridEvent.as index 2acaeddca3..08122b6b73 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataGridEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataGridEvent.as @@ -1,82 +1,82 @@ -package fl.events -{ - import flash.events.Event; - import fl.events.ListEvent; - +package fl.events +{ + import flash.events.Event; + import fl.events.ListEvent; + /** * The DataGridEvent class defines events that are associated with the DataGrid component. * These include the following events: *
      *
    • DataGridEvent.COLUMN_STRETCH: dispatched after a user resizes a column horizontally.
    • *
    • DataGridEvent.HEADER_RELEASE: dispatched after the user presses and releases the mouse on a column header.
    • *
    • DataGridEvent.ITEM_EDIT_BEGIN: dispatched when an item is ready to be edited.
    • *
    • DataGridEvent.ITEM_EDIT_BEGINNING: dispatched after the user is prepared to edit an item; this is indicated, * for example, by the user releasing the mouse button when the mouse is over the item.
    • *
    • DataGridEvent.ITEM_EDIT_END: dispatched when an edit session is ending.
    • *
    • DataGridEvent.ITEM_FOCUS_IN: dispatched after an item receives focus.
    • *
    • DataGridEvent.ITEM_FOCUS_OUT: dispatched after an item loses focus.
    • *
    * * @see fl.controls.DataGrid * @see DataGridEventReason * * @includeExample examples/DataGridEventExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataGridEvent extends ListEvent - { + public class DataGridEvent extends ListEvent + { /** * The DataGridEvent.COLUMN_STRETCH constant defines the value of the type property * of a columnStretch event object. * *

    This event has the following properties:

    * * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    columnIndexThe zero-based index of the header column * in the columns array of the DataGrid object.
    currentTargetThe object that is actively processing * the event object with an event listener.
    dataFieldThe name of the field or property in the data * associated with the column of the item.
    itemRendererThe header renderer for the column that * was stretched.
    reasonnull
    rowIndexThe zero-based index of the item in the * data provider.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @includeExample ../controls/examples/DataGrid.columnStretch.1.as -noswf * * @eventType columnStretch * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const COLUMN_STRETCH : String = "columnStretch"; + public static const COLUMN_STRETCH : String = "columnStretch"; /** * The DataGridEvent.HEADER_RELEASE constant defines the value of the type property * of a headerRelease event object. * *

    This event has the following properties:

    * * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    columnIndexThe zero-based index of the header column * in the columns array of the DataGrid object.
    currentTargetThe object that is actively processing * the event object with an event listener.
    dataFieldThe name of the field or property in the data * associated with the column of the item.
    itemRendererThe header renderer that was clicked.
    reasonnull
    rowIndex-1
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @includeExample ../controls/examples/DataGrid.headerRelease.1.as -noswf * * @eventType headerRelease * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const HEADER_RELEASE : String = "headerRelease"; + public static const HEADER_RELEASE : String = "headerRelease"; /** * The DataGridEvent.ITEM__EDIT_BEGINNING constant defines the value of the * type property of an itemEditBeginning event object. * *

    This event has the following properties:

    * * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    columnIndexThe zero-based index of the header column * in the columns array of the DataGrid object.
    currentTargetThe object that is actively processing * the event object with an event listener.
    dataFieldThe name of the field or property in the data * associated with the column of the item.
    itemRendererThe item renderer for the item to * be edited.
    reasonnull
    rowIndexThe zero-based index of the item in the * data provider.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemEditBeginning * * @see #ITEM_EDIT_BEGIN * @see #ITEM_EDIT_END * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_EDIT_BEGINNING : String = "itemEditBeginning"; + public static const ITEM_EDIT_BEGINNING : String = "itemEditBeginning"; /** * The DataGridEvent.ITEM_EDIT_BEGIN constant defines the value of * the type property of an itemEditBegin event object. * *

    This event has the following properties:

    * * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    columnIndexThe zero-based index of the header column * in the columns array of the DataGrid object.
    currentTargetThe object that is actively processing * the event object with an event listener.
    dataFieldnull
    itemRendererThe item renderer for the item to * be edited.
    reasonnull
    rowIndexThe zero-based index of the item in the * data provider.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemEditBegin * * @see #ITEM_EDIT_BEGINNING * @see #ITEM_EDIT_END * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_EDIT_BEGIN : String = "itemEditBegin"; + public static const ITEM_EDIT_BEGIN : String = "itemEditBegin"; /** * The DataGridEvent.ITEM_EDIT_END constant defines the value of the type * property of an itemEditEnd event object. * *

    This event has the following properties:

    * * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    columnIndexThe zero-based index of the header column * in the columns array of the DataGrid object.
    currentTargetThe object that is actively processing * the event object with an event listener.
    dataFieldThe name of the field or property in the data * associated with the column of the item.
    itemRendererThe item renderer for the item to * be edited.
    reasonA constant defining the reason for the event. The * value must be a member of the DataGridEventReason class.
    rowIndexThe zero-based index of the item in the * data provider.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemEditEnd * * @see #ITEM_EDIT_BEGIN * @see #ITEM_EDIT_BEGINNING * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_EDIT_END : String = "itemEditEnd"; + public static const ITEM_EDIT_END : String = "itemEditEnd"; /** * The DataGridEvent.ITEM_FOCUS_IN constant defines the value of the type * property of a itemFocusIn event object. * *

    This event has the following properties:

    * * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    columnIndexThe zero-based index of the header column * in the columns array of the DataGrid object.
    currentTargetThe object that is actively processing * the event object with an event listener.
    dataFieldnull
    itemRendererThe item renderer for the item to * be edited.
    reasonnull
    rowIndexThe zero-based index of the item in the * data provider.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemFocusIn * * @see #ITEM_FOCUS_OUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_FOCUS_IN : String = "itemFocusIn"; + public static const ITEM_FOCUS_IN : String = "itemFocusIn"; /** * The DataGridEvent.ITEM_FOCUS_OUT constant defines the value of the type * property of an itemFocusOut event object. * *

    This event has the following properties:

    * * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    columnIndexThe zero-based index of the header column * in the columns array of the DataGrid object.
    currentTargetThe object that is actively processing * the event object with an event listener.
    dataFieldnull
    itemRendererThe item renderer for the item to * be edited.
    reasonnull
    rowIndexThe zero-based index of the item in the * data provider.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemFocusOut * * @see #ITEM_FOCUS_IN * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_FOCUS_OUT : String = "itemFocusOut"; + public static const ITEM_FOCUS_OUT : String = "itemFocusOut"; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _dataField : String; + protected var _dataField : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _itemRenderer : Object; + protected var _itemRenderer : Object; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _reason : String; - + protected var _reason : String; + /** * Gets the item renderer for the item that is being edited or the * header renderer that is being clicked or resized. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get itemRenderer () : Object; + public function get itemRenderer () : Object; /** * Gets or sets the name of the field or property in the data associated with the column. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get dataField () : String; + public function get dataField () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set dataField (value:String) : void; + public function set dataField (value:String) : void; /** * Gets the reason the itemEditEnd event was dispatched. * This property is only valid for events of type DataGridEvent.ITEM_EDIT_END. *

    The possible values are defined in the DataGridEventReason class.

    * * @see fl.controls.DataGrid#event:itemEditEnd * @see DataGridEventReason * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get reason () : String; - + public function get reason () : String; + /** * Creates a new DataGridEvent object with the specified parameters. * * @param type The event type; this value indicates the action that caused the event. * * @param bubbles Indicates whether the event can bubble up the display list hierarchy. * * @param cancelable Indicates whether the behavior associated with the event can be * prevented. * * @param columnIndex The zero-based index of the column that contains the renderer. * * @param rowIndex The zero-based index of the row that contains the renderer. * * @param itemRenderer The item renderer for the item that is being edited or the header * render that is being clicked or stretched. * * @param dataField The name of the field or property in the data associated with the column. * * @param reason The reason the itemEditEnd event was dispatched. * * @see DataGridEventReason * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function DataGridEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, columnIndex:int = -1, rowIndex:int = -1, itemRenderer:Object = null, dataField:String = null, reason:String = null); + public function DataGridEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, columnIndex:int = -1, rowIndex:int = -1, itemRenderer:Object = null, dataField:String = null, reason:String = null); /** * Returns a string that contains all the properties of the DataGridEvent object. The * string is in the following format: * *

    [DataGridEvent type=value bubbles=value * cancelable=value columnIndex=value rowIndex=value * itemRenderer=value dataField=value reason=value]

    * * @return A string that contains all the properties of the DataGridEvent object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; + public function toString () : String; /** * Creates a copy of the DataGridEvent object and sets the value of each * property to match the original. * * @return A new DataGridEvent object with parameter values that match those of the original. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataGridEventReason.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataGridEventReason.as index 8d0ef4c9b2..cf3ec4bd16 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataGridEventReason.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/DataGridEventReason.as @@ -1,26 +1,26 @@ -package fl.events -{ +package fl.events +{ /** * The DataGridEventReason class defines constants that are used for the * values of the reason property of the DataGridEvent object * when the value of the type property is itemEditEnd. * * @see fl.controls.DataGrid * @see DataGridEvent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class DataGridEventReason - { + public class DataGridEventReason + { /** * The user canceled editing and does not want to save the edited * data. * *

    Even if you call the preventDefault() method * from your event listener for the itemEditEnd event, * Flash still calls the destroyItemEditor() editor to close the editor.

    * * @see flash.events.Event#preventDefault() Event.preventDefault() * @see fl.controls.DataGrid#destroyItemEditor() DataGrid.destroyItemEditor() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const CANCELLED : String = "cancelled"; + public static const CANCELLED : String = "cancelled"; /** * The list component lost focus, was scrolled, or is in a state where * editing is not allowed. * *

    Even if you call the preventDefault() method from your event * listener for the itemEditEnd event, Flash still calls the * destroyItemEditor() editor to close the editor.

    * * @see flash.events.Event#preventDefault() Event.preventDefault() * @see fl.controls.DataGrid#destroyItemEditor() DataGrid.destroyItemEditor() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const OTHER : String = "other"; + public static const OTHER : String = "other"; /** * The user moved focus to a new column in the same row. * *

    Your event listener can include logic that permits a change in focus * or that stops it. For example, if an event listener detects that the user * entered an invalid value, the event listener can make a call to the * preventDefault() method to stop focus from being moved to a * new item. The item editor remains open and the user continues to edit the * current item. To close the editor that is associated with the current item, * call the destroyItemEditor() method.

    * * @see #NEW_ROW * @see flash.events.Event#preventDefault() Event.preventDefault() * @see fl.controls.DataGrid#destroyItemEditor() DataGrid.destroyItemEditor() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const NEW_COLUMN : String = "newColumn"; + public static const NEW_COLUMN : String = "newColumn"; /** * Indicates that the user moved focus to a new row. * *

    Your event listener can include logic that permits a change in focus * or that stops it. For example, if an event listener detects that the user * entered an invalid value, the event listener can make a call to the * preventDefault() method to stop focus from being moved to a * new row. The item editor remains open and the user continues to edit the * current item. To close the editor that is associated with the current item, * call the destroyItemEditor() method.

    * * @see #NEW_COLUMN * @see flash.events.Event#preventDefault() Event.preventDefault() * @see fl.controls.DataGrid#destroyItemEditor() DataGrid.destroyItemEditor() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const NEW_ROW : String = "newRow"; - - } -} + public static const NEW_ROW : String = "newRow"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/InteractionInputType.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/InteractionInputType.as index db4a2afd7d..00e5bdb661 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/InteractionInputType.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/InteractionInputType.as @@ -1,18 +1,18 @@ -package fl.events -{ +package fl.events +{ /** * The InteractionInputType class defines constants for the values of the * triggerEvent property of the SliderEvent object. These constants define strings * to identify the sources of input that can trigger an event: the mouse and the keyboard. * * @see SliderEvent#triggerEvent * * @includeExample examples/InteractionInputTypeExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal Can a pointing device that is not a mouse cause these events to be dispatched? */ - public class InteractionInputType - { + public class InteractionInputType + { /** * The InteractionInputType.MOUSE constant defines the value of * the type property of a mouse event object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * @internal Seems like another type of pointing device could also generate this event? */ - public static const MOUSE : String = 'mouse'; + public static const MOUSE : String = 'mouse'; /** * The InteractionInputType.KEYBOARD constant defines the value of * the type property of a keyboard event object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const KEYBOARD : String = 'keyboard'; - - } -} + public static const KEYBOARD : String = 'keyboard'; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ListEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ListEvent.as index 9ec6e5f442..9424a524b3 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ListEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ListEvent.as @@ -1,73 +1,73 @@ -package fl.events -{ - import flash.events.Event; - +package fl.events +{ + import flash.events.Event; + /** * The ListEvent class defines events for list-based components including the List, DataGrid, TileList, and ComboBox components. * These events include the following: *
      *
    • ListEvent.ITEM_CLICK: dispatched after the user clicks the mouse over an item in the component.
    • *
    • ListEvent.ITEM_DOUBLE_CLICK: dispatched after the user clicks the mouse twice in rapid succession * over an item in the component.
    • *
    • ListEvent.ITEM_ROLL_OUT: dispatched after the user rolls the mouse pointer out of an item in the component.
    • *
    • ListEvent.ITEM_ROLL_OVER: dispatched after the user rolls the mouse pointer over an item in the component.
    • *
    * * @see fl.controls.List List * @see fl.controls.SelectableList SelectableList * * @includeExample examples/ListEventExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ListEvent extends Event - { + public class ListEvent extends Event + { /** * Defines the value of the type property of an * itemRollOut event object. * *

    This event has the following properties:

    * * * * * * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is * no default behavior to cancel.
    columnIndexThe zero-based index of the column that * contains the renderer.
    currentTargetThe object that is actively processing * the event object with an event listener.
    indexThe zero-based index in the DataProvider * that contains the renderer.
    itemA reference to the data that belongs to the renderer.
    rowIndexThe zero-based index of the row that * contains the renderer.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemRollOut * * @see #ITEM_ROLL_OVER * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_ROLL_OUT : String = "itemRollOut"; + public static const ITEM_ROLL_OUT : String = "itemRollOut"; /** * Defines the value of the type property of an itemRollOver * event object. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is * no default behavior to cancel.
    columnIndexThe zero-based index of the column that * contains the renderer.
    currentTargetThe object that is actively processing * the event object with an event listener.
    indexThe zero-based index in the DataProvider * that contains the renderer.
    itemA reference to the data that belongs to the renderer.
    rowIndexThe zero-based index of the row that * contains the renderer.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemRollOver * * @see #ITEM_ROLL_OUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_ROLL_OVER : String = "itemRollOver"; + public static const ITEM_ROLL_OVER : String = "itemRollOver"; /** * Defines the value of the type property of an itemClick * event object. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelabletrue
    columnIndexThe zero-based index of the column that * contains the renderer.
    currentTargetThe object that is actively processing * the event object with an event listener.
    indexThe zero-based index in the DataProvider * that contains the renderer.
    itemA reference to the data that belongs to the renderer. *
    rowIndexThe zero-based index of the row that * contains the renderer.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemClick * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_CLICK : String = "itemClick"; + public static const ITEM_CLICK : String = "itemClick"; /** * Defines the value of the type property of an itemDoubleClick * event object. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelabletrue
    columnIndexThe zero-based index of the column that * contains the renderer.
    currentTargetThe object that is actively processing * the event object with an event listener.
    indexThe zero-based index in the DataProvider * that contains the renderer.
    itemA reference to the data that belongs to the renderer. *
    rowIndexThe zero-based index of the row that * contains the renderer.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType itemDoubleClick * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ITEM_DOUBLE_CLICK : String = "itemDoubleClick"; + public static const ITEM_DOUBLE_CLICK : String = "itemDoubleClick"; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _rowIndex : int; + protected var _rowIndex : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _columnIndex : int; + protected var _columnIndex : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _index : int; + protected var _index : int; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _item : Object; - + protected var _item : Object; + /** * Gets the row index of the item that is associated with this event. * * @see #columnIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get rowIndex () : Object; + public function get rowIndex () : Object; /** * Gets the column index of the item that is associated with this event. * * @see #rowIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get columnIndex () : int; + public function get columnIndex () : int; /** * Gets the zero-based index of the cell that contains the renderer. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get index () : int; + public function get index () : int; /** * Gets the data that belongs to the current cell renderer. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get item () : Object; - + public function get item () : Object; + /** * Creates a new ListEvent object with the specified parameters. * * @param type The event type; this value identifies the action that caused the event. * * @param bubbles Indicates whether the event can bubble up the display list hierarchy. * * @param cancelable Indicates whether the behavior associated with the event can be * prevented. * * @param columnIndex The zero-based index of the column that contains the renderer or visual * representation of the data in the column. * * @param rowIndex The zero-based index of the row that contains the renderer or visual * representation of the data in the row. * * @param index The zero-based index of the item in the DataProvider. * * @param item A reference to the data that belongs to the renderer. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ListEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, columnIndex:int = -1, rowIndex:int = -1, index:int = -1, item:Object = null); + public function ListEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, columnIndex:int = -1, rowIndex:int = -1, index:int = -1, item:Object = null); /** * Returns a string that contains all the properties of the ListEvent object. The string * is in the following format: * *

    [ListEvent type=value bubbles=value * cancelable=value columnIndex=value * rowIndex=value]

    * * @return A string representation of the ListEvent object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; + public function toString () : String; /** * Creates a copy of the ListEvent object and sets the value of each parameter to match * the original. * * @return A new ListEvent object with parameter values that match those of the original. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ScrollEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ScrollEvent.as index 2902b28b8e..2d87b9f91d 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ScrollEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/ScrollEvent.as @@ -1,53 +1,53 @@ -package fl.events -{ - import flash.events.Event; - +package fl.events +{ + import flash.events.Event; + /** * The ScrollEvent class defines the scroll event that is associated with the ScrollBar component. * * @see fl.controls.ScrollBar ScrollBar * @see fl.controls.ScrollBarDirection ScrollBarDirection * @see fl.core.UIComponent UIComponent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ScrollEvent extends Event - { + public class ScrollEvent extends Event + { /** * Defines the value of the type property of a scroll * event object. * *

    This event has the following properties:

    * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    currentTargetThe object that is actively processing * the event object with an event listener.
    delta1; a value that indicates * how much scrolling was done. *
    directionvertical; the direction of the * ScrollBar.
    position0; the position of the * Scrollbar thumb after it was moved.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    * * @eventType scroll * * @includeExample ../containers/examples/ScrollPane.scroll.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const SCROLL : String = "scroll"; + public static const SCROLL : String = "scroll"; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _direction : String; + private var _direction : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _delta : Number; + private var _delta : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _position : Number; - + private var _position : Number; + /** * Gets a constant value that indicates the direction of movement associated with the event. * A value of ScrollBarDirection.HORIZONTAL indicates horizontal movement; a value * of ScrollBarDirection.VERTICAL indicates vertical movement. * * @see fl.controls.ScrollBarDirection * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get direction () : String; + public function get direction () : String; /** * Gets the size of the change in scroll position, in pixels. A positive value * indicates that the direction of the scroll was down or to the right. A negative value indicates that * the direction of the scroll was up or to the left. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get delta () : Number; + public function get delta () : Number; /** * Gets the current scroll position, in pixels. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get position () : Number; - + public function get position () : Number; + /** * Creates a new ScrollEvent object with the specified parameters. * * @param direction The direction of movement associated with the event. A value of * ScrollBarDirection.HORIZONTAL indicates horizontal movement; a value of * ScrollBarDirection.VERTICAL indicates vertical movement. * * @param delta The change in scroll position, in pixels. A positive value indicates that the direction * of the scroll was down or to the right. A negative value indicates that the * direction of the scroll was up or to the left. * * @param position The current scroll position. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function ScrollEvent (direction:String, delta:Number, position:Number); + public function ScrollEvent (direction:String, delta:Number, position:Number); /** * Returns a string that contains all the properties of the ScrollEvent object. The * string has the following format: * *

    [ScrollEvent type=value bubbles=value * cancelable=value direction=value delta=value * position=value]

    * * @return A string representation of the ScrollEvent object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; + public function toString () : String; /** * Creates a copy of the ScrollEvent object and sets the value of each parameter to * match the original. * * @return A new ScrollEvent object with parameter values that match the original. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/SliderEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/SliderEvent.as index c3d7508ac1..fc98bbd02c 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/SliderEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/SliderEvent.as @@ -1,73 +1,73 @@ -package fl.events -{ - import flash.events.Event; - +package fl.events +{ + import flash.events.Event; + /** * The SliderEvent class defines events that are associated with the Slider component. * These include the following: *
      *
    • SliderEvent.CHANGE: dispatched after there is a change in the position of the slider.
    • *
    • SliderEvent.THUMB_DRAG: dispatched when a user drags the thumb of the slider.
    • *
    • SliderEvent.THUMB_PRESS: dispatched when a user presses the thumb of the slider.
    • *
    • SliderEvent.THUMB_RELEASE: dispatched when the user releases the thumb of the slider.
    • *
    * @see SliderEventClickTarget * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class SliderEvent extends Event - { + public class SliderEvent extends Event + { /** * Defines the value of the type property of a change event object. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    clickTargetIdentifies whether the slider track * or a slider thumb was pressed.
    currentTargetThe object that is actively processing * the event object with an event listener.
    keyCodeIf the event was triggered by a key press, * the code for the key that was pressed.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    triggerEventThe type of device that triggered the event. A value * of InteractionInputType.MOUSE indicates that a mouse was the source of input; * a value of InteractionInputType.KEYBOARD indicates that a keyboard was * the source of input.
    valueThe value of the slider after the event.
    * * @eventType change * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const CHANGE : String = "change"; + public static const CHANGE : String = "change"; /** * Defines the value of the type property of a thumbDrag event * object. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    clickTargetIdentifies whether the slider track * or a slider thumb was pressed.
    currentTargetThe object that is actively processing * the event object with an event listener.
    keyCodeIf the event was triggered by a key press, * the code for the key that was pressed.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    triggerEventThe type of device that triggered the event. A value * of InteractionInputType.MOUSE indicates that a mouse was the source of the * input; a value of InteractionInputType.KEYBOARD indicates that a keyboard * was the source of the input.
    valueThe value of the slider after the event.
    * * @eventType thumbDrag * * @see #THUMB_PRESS * @see #THUMB_RELEASE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const THUMB_DRAG : String = "thumbDrag"; + public static const THUMB_DRAG : String = "thumbDrag"; /** * Defines the value of the type property of a thumbPress * event object. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    clickTargetIdentifies whether the slider track * or a slider thumb was pressed.
    currentTargetThe object that is actively processing * the event object with an event listener.
    keyCodeIf the event was triggered by a key press, * the code for the key that was pressed.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    triggerEventThe type of device that triggered the event. A value * of InteractionInputType.MOUSE indicates that a mouse was the source of the * input; a value of InteractionInputType.KEYBOARD indicates that a keyboard * was the source of the input.
    valueThe value of the slider after the event.
    * * @eventType thumbPress * * @see #THUMB_DRAG * @see #THUMB_RELEASE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const THUMB_PRESS : String = "thumbPress"; + public static const THUMB_PRESS : String = "thumbPress"; /** * Defines the value of the type property of a thumbRelease * event object. * *

    This event has the following properties:

    * * * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default * behavior to cancel.
    clickTargetIdentifies whether the slider track * or a slider thumb was pressed.
    currentTargetThe object that is actively processing * the event object with an event listener.
    keyCodeIf the event was triggered by a key press, * the code for the key that was pressed.
    targetThe object that dispatched the event. The target is * not always the object listening for the event. Use the currentTarget * property to access the object that is listening for the event.
    triggerEventThe type of device that triggered the event. A value * of InteractionInputType.MOUSE indicates that a mouse was the source of the * input; a value of InteractionInputType.KEYBOARD indicates that a keyboard * was the source of the input.
    valueThe value of the slider after the event.
    * * @eventType thumbRelease * * @see #THUMB_DRAG * @see #THUMB_PRESS * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const THUMB_RELEASE : String = "thumbRelease"; + public static const THUMB_RELEASE : String = "thumbRelease"; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _triggerEvent : String; + protected var _triggerEvent : String; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _value : Number; + protected var _value : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _keyCode : Number; + protected var _keyCode : Number; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - protected var _clickTarget : String; - + protected var _clickTarget : String; + /** * Gets the new value of the slider, based on its position. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get value () : Number; + public function get value () : Number; /** * Gets the key code for the key that was pressed to trigger the event. * A key code is a numeric value that identifies the key that was pressed. * * @see flash.events.KeyboardEvent#keyCode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get keyCode () : Number; + public function get keyCode () : Number; /** * Gets the type of device that was used to send the input. A value of InteractionInputType.MOUSE * indicates that a mouse was the source of the input; a value of InteractionInputType.KEYBOARD * indicates that a keyboard was the source of the input. * * @see SliderEventClickTarget SliderEventClickTarget * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get triggerEvent () : String; + public function get triggerEvent () : String; /** * Gets a string that indicates whether the slider thumb or a slider track was pressed. * A value of SliderEventClickTarget.THUMB indicates that the slider thumb was * pressed; a value of SliderEventClickTarget.TRACK indicates that the slider * track was pressed. * * @see SliderEventClickTarget SliderEventClickTarget * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get clickTarget () : String; - + public function get clickTarget () : String; + /** * Creates a new SliderEvent object with the specified parameters. * * @param type The event type; this value identifies the action that triggered the event. * * @param value The new value of the slider. * * @param clickTarget Indicates whether a slider thumb or the slider track was * pressed. A value of SliderEventClickTarget.THUMB indicates that * the slider thumb was pressed; a value of SliderEventClickTarget.TRACK * indicates that the slider track was pressed. * * @param triggerEvent A String that indicates the source of the input. A value of * InteractionInputType.MOUSE indicates that the mouse was the source of input; * a value of InteractionInputType.KEYBOARD indicates that the keyboard was * the source of input. * * @param keyCode If the event was triggered by a key press, this value is the key code * that identifies that key. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function SliderEvent (type:String, value:Number, clickTarget:String, triggerEvent:String, keyCode:int = 0); + public function SliderEvent (type:String, value:Number, clickTarget:String, triggerEvent:String, keyCode:int = 0); /** * Returns a string that contains all the properties of the SliderEvent object. The * string is in the following format: * *

    [SliderEvent type=value value=value * bubbles=value cancelable=value keycode=value * triggerEvent=value clickTarget=value]

    * * @return A string representation of the SliderEvent object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function toString () : String; + public function toString () : String; /** * Creates a copy of the SliderEvent object and sets the value of each parameter to match * the original. * * @return A copy of the current SliderEvent instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/SliderEventClickTarget.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/SliderEventClickTarget.as index 47a4abffa4..e3339d6136 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/SliderEventClickTarget.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/events/SliderEventClickTarget.as @@ -1,18 +1,18 @@ -package fl.events -{ +package fl.events +{ /** * The SliderEventClickTarget class defines constants for the values of the clickTarget * property of the SliderEvent class. * * @see SliderEvent * * @includeExample examples/SliderEventClickTargetExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class SliderEventClickTarget - { + public class SliderEventClickTarget + { /** * The Slider thumb was clicked. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const THUMB : String = 'thumb'; + public static const THUMB : String = 'thumb'; /** * The Slider track was clicked. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const TRACK : String = 'track'; - - } -} + public static const TRACK : String = 'track'; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/lang/Locale.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/lang/Locale.as index eabb69eeb6..e27d238093 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/lang/Locale.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/lang/Locale.as @@ -1,99 +1,99 @@ -package fl.lang -{ - import flash.system.Capabilities; - import flash.xml.*; - import flash.net.*; - import flash.events.*; - +package fl.lang +{ + import flash.system.Capabilities; + import flash.xml.*; + import flash.net.*; + import flash.events.*; + /** * The fl.lang.Locale class allows you to control how multilanguage text is displayed in a SWF file. * The Flash Strings panel allows you to use string IDs instead of string literals in dynamic text fields. This allows you to create a SWF file that displays text loaded from a language-specific XML file. The XML file must use the XML Localization Interchange File Format (XLIFF). There are three ways to display the language-specific strings contained in the XLIFF files: *
      *
    • "automatically at runtime"—Flash Player replaces string IDs with strings from the XML file matching the default system language code returned by flash.system.capabilities.language.
    • *
    • "manually using stage language"—String IDs are replaced by strings at compile time and cannot be changed by Flash Player.
    • *
    • "via ActionScript at runtime"—String ID replacement is controlled using ActionScript at runtime. This option gives you control over both the timing and language of string ID replacement.
    • *
    *

    You can use the properties and methods of this class when you want to replace the string IDs "via ActionScript at runtime."

    *

    All of the properties and methods available are static, which means that they are accessed through the fl.lang.Locale class itself rather than through an instance of the class.

    * *

    Note: The Locale class is installed in the Flash Authoring classpath and is automatically compiled into your SWF files. Using the Locale class increases the SWF file size slightly since the class is compiled into the SWF.

    * @helpid * @category Class * @playerversion Flash 9 * @langversion 3.0 * @see flash.system.Capabilities#language */ - public class Locale extends flash.events.EventDispatcher - { - private static var flaName : String; - private static var defaultLang : String; - private static var xmlLang : String; - private static var xmlMap : Object; - private static var xmlDoc : XMLDocument; - private static var stringMap : Object; - private static var delayedInstanceArray : Array; - private static var currentXMLMapIndex : Number; - private static var callback : Function; - private static var autoReplacement : Boolean; - private static var currentLang : String; - private static var stringMapList : Object; - private static var _xmlLoaded : Boolean; - + public class Locale extends flash.events.EventDispatcher + { + private static var flaName : String; + private static var defaultLang : String; + private static var xmlLang : String; + private static var xmlMap : Object; + private static var xmlDoc : XMLDocument; + private static var stringMap : Object; + private static var delayedInstanceArray : Array; + private static var currentXMLMapIndex : Number; + private static var callback : Function; + private static var autoReplacement : Boolean; + private static var currentLang : String; + private static var stringMapList : Object; + private static var _xmlLoaded : Boolean; + /** * Determines whether strings are replaced automatically after loading the XML file. If set to true, the text replacement method is equivalent to the Strings panel setting "automatically at runtime". This means that Flash Player will determine the default language of the host environment and automatically display the text in that language. If set to false, the text replacement method is equivalent to the Strings panel setting "via ActionScript at runtime". This means that you are responsible for loading the appropriate XML file to display the text. * *

    The default value of this property reflects the setting that you select for Replace strings in the Strings panel dialog box: true for "automatically at runtime" (the default setting) and false for "via ActionScript at runtime".

    * * @example The following example uses the Locale.autoReplace property to populate the dynamically created greeting_txt text field on the Stage with the contents of the IDS_GREETING string in the English XML file. In the Strings panel, click the Settings button to open the Settings dialog box. You can add two active languages using the Settings dialog box: English (en) and French (fr), set the replacement strings radio option to "via ActionScript at runtime", and click OK. Finally, enter a string ID of IDS_GREETING in the Strings panel, and add text for each active language. * * var greeting_txt:TextField = new TextField(); * greeting_txt.x = 40; * greeting_txt.y = 40; * greeting_txt.width = 200; * greeting_txt.height = 20; * greeting_txt.autoSize = TextFieldAutoSize.LEFT; * Locale.autoReplace = true; * Locale.addDelayedInstance(greeting_txt, "IDS_GREETING"); * Locale.loadLanguageXML("en"); * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Property * * */ - public static function get autoReplace () : Boolean; - public static function set autoReplace (auto:Boolean) : void; + public static function get autoReplace () : Boolean; + public static function set autoReplace (auto:Boolean) : void; /** * An array containing language codes for the languages that have been specified or loaded into the FLA file. The language codes are not sorted alphabetically. * * @example The following example loads a language XML file based on the current value of a ComboBox component. You drag a ComboBox component onto the Stage and give it an instance name of lang_cb. Using the Text tool, you create a dynamic text field and give it an instance name of greeting_txt. In the Strings panel, you add at least two active languages, set the replace strings radio option to "via ActionScript at runtime", and click OK. Next, you add a string ID of IDS_GREETING and enter text for each active language. Finally, you add the following ActionScript code to Frame 1 of the main Timeline: * * Locale.setLoadCallback(localeListener); * lang_cb.dataProvider = Locale.languageCodeArray.sort(); * lang_cb.addEventListener("change", langListener); * * function langListener(eventObj:Object):void { * Locale.loadLanguageXML(eventObj.target.value); * } * function localeListener(success:Boolean):void { * if (success) { * greeting_txt.text = Locale.loadString("IDS_GREETING"); * } else { * greeting_txt.text = "unable to load language XML file."; * } * } * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Property[read-only] * */ - public static function get languageCodeArray () : Array; + public static function get languageCodeArray () : Array; /** * An array containing all the string IDs in the FLA file. The string IDs are not sorted alphabetically. * * @example The following example traces the Locale.stringIDArray property for the currently loaded language XML file. Click the Settings button in the Strings panel to open the Settings dialog box. Next, you add two active languages: English (en) and French (fr), set the replace strings radio control to "via ActionScript at runtime", and click OK. In the Strings panel, you add a string ID of IDS_GREETING, and then add text for each active language. * * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML("fr"); * function localeCallback(success:Boolean) { * trace(success); * trace(Locale.stringIDArray); // IDS_GREETING * trace(Locale.loadStringEx("IDS_GREETING", "fr")); // bonjour * } * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Property[read-only] */ - public static function get stringIDArray () : Array; - + public static function get stringIDArray () : Array; + /** * @private No need to document this, users won't need it. This is old code that isn't used by Flash Player 8, * but is used when SWFs are published for Flash Player 7. */ - public static function setFlaName (name:String) : void; + public static function setFlaName (name:String) : void; /** * The default language code as set in the Strings panel dialog box or by calling the setDefaultLang() method. * * @return Returns the default language code. * * @example The following example creates a variable called defLang, which is used to hold the initial default language for the Flash document. You click the Settings button in the Strings panel to launch the Settings dialog box. Then you add two active languages: English (en) and French (fr), set the replace strings radio control to "via ActionScript at runtime", and click OK. In the Strings panel, you add a string ID of IDS_GREETING, and then add text for each active language. * * var defLang:String = "fr"; * Locale.setDefaultLang(defLang); * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML(Locale.getDefaultLang()); * function localeCallback(success:Boolean) { * if (success) { * trace(Locale.stringIDArray); // IDS_GREETING * trace(Locale.loadString("IDS_GREETING")); * } else { * trace("unable to load XML"); * } * } * * @see #setDefaultLang() Locale.setDefaultLang() * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function getDefaultLang () : String; + public static function getDefaultLang () : String; /** * Sets the default language code. * @param langCode A string representing a language code. * * @example The following example creates a variable called defLang, which is used to hold the initial default language for the Flash document. You click the Settings button in the Strings panel to open the Settings dialog box. Then you add two active languages: English (en) and French (fr), set the replace strings radio control to "via ActionScript at runtime", and click OK. In the Strings panel, you add a string ID of IDS_GREETING, and then add text for each active language. * * var defLang:String = "fr"; * Locale.setDefaultLang(defLang); * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML(Locale.getDefaultLang()); * function localeCallback(success:Boolean) { * if (success) { * trace(Locale.stringIDArray); // IDS_GREETING * trace(Locale.loadString("IDS_GREETING")); * } else { * trace("unable to load XML"); * } * } * * @see #getDefaultLang() Locale.getDefaultLang() * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function setDefaultLang (langCode:String) : void; + public static function setDefaultLang (langCode:String) : void; /** * Adds the {languageCode and languagePath} pair into the internal array for later use. * This is primarily used by Flash when the strings replacement method is "automatically at runtime" * or "via ActionScript at runtime". * @param langCode The language code. * @param path The XML path to add. * * @example The following example uses the setInterval() method to check whether the language XML file has successfully loaded. * * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML("en"); * // create interval to check if language XML file is loaded * var locale_int:Number = setInterval(checkLocaleStatus, 10); * function checkLocaleStatus():void { * if (Locale.checkXMLStatus()) { * clearInterval(locale_int); * trace("clearing interval @ " + getTimer() + " ms"); * } * } * // callback function for Locale.setLoadCallback() * function localeCallback(success:Boolean):void { * greeting_txt.text = Locale.loadString("IDS_GREETING"); * } * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function addXMLPath (langCode:String, path:String) : void; + public static function addXMLPath (langCode:String, path:String) : void; /** * Adds the {instance, string ID} pair into the internal array for later use. * This is primarily used by Flash when the strings replacement method is "automatically at runtime". * @param instance Instance name of the text field to populate. * @param stringID Language string ID. * * @example The following example uses the autoReplace property and addDelayedInstance() method to populate a text field on the Stage with the IDS_GREETING string from the English XML language file. * * greeting_txt.autoSize = TextFieldAutoSize.LEFT; * Locale.autoReplace = true; * Locale.addDelayedInstance(greeting_txt, "IDS_GREETING"); * Locale.loadLanguageXML("en"); * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function addDelayedInstance (instance:Object, stringID:String); + public static function addDelayedInstance (instance:Object, stringID:String); /** * Returns true if the XML file is loaded; false otherwise. * @return Returns true if the XML file is loaded; false otherwise. * * @example The following example uses an interval to check every 10 milliseconds to see if the language file has successfully loaded. Once the XML file has loaded, the greeting_txt text field instance on the Stage is populated with the IDS_GREETING string from the language XML file. * * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML("en"); * // create interval to check if language XML file is loaded * var locale_int:Number = setInterval(checkLocaleStatus, 10); * function checkLocaleStatus():void { * if (Locale.checkXMLStatus()) { * clearInterval(locale_int); * trace("clearing interval @ " + getTimer() + " ms"); * } * } * // callback function for Locale.setLoadCallback() * function localeCallback(success:Boolean):void { * greeting_txt.text = Locale.loadString("IDS_GREETING"); * } * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function checkXMLStatus () : Boolean; + public static function checkXMLStatus () : Boolean; /** * Sets the callback function that is called after the XML file is loaded. * @param loadCallback The function to call when the XML language file loads. * * @example The following example uses an interval to check every 10 milliseconds to see if the language file has successfully loaded. Once the XML file has loaded, the greeting_txt text field instance on the Stage is populated with the IDS_GREETING string from the XML language file. * * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML("en"); * // create interval to check if language XML file is loaded * var locale_int:Number = setInterval(checkLocaleStatus, 10); * function checkLocaleStatus():void { * if (Locale.checkXMLStatus()) { * clearInterval(locale_int); * trace("clearing interval @ " + getTimer() + " ms"); * } * } * // callback function for Locale.setLoadCallback() * function localeCallback(success:Boolean):void { * greeting_txt.text = Locale.loadString("IDS_GREETING"); * } * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function setLoadCallback (loadCallback:Function); + public static function setLoadCallback (loadCallback:Function); /** * Returns the string value associated with the given string ID in the current language. * @param id The identification (ID) number of the string to load. * @return The string value associated with the given string ID in the current language. * * @example The following example uses an interval to check every 10 milliseconds to see if the language file has successfully loaded. Once the XML file has loaded, the greeting_txt text field instance on the Stage is populated with the IDS_GREETING string from the XML language file. * * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML("en"); * // create interval to check if language XML file is loaded * var locale_int:Number = setInterval(checkLocaleStatus, 10); * function checkLocaleStatus():void { * if (Locale.checkXMLStatus()) { * clearInterval(locale_int); * trace("clearing interval @ " + getTimer() + " ms"); * } * } * // callback function for Locale.setLoadCallback() * function localeCallback(success:Boolean):void { * greeting_txt.text = Locale.loadString("IDS_GREETING"); * } * * @see #loadStringEx() Locale.loadStringEx() * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function loadString (id:String) : String; + public static function loadString (id:String) : String; /** * Returns the string value associated with the given string ID and language code. * To avoid unexpected XML file loading, loadStringEx() does not load the XML language file if the XML file is not already loaded. You should decide on the right time to call the loadLanguageXML() method if you want to load a XML language file. * @param stringID The identification (ID) number of the string to load. * @param languageCode The language code. * @return The string value associated with the given string ID in the language specified by the languageCode parameter. * * @example The following example uses the loadStringEx() method to trace the value of the IDS_GREETING string for the currently loaded French language XML file. * * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML("fr"); * function localeCallback(success:Boolean) { * trace(success); * trace(Locale.stringIDArray); // IDS_GREETING * trace(Locale.loadStringEx("IDS_GREETING", "fr")); // bonjour * } * * @see #loadString() Locale.loadString() * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function loadStringEx (stringID:String, languageCode:String) : String; + public static function loadStringEx (stringID:String, languageCode:String) : String; /** * Sets the new string value of a given string ID and language code. * * @param stringID The identification (ID) number of the string to set. * @param languageCode The language code. * @param stringValue A string value. * * @example The following example uses the setString() method to set the IDS_WELCOME string for both English (en) and French (fr). * * Locale.setString("IDS_WELCOME", "en", "hello"); * Locale.setString("IDS_WELCOME", "fr", "bonjour"); * trace(Locale.loadStringEx("IDS_WELCOME", "en")); // hello * * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function setString (stringID:String, languageCode:String, stringValue:String) : void; + public static function setString (stringID:String, languageCode:String, stringValue:String) : void; /** * Automatically determines the language to use and loads the XML language file. * This is primarily used by Flash when the strings replacement method is "automatically at runtime". * * @example This example shows how to use the initialize() method to automatically populate the greeting_txt text field on the Stage with the user's current OS language. Instead of using the initialize() method directly, use the string replacement method of "automatically at runtime". * * trace(System.capabilities.language); * Locale.autoReplace = true; * Locale.addDelayedInstance(greeting_txt, "IDS_GREETING"); * Locale.initialize(); * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function initialize () : void; + public static function initialize () : void; /** * Loads the specified XML language file. * * @param xmlLanguageCode The language code for the XML language file that you want to load. * @param customXmlCompleteCallback Custom callback function to call when XML language file loads. * * @example The following example uses the loadLanguageXML() method to load the English (en) XML language file. Once the language file loads, the localeCallback() method is called and populates the greeting_txt text field on the Stage with the contents of the IDS_GREETING string in the XML file. * * Locale.setLoadCallback(localeCallback); * Locale.loadLanguageXML("en"); * // create interval to check if language XML file is loaded * var locale_int:Number = setInterval(checkLocaleStatus, 10); * function checkLocaleStatus():void { * if (Locale.checkXMLStatus()) { * clearInterval(locale_int); * trace("clearing interval @ " + getTimer() + " ms"); * } * } * // callback function for Locale.setLoadCallback() * function localeCallback(success:Boolean):void { * greeting_txt.text = Locale.loadString("IDS_GREETING"); * } * * @playerversion Flash 9 * @langversion 3.0 * @helpid * @category Method */ - public static function loadLanguageXML (xmlLanguageCode:String, customXmlCompleteCallback:Function = null) : void; - private static function loadXML (langCode:String); - private static function onXMLLoad (eventObj:Event); - private static function parseStringsXML (doc:XMLDocument) : void; - private static function parseXLiff (node:XMLNode) : void; - private static function parseFile (node:XMLNode) : void; - private static function parseBody (node:XMLNode) : void; - private static function parseTransUnit (node:XMLNode) : void; - private static function parseSource (node:XMLNode) : String; - private static function assignDelayedInstances () : void; - } -} + public static function loadLanguageXML (xmlLanguageCode:String, customXmlCompleteCallback:Function = null) : void; + private static function loadXML (langCode:String); + private static function onXMLLoad (eventObj:Event); + private static function parseStringsXML (doc:XMLDocument) : void; + private static function parseXLiff (node:XMLNode) : void; + private static function parseFile (node:XMLNode) : void; + private static function parseBody (node:XMLNode) : void; + private static function parseTransUnit (node:XMLNode) : void; + private static function parseSource (node:XMLNode) : String; + private static function assignDelayedInstances () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/livepreview/LivePreviewParent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/livepreview/LivePreviewParent.as index 003db0184b..0de7b79636 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/livepreview/LivePreviewParent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/livepreview/LivePreviewParent.as @@ -1,34 +1,34 @@ -package fl.livepreview -{ - import flash.display.*; - import flash.external.*; - import flash.utils.*; - +package fl.livepreview +{ + import flash.display.*; + import flash.external.*; + import flash.utils.*; + /** * The LivePreviewParent class provides the timeline for a SWC file * or for a compiled clip that is being exported when ActionScript 3.0 * is selected. * *

    When a property is set on a component instance or when a component * instance is resized on the Stage, Flash makes calls to the methods of * this class, which in turn call methods in your component code to set * the properties and to resize the component.

    * *

    In cases where your component must implement a specific action when * it is in live preview mode, use the following code to test for live preview * mode:

    * * var isLivePreview:Boolean = (parent != null && getQualifiedClassName(parent) == "fl.livepreview::LivePreviewParent"); * *

    The LivePreviewParent class supports the definition of a setSize() * method that uses width and height values to resize * a component. If you do not define a setSize() method, this object * sets the width and height properties individually.

    * *

    You can also use this class to create a custom live preview SWF file without * creating a SWC file; however, it is probably easier to create a component live * preview file by:

    *
      *
    • Exporting your component as a SWC file.
    • *
    • Changing the .swc file extension to .zip.
    • *
    • Extracting the SWF file within the ZIP file.
    • *
    *

    To create a component live preview file in this way, follow these steps:

    *
      *
    1. Create a new Flash document.
    2. *
    3. Set its document class to fl.livepreview.LivePreviewParent.
    4. *
    5. Drag your component to the Stage and position it to x and y coordinates of 0.
    6. *
    7. Check to ensure that the component parameters remain at their default settings. * This should be the case if you drag the component from the Library panel or from the * Components panel.
    8. *
    9. Select Modify > Document from the main menu and, for the Match option, click Contents.
    10. *
    11. Click OK.
    12. *
    13. Publish the file to see the resulting SWF file as a custom live preview * SWF file.
    14. *
    15. Right-click the asset in the Library panel and select Component Definition from the context menu.
    16. *
    17. The Component Definition dialog box allows you to specify a custom live preview * SWF file for a component.
    18. *
    * *

    In some cases, you may want to have a custom live preview SWF file that is * completely different from your component. See the live preview of the fl.containers.UILoader * component for such an example. This live preview does not use the properties of UILoader, * nor does it implement getter and setter functions for these properties. It does, however, * implement a setSize() method that uses width and height * parameters to draw the component at the new size.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class LivePreviewParent extends MovieClip - { + public class LivePreviewParent extends MovieClip + { /** * The component instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var myInstance : DisplayObject; - + public var myInstance : DisplayObject; + /** * Initializes the scale and align modes of the Stage, sets the * myInstance property, resizes myInstance to * the proper size and uses the ExternalInterface class to expose * functions to Flash. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function LivePreviewParent (); + public function LivePreviewParent (); /** * Resizes the component instance on the Stage to the specified * dimensions, either by calling a user-defined method, or by * separately setting the width and height * properties. * *

    This method is called by Flash Player.

    * * @param width The new width for the myInstance instance. * @param height The new height for the myInstance instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function onResize (width:Number, height:Number) : void; + public function onResize (width:Number, height:Number) : void; /** * Updates the properties of the component instance. * This method is called by Flash Player when there * is a change in the value of a property. This method * updates all component properties, whether or not * they were changed. * * @param updateArray An array of parameter names and values. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function onUpdate (...updateArray:Array) : void; + public function onUpdate (...updateArray:Array) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function updateCollection (collDesc:Object, index:String) : void; - } -} + private function updateCollection (collDesc:Object, index:String) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/FocusManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/FocusManager.as index 783ff626b6..f054b8f5e4 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/FocusManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/FocusManager.as @@ -1,263 +1,263 @@ -package fl.managers -{ - import flash.display.Sprite; - import flash.display.MovieClip; - import flash.display.Stage; - import flash.display.SimpleButton; - import flash.display.DisplayObject; - import flash.display.DisplayObjectContainer; - import flash.display.InteractiveObject; - import flash.text.TextField; - import flash.text.TextFieldType; - import flash.ui.Keyboard; - import flash.events.Event; - import flash.events.FocusEvent; - import flash.events.MouseEvent; - import flash.events.KeyboardEvent; - import fl.controls.Button; - import fl.controls.TextInput; - import fl.core.UIComponent; - import flash.system.Capabilities; - import flash.utils.*; - +package fl.managers +{ + import flash.display.Sprite; + import flash.display.MovieClip; + import flash.display.Stage; + import flash.display.SimpleButton; + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + import flash.display.InteractiveObject; + import flash.text.TextField; + import flash.text.TextFieldType; + import flash.ui.Keyboard; + import flash.events.Event; + import flash.events.FocusEvent; + import flash.events.MouseEvent; + import flash.events.KeyboardEvent; + import fl.controls.Button; + import fl.controls.TextInput; + import fl.core.UIComponent; + import flash.system.Capabilities; + import flash.utils.*; + /** * The FocusManager class manages focus for a set of components that are navigated by mouse * or keyboard as a tab loop. * *

    A tab loop is typically navigated by using the Tab key; focus moves between the components * in the tab loop in a circular pattern from the first component that has focus, to the last, * and then back again to the first. A tab loop includes all the components and tab-enabled * components in a container. An application can contain numerous tab loops.

    * *

    A FocusManager instance is responsible for a single tab loop; an application uses * a different FocusManager instance to manage each tab loop that it contains, although * a main application is always associated with at least one FocusManager instance. An * application may require additional FocusManager instances if it includes a popup window, * for example, that separately contains one or more tab loops of components.

    * *

    All components that can be managed by a FocusManager instance must implement the * fl.managers.IFocusManagerComponent interface. Objects for which Flash Player * manages focus are not required to implement the IFocusManagerComponent interface.

    * *

    The FocusManager class also manages how the default button is implemented. A default button * dispatches a click event when the Enter key is pressed on a form, * depending on where focus is at the time. The default button does not dispatch the * click event if a text area has focus or if a value is being edited in * a component, for example, in a ComboBox or NumericStepper component.

    * * @see IFocusManager * @see IFocusManagerComponent * * @includeExample examples/FocusManagerExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class FocusManager implements IFocusManager - { + public class FocusManager implements IFocusManager + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _form : DisplayObjectContainer; + private var _form : DisplayObjectContainer; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var focusableObjects : Dictionary; + private var focusableObjects : Dictionary; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var focusableCandidates : Array; + private var focusableCandidates : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var activated : Boolean; + private var activated : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var calculateCandidates : Boolean; + private var calculateCandidates : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var lastFocus : InteractiveObject; + private var lastFocus : InteractiveObject; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _showFocusIndicator : Boolean; + private var _showFocusIndicator : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var lastAction : String; + private var lastAction : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var defButton : Button; + private var defButton : Button; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _defaultButton : Button; + private var _defaultButton : Button; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var _defaultButtonEnabled : Boolean; - + private var _defaultButtonEnabled : Boolean; + /** * Gets or sets the current default button. * *

    The default button is the button on a form that dispatches a * click event when the Enter key is pressed, * depending on where focus is at the time.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get defaultButton () : Button; + public function get defaultButton () : Button; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set defaultButton (value:Button) : void; + public function set defaultButton (value:Button) : void; /** * @copy fl.managers.IFocusManager#defaultButtonEnabled * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get defaultButtonEnabled () : Boolean; + public function get defaultButtonEnabled () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set defaultButtonEnabled (value:Boolean) : void; + public function set defaultButtonEnabled (value:Boolean) : void; /** * Gets the next unique tab index to use in this tab loop. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get nextTabIndex () : int; + public function get nextTabIndex () : int; /** * Gets or sets a value that indicates whether a component that has focus should be marked with a visual indicator of focus. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get showFocusIndicator () : Boolean; + public function get showFocusIndicator () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set showFocusIndicator (value:Boolean) : void; + public function set showFocusIndicator (value:Boolean) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get form () : DisplayObjectContainer; + public function get form () : DisplayObjectContainer; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set form (value:DisplayObjectContainer) : void; - + public function set form (value:DisplayObjectContainer) : void; + /** * Creates a new FocusManager instance. * *

    A focus manager manages focus within the children of a * DisplayObjectContainer object.

    * * @param container A DisplayObjectContainer that hosts the focus manager, * or stage. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function FocusManager (container:DisplayObjectContainer); + public function FocusManager (container:DisplayObjectContainer); /** * @private * Listen for children being added and see if they are focus candidates. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function addedHandler (event:Event) : void; + private function addedHandler (event:Event) : void; /** * @private * Listen for children being removed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function removedHandler (event:Event) : void; + private function removedHandler (event:Event) : void; /** * @private * Do a tree walk and add all children you can find. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function addFocusables (o:DisplayObject, skipTopLevel:Boolean = false) : void; + private function addFocusables (o:DisplayObject, skipTopLevel:Boolean = false) : void; /** * @private * Removes the DisplayObject and all its children. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function removeFocusables (o:DisplayObject) : void; + private function removeFocusables (o:DisplayObject) : void; /** * @private * Checks if the DisplayObject is visible for the tab loop. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function isTabVisible (o:DisplayObject) : Boolean; + private function isTabVisible (o:DisplayObject) : Boolean; /** * @private * Checks if the DisplayObject is a valid candidate for the tab loop. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function isValidFocusCandidate (o:DisplayObject, groupName:String) : Boolean; + private function isValidFocusCandidate (o:DisplayObject, groupName:String) : Boolean; /** * @private * Checks if the DisplayObject is enabled and visible, or * a selectable or input TextField * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function isEnabledAndVisible (o:DisplayObject) : Boolean; + private function isEnabledAndVisible (o:DisplayObject) : Boolean; /** * @private * Add or remove object if tabbing properties change. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function tabEnabledChangeHandler (event:Event) : void; + private function tabEnabledChangeHandler (event:Event) : void; /** * @private * Called when a focusable object's tabIndex property changes. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function tabIndexChangeHandler (event:Event) : void; + private function tabIndexChangeHandler (event:Event) : void; /** * @private * Add or remove object if tabbing properties change. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function tabChildrenChangeHandler (event:Event) : void; + private function tabChildrenChangeHandler (event:Event) : void; /** * Activates the FocusManager instance. * *

    The FocusManager instance adds event handlers that allow it to monitor * focus-related keyboard and mouse activity.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function activate () : void; + public function activate () : void; /** * Deactivates the FocusManager. * *

    The FocusManager removes the event handlers that allow it to monitor * focus-related keyboard and mouse activity.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function deactivate () : void; + public function deactivate () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function focusInHandler (event:FocusEvent) : void; + private function focusInHandler (event:FocusEvent) : void; /** * @private * Useful for debugging. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function focusOutHandler (event:FocusEvent) : void; + private function focusOutHandler (event:FocusEvent) : void; /** * @private * Restore focus to the element that had it last. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function activateHandler (event:Event) : void; + private function activateHandler (event:Event) : void; /** * @private * Useful for debugging. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function deactivateHandler (event:Event) : void; + private function deactivateHandler (event:Event) : void; /** * @private * This gets called when mouse clicks on a focusable object. * We block Flash Player behavior. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function mouseFocusChangeHandler (event:FocusEvent) : void; + private function mouseFocusChangeHandler (event:FocusEvent) : void; /** * @private * This function is called when the tab key is hit. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function keyFocusChangeHandler (event:FocusEvent) : void; + private function keyFocusChangeHandler (event:FocusEvent) : void; /** * @private * Watch for the Enter key. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function keyDownHandler (event:KeyboardEvent) : void; + private function keyDownHandler (event:KeyboardEvent) : void; /** * @private * This gets called when the focus changes due to a mouse click. * *

    Note: If focus is moving to a TextField, it is not * necessary to call setFocus() on it because the player handles it; * calling setFocus() on a TextField that has scrollable text * causes the text to auto-scroll to the end, making the * mouse click set the insertion point in the wrong place.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function mouseDownHandler (event:MouseEvent) : void; + private function mouseDownHandler (event:MouseEvent) : void; /** * @private * Call this method to make the system * think the Enter key was pressed and the default button was clicked. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function sendDefaultButtonEvent () : void; + public function sendDefaultButtonEvent () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function setFocusToNextObject (event:FocusEvent) : void; + private function setFocusToNextObject (event:FocusEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function hasFocusableObjects () : Boolean; + private function hasFocusableObjects () : Boolean; /** * Retrieves the interactive object that would receive focus * if the user pressed the Tab key to navigate to the next object. * This method retrieves the object that currently has focus * if there are no other valid objects in the application. * * @param backward If this parameter is set to true, * focus moves in a backward direction, causing this method to retrieve * the object that would receive focus next if the Shift+Tab key combination * were pressed. * * @return The next component to receive focus. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getNextFocusManagerComponent (backward:Boolean = false) : InteractiveObject; + public function getNextFocusManagerComponent (backward:Boolean = false) : InteractiveObject; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function getIndexOfFocusedObject (o:DisplayObject) : int; + private function getIndexOfFocusedObject (o:DisplayObject) : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function getIndexOfNextObject (i:int, shiftKey:Boolean, bSearchAll:Boolean, groupName:String) : int; + private function getIndexOfNextObject (i:int, shiftKey:Boolean, bSearchAll:Boolean, groupName:String) : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function sortFocusableObjects () : void; + private function sortFocusableObjects () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function sortFocusableObjectsTabIndex () : void; + private function sortFocusableObjectsTabIndex () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function sortByDepth (aa:InteractiveObject, bb:InteractiveObject) : Number; + private function sortByDepth (aa:InteractiveObject, bb:InteractiveObject) : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function getChildIndex (parent:DisplayObjectContainer, child:DisplayObject) : int; + private function getChildIndex (parent:DisplayObjectContainer, child:DisplayObject) : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function sortByTabIndex (a:InteractiveObject, b:InteractiveObject) : int; + private function sortByTabIndex (a:InteractiveObject, b:InteractiveObject) : int; /** * Gets the interactive object that currently has focus. * Adobe recommends calling this method instead of using the Stage object * because this method indicates which component has focus. * The Stage might return a subcomponent in that component. * * @return The interactive object that currently has focus. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getFocus () : InteractiveObject; + public function getFocus () : InteractiveObject; /** * Sets focus on an IFocusManagerComponent component. This method does * not check for component visibility, enabled state, or other conditions. * * @param component An object that can receive focus. * * @internal Do you guys have a code snippet/test case/sample you could give us for this? (rberry(at)adobe.com) * Adobe: [LM] {StyleManager.setFocus(myBtn);} * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setFocus (component:InteractiveObject) : void; + public function setFocus (component:InteractiveObject) : void; /** * Sets the showFocusIndicator value to true * and draws the visual focus indicator on the object with focus, if any. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function showFocus () : void; + public function showFocus () : void; /** * Sets the showFocusIndicator value to false * and removes the visual focus indicator from the object that has focus, if any. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function hideFocus () : void; + public function hideFocus () : void; /** * Retrieves the interactive object that contains the given object, if any. * The player can set focus to a subcomponent of a Flash component; * this method determines which interactive object has focus from * the component perspective. * * @param component An object that can have player-level focus. * * @return The object containing the component or, if one is * not found, the component itself. * * @internal Description needs explanation of relationship between interactive object (param and return type) and * FocusManagerComponent, which the function claims to be finding. Do you guys have a code snippet/test * case/sample you could give us for this? (rberry(at)adobe.com) * Metaliq: Anybody? * Adobe: [LM] Changed description to InteractiveObject. This was changed to InteractiveObject because the FocusManager supports native flash objects too. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function findFocusManagerComponent (component:InteractiveObject) : InteractiveObject; + public function findFocusManagerComponent (component:InteractiveObject) : InteractiveObject; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function getTopLevelFocusTarget (o:InteractiveObject) : InteractiveObject; - } -} + private function getTopLevelFocusTarget (o:InteractiveObject) : InteractiveObject; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManager.as index 9c2a05054e..99a2aa4d99 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManager.as @@ -1,74 +1,74 @@ -package fl.managers -{ - import flash.display.InteractiveObject; - import flash.display.Sprite; - import fl.controls.Button; - +package fl.managers +{ + import flash.display.InteractiveObject; + import flash.display.Sprite; + import fl.controls.Button; + /** * Implement the IFocusManager interface to create a custom focus manager. * A focus manager enables an application to transfer focus among components * when the user moves the mouse or presses the Tab key. * * @see FocusManager * @see IFocusManagerComponent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public interface IFocusManager - { + public interface IFocusManager + { /** * Gets or sets a reference to the default button. * The default button serves as a proxy button for * any component that has focus when the Enter key is pressed. * The pressing of the Enter key triggers a click * event to be dispatched on the default button * on behalf of the component that has focus. Button components do * not require default buttons. When focus moves to a Button * component it cannot trigger the default button; if * focus moves from a Button component to a component that is not * a button, the default button may be triggered again. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get defaultButton () : Button; + public function get defaultButton () : Button; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set defaultButton (value:Button) : void; + public function set defaultButton (value:Button) : void; /** * Gets or sets a value that indicates whether the default button * is enabled. If this value is set to true, the focus manager * monitors the Enter key and dispatches a click event on the * default button if the Enter key is pressed when a component that is not a * Button component has focus. If this value is set to false, the focus manager * does not monitor the Enter key. Components that use the Enter key set * this property to false to prevent a click event * from being dispatched on the default button, if one exists, when a user * presses the Enter key. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get defaultButtonEnabled () : Boolean; + public function get defaultButtonEnabled () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set defaultButtonEnabled (value:Boolean) : void; + public function set defaultButtonEnabled (value:Boolean) : void; /** * Gets the next unique tab index to use in the current tab loop. A tab loop * includes one or more components that are managed by a focus manager. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get nextTabIndex () : int; + public function get nextTabIndex () : int; /** * Gets or sets a value that determines whether the user interface * changes to indicate that a specific component has focus. * *

    If this property is set to true, a component * that has focus is marked with a visual indicator. If it is set * to false, a visual indicator of focus is not used.

    * *

    By default, this property is set to false until the user * presses the Tab key; then it is set to true.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get showFocusIndicator () : Boolean; + public function get showFocusIndicator () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set showFocusIndicator (value:Boolean) : void; - + public function set showFocusIndicator (value:Boolean) : void; + /** * Retrieves the IFocusManagerComponent component that currently has focus. * Use this method to determine which component has focus. * Using the Stage object to find out which component has focus may result * in the return of the subcomponent of the component that has focus. * * @return IFocusManagerComponent object that has focus. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getFocus () : InteractiveObject; + public function getFocus () : InteractiveObject; /** * Sets focus to an IFocusManagerComponent component. This method does not * check for component visibility, enabled state, or any other conditions. * * @param o The component that is to receive focus. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setFocus (o:InteractiveObject) : void; + public function setFocus (o:InteractiveObject) : void; /** * Sets the showFocusIndicator property to true. * If a component has focus, this method draws the visual focus indicator * on that component. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function showFocus () : void; + public function showFocus () : void; /** * Sets the showFocusIndicator property to false. * If a component that has focus is marked with a visual indicator * of focus, this method removes that indicator. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function hideFocus () : void; + public function hideFocus () : void; /** * Activates a focus manager. * *

    When multiple DisplayObjectContainer objects are displayed on the screen * at the same time, the system manager activates and deactivates their * FocusManager objects as focus moves from one container to the next. * When focus moves to a component in an DisplayObjectContainer object whose * focus manager is deactivated, the system manager activates that focus manager * by making a call to the activate() method. Only one focus manager * is active at a time; before activating a focus manager the system manager * uses the deactivate() method to deactivate an active * focus manager whose components have lost focus.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function activate () : void; + public function activate () : void; /** * Deactivates a focus manager. * *

    When multiple DisplayObjectContainer objects are displayed on the screen * at the same time, the system manager activates and deactivates their * FocusManager objects as focus moves from one container to the next. * When focus moves to a component in an DisplayObjectContainer object whose * focus manager is deactivated, the system manager activates that focus manager * by making a call to the activate() method. Only one focus manager * is active at a time; before activating a focus manager the system manager * uses the deactivate() method to deactivate an active * focus manager whose components have lost focus.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function deactivate () : void; + public function deactivate () : void; /** * Retrieves the IFocusManagerComponent object that contains the specified * object, if there is one. * *

    Flash Player can set focus on subcomponents as well as on components * themselves. This method is used to find the component that either has focus * or contains the subcomponent that has focus.

    * * @param component An object that can have Flash Player-level focus. * * @return The IFocusManagerComponent that contains the specified object; * otherwise, this method returns null. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function findFocusManagerComponent (component:InteractiveObject) : InteractiveObject; + public function findFocusManagerComponent (component:InteractiveObject) : InteractiveObject; /** * Retrieves the component that receives focus next if the user * causes focus to move by using the Tab key. * *

    This method can be used to detect the next component to * receive focus in the tab loop if focus moves by one element in either * a forward or backward direction. If the application does not contain * other valid components, this method retrieves the current component * that has focus.

    * * @param backward Indicates whether focus moves in a backward * direction through the tab loop. If this value is true, this method * returns the component that would have focus if focus were moved in a backward * direction by the user pressing the Shift+Tab key combination. * * @return The component that is next to receive focus. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getNextFocusManagerComponent (backward:Boolean = false) : InteractiveObject; - } -} + public function getNextFocusManagerComponent (backward:Boolean = false) : InteractiveObject; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManagerComponent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManagerComponent.as index 62b7b7d290..ba8d40ce92 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManagerComponent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManagerComponent.as @@ -1,38 +1,38 @@ -package fl.managers -{ +package fl.managers +{ /** * The IFocusManagerComponent interface provides methods and properties * that give components the capability to receive focus. Components * must implement this interface to receive focus from the FocusManager. * *

    The UIComponent class provides a base implementation of this interface * but does not fully implement it because not all UIComponent objects * receive focus. Components that are derived from the UIComponent * class must implement this interface to be capable of receiving focus. * To enable focus, add the statement implements IFocusManagerComponent * to the class definition of a component that is derived from the UIComponent * class.

    * * @see FocusManager * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public interface IFocusManagerComponent - { + public interface IFocusManagerComponent + { /** * Gets or sets a Boolean value that indicates whether a selected component can receive * focus from the focus manager. * *

    To make a component capable of receiving focus from the focus manager, * set this property to true. To make the component incapable of receiving * focus, set this property to false. When focusEnabled * is set to false, the focus manager ignores the component over the * component's lifetime and does not monitor it for changes in the following * properties: tabEnabled, tabChildren, and * mouseFocusEnabled.

    * *

    You can use the focusEnabled property to prevent the child component of * a component that implements the IFocusManagerComponent interface * from receiving focus from the focus manager. To do so, set this property to false * before using the addChild() method to add the child component * to the display list. Note that if you set this property to false * before adding the component to the display list, the focus manager will continue to * ignore the component even if you set this property to true * later on.

    * *

    Note: Even if you set this property to false, * you can still set focus programmatically by using the setFocus() * method.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get focusEnabled () : Boolean; + public function get focusEnabled () : Boolean; /** * @private */ - public function set focusEnabled (value:Boolean) : void; + public function set focusEnabled (value:Boolean) : void; /** * Gets a Boolean value that indicates whether a component that is * selected by using a mouse device can receive focus. * *

    Set this property to true to give focus * to components that are selected by using a mouse device. * Set this property to false to prevent focus * from being given to components that are selected by using * a mouse device. If this property is set to false * when a component is selected by using a mouse device, focus * is transferred to the first parent component for which * this property is set to true.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get mouseFocusEnabled () : Boolean; + public function get mouseFocusEnabled () : Boolean; /** * Gets a Boolean value that indicates whether pressing the Tab key can * move focus to this component. A value of true indicates * that pressing the Tab key can cause focus to be moved to this component; * a value of false indicates that the Tab key cannot be * used to give this component focus. * *

    Even if this value is set to false, the component can still * receive focus when it is selected by a mouse device or through a call to the * setFocus() method.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get tabEnabled () : Boolean; + public function get tabEnabled () : Boolean; /** * Gets the order in which the component receives focus, if tabEnabledis set * to true. The tabIndex property is -1 by default, meaning * that no tab index is set for the object and that the object receives focus based on z-order. * *

    The tabIndex property can also be a non-negative integer. In this * case, the objects are ordered according to their tabIndex properties, * in ascending order. An object with a tabIndex value of 1 precedes an * object with a tabIndex value of 2. If two objects have the same * tabIndex value, the one that comes first in the default tab ordering * precedes the other.

    * * @default -1 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get tabIndex () : int; - + public function get tabIndex () : int; + /** * Sets focus for a component. * *

    This method is called by the focus manager when the component receives focus. * The component may in turn set focus to an internal component.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setFocus () : void; + public function setFocus () : void; /** * Draws a visual focus indicator. * *

    This method is called by the focus manager when the component receives focus. * The component should draw or hide a graphic that indicates that the component has focus.

    * * @param draw If true, draw the focus indicator, * otherwise hide it. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function drawFocus (draw:Boolean) : void; - } -} + public function drawFocus (draw:Boolean) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManagerGroup.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManagerGroup.as index a273e4d958..aab7cbc7cc 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManagerGroup.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/IFocusManagerGroup.as @@ -1,26 +1,26 @@ -package fl.managers -{ +package fl.managers +{ /** * The IFocusManagerGroup interface provides properties that are used * to manage a set of components of which only one can be selected * at a time. Components that are part of such a component set * must implement this interface. * *

    A radio button, for example, must implement the IFocusManagerGroup interface * because only one radio button can be selected from a group of radio button * components at a time. The focus manager ensures that focus is not given to a * radio button that is not selected when focus moves in response to the Tab key.

    * * @see FocusManager * @see IFocusManagerComponent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public interface IFocusManagerGroup - { + public interface IFocusManagerGroup + { /** * Gets or sets the name of the group of components to which this component belongs. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get groupName () : String; + public function get groupName () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set groupName (value:String) : void; + public function set groupName (value:String) : void; /** * Gets or sets a Boolean value that indicates whether this component is selected. * A value of true indicates that the component is selected; * a value of false indicates that it is not selected. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get selected () : Boolean; + public function get selected () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set selected (value:Boolean) : void; - - } -} + public function set selected (value:Boolean) : void; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/StyleManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/StyleManager.as index 241812d3ac..243bd00bf5 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/StyleManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/managers/StyleManager.as @@ -1,98 +1,98 @@ -package fl.managers -{ - import fl.core.UIComponent; - import flash.display.Sprite; - import flash.text.TextFormat; - import flash.utils.Dictionary; - import flash.utils.getDefinitionByName; - import flash.utils.getQualifiedClassName; - import flash.utils.getQualifiedSuperclassName; - +package fl.managers +{ + import fl.core.UIComponent; + import flash.display.Sprite; + import flash.text.TextFormat; + import flash.utils.Dictionary; + import flash.utils.getDefinitionByName; + import flash.utils.getQualifiedClassName; + import flash.utils.getQualifiedSuperclassName; + /** * The StyleManager class provides static methods that can be used to get and * set styles for a component instance, an entire component type, or all user * interface components in a Flash document. Styles are defined as values that * affect the display of a component, including padding, text formats, and skins. * * @includeExample examples/StyleManagerExample.as * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class StyleManager - { + public class StyleManager + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static var _instance : StyleManager; + private static var _instance : StyleManager; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var styleToClassesHash : Object; + private var styleToClassesHash : Object; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var classToInstancesDict : Dictionary; + private var classToInstancesDict : Dictionary; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var classToStylesDict : Dictionary; + private var classToStylesDict : Dictionary; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var classToDefaultStylesDict : Dictionary; + private var classToDefaultStylesDict : Dictionary; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private var globalStyles : Object; - + private var globalStyles : Object; + /** * Creates a new StyleManager object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function StyleManager (); + public function StyleManager (); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function getInstance (); + private static function getInstance (); /** * Registers a component instance with the style manager. After a component instance is * instantiated, it can register with the style manager to be notified of changes * in style. Component instances can register to receive notice of style changes that are * component-based or global in nature. * * @param instance The component instance to be registered for style * management. * * @internal Do you guys have a code snippet/test case/sample you could give us for this? (pdehaan(at)adobe.com) * Adobe: [LM] Although this method is public, it is all handled internally by UIComponent. Each component registers itself when it instantiates. * @internal Should this then be (at)private in the docs? * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function registerInstance (instance:UIComponent) : void; + public static function registerInstance (instance:UIComponent) : void; /** * @private * * Sets an inherited style on a component. * * @param instance The component object on which to set the inherited style. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function setSharedStyles (instance:UIComponent) : void; + private static function setSharedStyles (instance:UIComponent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function getSharedStyle (instance:UIComponent, name:String) : Object; + private static function getSharedStyle (instance:UIComponent, name:String) : Object; /** * Gets a style that exists on a specific component. * * @param component The name of the component instance on which to find the * requested style. * * @param name The name of the style to be retrieved. * * @return The requested style from the specified component. This function returns null * if the specified style is not found. * * @see #clearComponentStyle() * @see #getStyle() * @see #setComponentStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getComponentStyle (component:Object, name:String) : Object; + public static function getComponentStyle (component:Object, name:String) : Object; /** * Removes a style from the specified component. * * @param component The name of the component from which the style is to be removed. * * @param name The name of the style to be removed. * * @see #clearStyle() * @see #getComponentStyle() * @see #setComponentStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function clearComponentStyle (component:Object, name:String) : void; + public static function clearComponentStyle (component:Object, name:String) : void; /** * Sets a style on all instances of a component type, for example, on all instances of a * Button component, or on all instances of a ComboBox component. * * @param component The type of component, for example, Button or ComboBox. This parameter also accepts * a component instance or class that can be used to identify all instances of a component type. * * @param name The name of the style to be set. * * @param style The style object that describes the style that is to be set. * * @see #clearComponentStyle() * @see #getComponentStyle() * @see #setStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function setComponentStyle (component:Object, name:String, style:Object) : void; + public static function setComponentStyle (component:Object, name:String, style:Object) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function getClassDef (component:Object) : Class; + private static function getClassDef (component:Object) : Class; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function invalidateStyle (name:String) : void; + private static function invalidateStyle (name:String) : void; /** * @private (protected) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private static function invalidateComponentStyle (componentClass:Class, name:String) : void; + private static function invalidateComponentStyle (componentClass:Class, name:String) : void; /** * Sets a global style for all user interface components in a document. * * @param name A String value that names the style to be set. * * @param style The style object to be set. The value of this property depends on the * style that the user sets. For example, if the style is set to "textFormat", the style * property should be set to a TextFormat object. A mismatch between the style name and * the value of the style property may cause the component to behave incorrectly. * * @see #clearStyle() * @see #getStyle() * @see #setComponentStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function setStyle (name:String, style:Object) : void; + public static function setStyle (name:String, style:Object) : void; /** * Removes a global style from all user interface components in a document. * * @param name The name of the global style to be removed. * * @see #clearComponentStyle() * @see #getStyle() * @see #setStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function clearStyle (name:String) : void; + public static function clearStyle (name:String) : void; /** * Gets a global style by name. * * @param name The name of the style to be retrieved. * * @return The value of the global style that was retrieved. * * @internal "that was removed" - doesn't sound right. Do you guys have a code snippet/test * case/sample you could give us for this? (rberry(at)adobe.com) * Adobe: [LM] Correct - description was wrong. Code sample would be simple: {var textFormat:TextFormat = StyleManager.getStyle("textFormat") as TextFormat;} * * @see #clearStyle() * @see #getComponentStyle() * @see #setStyle() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static function getStyle (name:String) : Object; - } -} + public static function getStyle (name:String) : Object; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AdjustColor.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AdjustColor.as index 9432584b7a..8b0e847e4c 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AdjustColor.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AdjustColor.as @@ -1,46 +1,46 @@ -package fl.motion -{ +package fl.motion +{ /** * The AdjustColor class defines various color properties, such as brightness, contrast, hue, and saturation, to support the ColorMatrixFilter class. * You can apply the AdjustColor filter to any display object, * and also generate a flat array representing all four color properties to use with the ColorMatrixFilter class. * @playerversion Flash 9 * @langversion 3.0 * @keyword AdjustColor * @see flash.filters.ColorMatrixFilter */ - public class AdjustColor - { - private static var s_arrayOfDeltaIndex : Array; - private var m_brightnessMatrix : ColorMatrix; - private var m_contrastMatrix : ColorMatrix; - private var m_saturationMatrix : ColorMatrix; - private var m_hueMatrix : ColorMatrix; - private var m_finalMatrix : ColorMatrix; - + public class AdjustColor + { + private static var s_arrayOfDeltaIndex : Array; + private var m_brightnessMatrix : ColorMatrix; + private var m_contrastMatrix : ColorMatrix; + private var m_saturationMatrix : ColorMatrix; + private var m_hueMatrix : ColorMatrix; + private var m_finalMatrix : ColorMatrix; + /** * Sets the brightness of the AdjustColor filter. The range of valid values is -100 to 100. * @playerversion Flash 9 * @langversion 3.0 */ - public function set brightness (value:Number) : void; + public function set brightness (value:Number) : void; /** * Sets the contrast of the AdjustColor filter. The range of valid values is -100 to 100. * @playerversion Flash 9 * @langversion 3.0 */ - public function set contrast (value:Number) : void; + public function set contrast (value:Number) : void; /** * Sets the saturation of the AdjustColor filter. The range of valid values is -100 to 100. * @playerversion Flash 9 * @langversion 3.0 */ - public function set saturation (value:Number) : void; + public function set saturation (value:Number) : void; /** * Sets the hue of the AdjustColor filter. The range of valid values is -180 to 180. * @playerversion Flash 9 * @langversion 3.0 */ - public function set hue (value:Number) : void; - + public function set hue (value:Number) : void; + /** * The AdjustColor class defines various color properties to support the ColorMatrixFilter. * @playerversion Flash 9 * @langversion 3.0 * @see flash.filters.ColorMatrixFilter */ - public function AdjustColor (); + public function AdjustColor (); /** * Verifies if all four AdjustColor properties are set. * @return A Boolean value that is true if all four AdjustColor properties have been set, false otherwise. * @playerversion Flash 9 * @langversion 3.0 */ - public function AllValuesAreSet () : Boolean; + public function AllValuesAreSet () : Boolean; /** * Returns the flat array of values for all four properties. * @return An array of 20 numerical values representing all four AdjustColor properties * to use with the flash.filters.ColorMatrixFilter class. * @playerversion Flash 9 * @langversion 3.0 * @see flash.filters.ColorMatrixFilter */ - public function CalculateFinalFlatArray () : Array; - private function CalculateFinalMatrix () : Boolean; - } -} + public function CalculateFinalFlatArray () : Array; + private function CalculateFinalMatrix () : Boolean; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Animator.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Animator.as index f4805bdc9c..a80cbd8dde 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Animator.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Animator.as @@ -1,34 +1,34 @@ -package fl.motion -{ - import flash.display.DisplayObject; - import flash.geom.Matrix; - import flash.geom.Point; - +package fl.motion +{ + import flash.display.DisplayObject; + import flash.geom.Matrix; + import flash.geom.Point; + /** * The Animator class applies an XML description of a motion tween to a display object. * The properties and methods of the Animator class control the playback of the motion, * and Flash Player broadcasts events in response to changes in the motion's status. * If there isn't any three-dimensional content, the Copy Motion as ActionScript command in * Flash CS4 uses the Animator class. For three-dimensional content, the Animator3D class is used, instead, which shares the * same base class as the Animator class but is specifically for three-dimensional content. * You can then edit the ActionScript using the application programming interface * (API) or construct your own custom animation. *

    If you plan to call methods of the Animator class within a function, declare the Animator * instance outside of the function so the scope of the object is not restricted to the * function itself. If you declare the instance within a function, Flash Player deletes the * Animator instance at the end of the function as part of Flash Player's routine "garbage collection" * and the target object will not animate.

    * * @internal

    Note: If you're not using Flash CS4 to compile your SWF file, you need the * fl.motion classes in your classpath at compile time to apply the motion to the display object.

    * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Animator, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class Animator extends AnimatorBase - { + public class Animator extends AnimatorBase + { /** * @private (setter) */ - public function set motion (value:MotionBase) : void; - + public function set motion (value:MotionBase) : void; + /** * @private */ - protected function setTargetState () : void; + protected function setTargetState () : void; /** * @private */ - protected function setTimeClassic (newTime:int, thisMotion:MotionBase, curKeyframe:KeyframeBase) : Boolean; + protected function setTimeClassic (newTime:int, thisMotion:MotionBase, curKeyframe:KeyframeBase) : Boolean; /** * Creates an Animator object to apply the XML-based motion tween description to a display object. * * @param xml An E4X object containing an XML-based motion tween description. * * @param target The display object using the motion tween. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword AnimatorBase * @see ../../motionXSD.html Motion XML Elements */ - function Animator (xml:XML = null, target:DisplayObject = null); + function Animator (xml:XML = null, target:DisplayObject = null); /** * Creates an Animator object from a string of XML. * This method is an alternative to using the Animator constructor, which accepts an E4X object instead. * * @param xmlString A string of XML describing the motion tween. * * @param target The display object using the motion tween. * * @return An Animator instance that applies the specified xmlString to the specified target. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword createFromXMLString, Animator * @see ../../motionXSD.html Motion XML Elements */ - public static function fromXMLString (xmlString:String, target:DisplayObject = null) : Animator; - } -} + public static function fromXMLString (xmlString:String, target:DisplayObject = null) : Animator; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Animator3D.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Animator3D.as index 8b7ff8a1df..20224392bf 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Animator3D.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Animator3D.as @@ -1,49 +1,49 @@ -package fl.motion -{ - import flash.display.DisplayObject; - import flash.geom.Matrix; - import flash.geom.Matrix3D; - import flash.geom.Vector3D; - import __AS3__.vec.Vector; - import flash.geom.Point; - +package fl.motion +{ + import flash.display.DisplayObject; + import flash.geom.Matrix; + import flash.geom.Matrix3D; + import flash.geom.Vector3D; + import __AS3__.vec.Vector; + import flash.geom.Point; + /** * The Animator3D class applies an XML description of a three-dimensional motion tween to a display object. * The properties and methods of the Animator3D class control the playback of the motion, * and Flash Player broadcasts events in response to changes in the motion's status. * If there isn't any three-dimensional content in the motion tween, the Copy Motion as ActionScript command in * Flash CS4 uses the Animator class. For three-dimensional content, the Animator3D class is used, instead, which shares the * same base class as the Animator class but is specifically for three-dimensional content. * You can then edit the ActionScript using the application programming interface * (API) or construct your own custom animation. *

    If you plan to call methods of the Animator3D class within a function, declare the Animator3D * instance outside of the function so the scope of the object is not restricted to the * function itself. If you declare the instance within a function, Flash Player deletes the * Animator instance at the end of the function as part of Flash Player's routine "garbage collection" * and the target object will not animate.

    * * @internal

    Note: If you're not using Flash CS4 to compile your SWF file, you need the * fl.motion classes in your classpath at compile time to apply the motion to the display object.

    * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @keyword Animator, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class Animator3D extends AnimatorBase - { - private var _initialPosition : Vector3D; - private var _initialMatrixOfTarget : Matrix3D; + public class Animator3D extends AnimatorBase + { + private var _initialPosition : Vector3D; + private var _initialMatrixOfTarget : Matrix3D; /** * @private */ - protected static const EPSILON : Number = 0.00000001; - + protected static const EPSILON : Number = 0.00000001; + /** * Establishes, the x-, y-, and z- coordinates of the display object. * * @param xml An array containing the x, y, and z coordinates of the object, in order, of the display * object at the start of the motion. * * @param target The display object using the motion tween. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @keyword AnimatorBase * @see ../../motionXSD.html Motion XML Elements */ - public function set initialPosition (initPos:Array) : void; - + public function set initialPosition (initPos:Array) : void; + /** * Creates an Animator3D object to apply the XML-based motion tween description in three dimensions to a display object. * * @param xml An E4X object containing an XML-based motion tween description. * * @param target The display object using the motion tween. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @keyword AnimatorBase * @see ../../motionXSD.html Motion XML Elements */ - public function Animator3D (xml:XML = null, target:DisplayObject = null); + public function Animator3D (xml:XML = null, target:DisplayObject = null); /** * @private */ - protected function setTargetState () : void; + protected function setTargetState () : void; /** * @private */ - protected function setTime3D (newTime:int, thisMotion:MotionBase) : Boolean; + protected function setTime3D (newTime:int, thisMotion:MotionBase) : Boolean; /** * @private */ - private function getScaleSkewMatrix (thisMotion:MotionBase, newTime:int, positionX:Number, positionY:Number) : Matrix; + private function getScaleSkewMatrix (thisMotion:MotionBase, newTime:int, positionX:Number, positionY:Number) : Matrix; /** * @private */ - protected static function getSign (n:Number) : int; - protected static function convertMatrixToMatrix3D (mat2D:Matrix) : Matrix3D; - } -} + protected static function getSign (n:Number) : int; + protected static function convertMatrixToMatrix3D (mat2D:Matrix) : Matrix3D; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorBase.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorBase.as index 47e6b727a4..fcd1460602 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorBase.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorBase.as @@ -1,239 +1,239 @@ -package fl.motion -{ - import flash.display.DisplayObject; - import flash.display.DisplayObjectContainer; - import flash.display.MovieClip; - import flash.events.Event; - import flash.events.EventDispatcher; - import flash.geom.ColorTransform; - import flash.geom.Matrix; - import flash.geom.Point; - import flash.display.SimpleButton; - import flash.utils.Dictionary; - import flash.display.MovieClip; - +package fl.motion +{ + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + import flash.display.MovieClip; + import flash.events.Event; + import flash.events.EventDispatcher; + import flash.geom.ColorTransform; + import flash.geom.Matrix; + import flash.geom.Point; + import flash.display.SimpleButton; + import flash.utils.Dictionary; + import flash.display.MovieClip; + /** * Dispatched when the motion finishes playing, * either when it reaches the end, or when the motion is * interrupted by a call to the stop() or end() methods. * * @eventType fl.motion.MotionEvent.MOTION_END * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - [Event(name="motionEnd", type="fl.motion.MotionEvent")] + [Event(name="motionEnd", type="fl.motion.MotionEvent")] /** * Dispatched when the motion starts playing. * * @eventType fl.motion.MotionEvent.MOTION_START * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - [Event(name="motionStart", type="fl.motion.MotionEvent")] + [Event(name="motionStart", type="fl.motion.MotionEvent")] /** * Dispatched when the motion has changed and the screen has been updated. * * @eventType fl.motion.MotionEvent.MOTION_UPDATE * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - [Event(name="motionUpdate", type="fl.motion.MotionEvent")] + [Event(name="motionUpdate", type="fl.motion.MotionEvent")] /** * Dispatched when the Animator's time value has changed, * but the screen has not yet been updated (i.e., the motionUpdate event). * * @eventType fl.motion.MotionEvent.TIME_CHANGE * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - [Event(name="timeChange", type="fl.motion.MotionEvent")] - + [Event(name="timeChange", type="fl.motion.MotionEvent")] + /** * The AnimatorBase class applies an XML description of a motion tween to a display object. * The properties and methods of the AnimatorBase class control the playback of the motion, * and Flash Player broadcasts events in response to changes in the motion's status. * The AnimatorBase class is primarily used by the Copy Motion as ActionScript command in Flash CS4. * You can then edit the ActionScript using the application programming interface * (API) or construct your own custom animation. * The AnimatorBase class should not be used on its own. Use its subclasses: Animator or Animator3D, instead. * *

    If you plan to call methods of the AnimatorBase class within a function, declare the AnimatorBase * instance outside of the function so the scope of the object is not restricted to the * function itself. If you declare the instance within a function, Flash Player deletes the * AnimatorBase instance at the end of the function as part of Flash Player's routine "garbage collection" * and the target object will not animate.

    * * @internal

    Note: If you're not using Flash CS4 to compile your SWF file, you need the * fl.motion classes in your classpath at compile time to apply the motion to the display object.

    * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Animator, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class AnimatorBase extends EventDispatcher - { + public class AnimatorBase extends EventDispatcher + { /** * @private */ - private var _motion : MotionBase; + private var _motion : MotionBase; /** * Sets the position of the display object along the motion path. If set to true * the baseline of the display object orients to the motion path; otherwise the registration * point orients to the motion path. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword orientToPath, orientation */ - public var orientToPath : Boolean; + public var orientToPath : Boolean; /** * The point of reference for rotating or scaling a display object. For 2D motion, the transformation point is * relative to the display object's bounding box. The point's coordinates must be scaled to a 1px x 1px box, where (1, 1) is the object's lower-right corner, * and (0, 0) is the object's upper-left corner. For 3Dmotion (when the AnimatorBase instance is an Animator3D), the transformationPoint's x and y plus the transformationPointZ are * absolute values in the target parent's coordinate space. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword transformationPoint */ - public var transformationPoint : Point; - public var transformationPointZ : int; + public var transformationPoint : Point; + public var transformationPointZ : int; /** * Sets the animation to restart after it finishes. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword autoRewind, loop */ - public var autoRewind : Boolean; + public var autoRewind : Boolean; /** * The Matrix object that applies an overall transformation to the motion path. * This matrix allows the path to be shifted, scaled, skewed or rotated, * without changing the appearance of the display object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword positionMatrix */ - public var positionMatrix : Matrix; + public var positionMatrix : Matrix; /** * Number of times to repeat the animation. * Possible values are any integer greater than or equal to 0. * A value of 1 means to play the animation once. * A value of 0 means to play the animation indefinitely * until explicitly stopped (by a call to the end() method, for example). * * @default 1 * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword repeatCount, repetition, loop * @see #end() */ - public var repeatCount : int; + public var repeatCount : int; /** * @private */ - private var _isPlaying : Boolean; + private var _isPlaying : Boolean; /** * @private */ - protected var _target : DisplayObject; + protected var _target : DisplayObject; /** * @private */ - private var _lastRenderedTime : int; + private var _lastRenderedTime : int; /** * @private */ - private var _time : int; - private var _targetParent : DisplayObjectContainer; - private var _targetName : String; - private var targetStateOriginal : Object; - private var _useCurrentFrame : Boolean; - private var _spanStart : int; - private var _sceneName : String; - private static var _registeredParents : Dictionary; - private var _frameEvent : String; - private var _targetState3D : Array; + private var _time : int; + private var _targetParent : DisplayObjectContainer; + private var _targetName : String; + private var targetStateOriginal : Object; + private var _useCurrentFrame : Boolean; + private var _spanStart : int; + private var _sceneName : String; + private static var _registeredParents : Dictionary; + private var _frameEvent : String; + private var _targetState3D : Array; /** * @private */ - protected var _isAnimator3D : Boolean; + protected var _isAnimator3D : Boolean; /** * @private */ - private var playCount : int; + private var playCount : int; /** * @private */ - private static var enterFrameBeacon : MovieClip; + private static var enterFrameBeacon : MovieClip; /** * @private */ - protected var targetState : Object; - + protected var targetState : Object; + /** * The object that contains the motion tween properties for the animation. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword motion */ - public function get motion () : MotionBase; + public function get motion () : MotionBase; /** * @private (setter) */ - public function set motion (value:MotionBase) : void; + public function set motion (value:MotionBase) : void; /** * Indicates whether the animation is currently playing. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword isPlaying */ - public function get isPlaying () : Boolean; + public function get isPlaying () : Boolean; /** * The display object being animated. * Any subclass of flash.display.DisplayObject can be used, such as a MovieClip, Sprite, or Bitmap. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword target * @see flash.display.DisplayObject */ - public function get target () : DisplayObject; + public function get target () : DisplayObject; /** * @private (setter) */ - public function set target (value:DisplayObject) : void; - public function set initialPosition (initPos:Array) : void; + public function set target (value:DisplayObject) : void; + public function set initialPosition (initPos:Array) : void; /** * A zero-based integer that indicates and controls the time in the current animation. * At the animation's first frame the time value is 0. * If the animation has a duration of 10 frames, at the last frame the time value is 9. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword time */ - public function get time () : int; + public function get time () : int; /** * @private (setter) */ - public function set time (newTime:int) : void; + public function set time (newTime:int) : void; /** * The target parent DisplayObjectContainer being animated, which can be used in conjunction with targetName * to retrieve the target object after it is removed and then replaced on the timeline. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public function get targetParent () : DisplayObjectContainer; - public function set targetParent (p:DisplayObjectContainer) : void; + public function get targetParent () : DisplayObjectContainer; + public function set targetParent (p:DisplayObjectContainer) : void; /** * The name of the target object as seen by the parent DisplayObjectContainer. * This can be used in conjunction with targetParent to retrieve the target object after it is removed and then replaced on the timeline. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public function get targetName () : String; - public function set targetName (n:String) : void; + public function get targetName () : String; + public function set targetName (n:String) : void; /** * Indicates whether the currentFrame property is checked whenever a new frame is entered and * whether the target's animation is synchronized to the frames in its parent's timeline, * or always advancing no matter what the parent's current frame is. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public function get usingCurrentFrame () : Boolean; + public function get usingCurrentFrame () : Boolean; /** * Returns the frame of the target's parent on which the animation of the target begins. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public function get spanStart () : int; + public function get spanStart () : int; /** * Returns the frame of the target's parent on which the animation of the target ends. * This value is determined using spanStart and the motion's duration property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public function get spanEnd () : int; - public function set sceneName (name:String) : void; - public function get sceneName () : String; - private static function get hasRegisteredParents () : Boolean; - public function get frameEvent () : String; - public function set frameEvent (evt:String) : void; + public function get spanEnd () : int; + public function set sceneName (name:String) : void; + public function get sceneName () : String; + private static function get hasRegisteredParents () : Boolean; + public function get frameEvent () : String; + public function set frameEvent (evt:String) : void; /** * The initial orientation for the target object. All 3D rotation is absolute to the motion data. * If you target another object that has a different starting 3D orientation, it is reset to this target state first. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ - public function get targetState3D () : Array; - public function set targetState3D (state:Array) : void; - private function get enterFrameHandler () : Function; - + public function get targetState3D () : Array; + public function set targetState3D (state:Array) : void; + private function get enterFrameHandler () : Function; + /** * @private */ - protected function setTargetState () : void; + protected function setTargetState () : void; /** * @private */ - protected function setTime3D (newTime:int, thisMotion:MotionBase) : Boolean; + protected function setTime3D (newTime:int, thisMotion:MotionBase) : Boolean; /** * @private */ - protected function setTimeClassic (newTime:int, thisMotion:MotionBase, curKeyframe:KeyframeBase) : Boolean; + protected function setTimeClassic (newTime:int, thisMotion:MotionBase, curKeyframe:KeyframeBase) : Boolean; /** * Sets the currentFrame property whenever a new frame is entered, and * sets whether the target's animation is synchronized to the frames in its parent MovieClips's timeline. * spanStart is the start frame of the animation in terms of the parent's timeline. * If enable is true, then in any given enter frame event within the span of the animation, * the time property is set to a frame number relative to the spanStart frame. * *

    For example, if a 4-frame animation starts on frame 5 (spanStart=5), * and you have a script on frame 5 to gotoAndPlay frame 8, * then upon entering frame 8 the time property is set to 3 (skipping time = 1 * and time = 2).

    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @param enable The true or false value that determines whether the currentFrame property is checked. * @param spanStart The start frame of the animation in terms of the parent MovieClip's timeline. */ - public function useCurrentFrame (enable:Boolean, spanStart:int) : void; + public function useCurrentFrame (enable:Boolean, spanStart:int) : void; /** * Registers the given MovieClip and an AnimatorBase instance for a child of that MovieClip. * The parent MovieClip's FRAME_CONSTRUCTED events are processed, * and its currentFrame and the AnimatorBase's spanStart properties * are used to determine the current relative frame of the animation that should be playing. *

    Calling this function automatically sets the AnimatorBase's useCurrentFrame property to true, * and its spanStart property using the parameter of the same name.

    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @param parent The parent MovieClip of the AnimatorBase instance. * @param anim The AnimatorBase instance associated with the parent MovieClip. * @param spanStart The start frame of the animation in terms of the parent MovieClip's timeline. * @param repeatCount The number of times the animation should play. The default value is 0, which means the animation will loop indefinitely. * @param useCurrentFrame Indicates whether the useCurrentFrame property is checked whenever a new frame is entered. */ - public static function registerParentFrameHandler (parent:MovieClip, anim:AnimatorBase, spanStart:int, repeatCount:int = 0, useCurrentFrame:Boolean = false) : void; - private static function parentEnterFrameHandler (evt:Event) : void; - public static function processCurrentFrame (parent:MovieClip, anim:AnimatorBase, startEnterFrame:Boolean, playOnly:Boolean = false) : void; - public static function registerButtonState (targetParentBtn:SimpleButton, anim:AnimatorBase, stateFrame:int) : void; + public static function registerParentFrameHandler (parent:MovieClip, anim:AnimatorBase, spanStart:int, repeatCount:int = 0, useCurrentFrame:Boolean = false) : void; + private static function parentEnterFrameHandler (evt:Event) : void; + public static function processCurrentFrame (parent:MovieClip, anim:AnimatorBase, startEnterFrame:Boolean, playOnly:Boolean = false) : void; + public static function registerButtonState (targetParentBtn:SimpleButton, anim:AnimatorBase, stateFrame:int) : void; /** * Creates an AnimatorBase object to apply the XML-based motion tween description to a display object. * If XML is null (which is the default value), then you can either supply XML directly to a Motion instance * or you can set the arrays of property values in the Motion instance. * @param xml An E4X object containing an XML-based motion tween description. * * @param target The display object using the motion tween. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword AnimatorBase * @see ../../motionXSD.html Motion XML Elements */ - function AnimatorBase (xml:XML = null, target:DisplayObject = null); + function AnimatorBase (xml:XML = null, target:DisplayObject = null); /** * Advances Flash Player to the next frame in the animation sequence. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword nextFrame */ - public function nextFrame () : void; + public function nextFrame () : void; /** * Begins the animation. Call the end() method * before you call the play() method to ensure that any previous * instance of the animation has ended before you start a new one. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @param startTime Indicates an alternate start time (relative frame) to use. If not specified, then the default start time of 0 is used. * @param startEnterFrame Indicates whether the event listener needs to be added to the parent in order to capture frame events. * The value can be false if the parent was registered to its AnimatorBase instance via registerParentFrameHandler(). * @keyword play, begin * @see #end() */ - public function play (startTime:int = -1, startEnterFrame:Boolean = true) : void; + public function play (startTime:int = -1, startEnterFrame:Boolean = true) : void; /** * Stops the animation and Flash Player goes immediately to the last frame in the animation sequence. * If the autoRewind property is set to true, Flash Player goes to the first * frame in the animation sequence. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @param reset Indicates whether _lastRenderedTime and _target should be reset to their original values. * _target only resets if targetParent and targetName have been supplied. * @keyword end, stop * @see #autoRewind */ - public function end (reset:Boolean = false, stopEnterFrame:Boolean = true) : void; + public function end (reset:Boolean = false, stopEnterFrame:Boolean = true) : void; /** * Stops the animation and Flash Player goes back to the first frame in the animation sequence. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword stop, end * @see #end() */ - public function stop () : void; + public function stop () : void; /** * Pauses the animation until you call the resume() method. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword pause * @see #resume() */ - public function pause () : void; + public function pause () : void; /** * Resumes the animation after it has been paused * by the pause() method. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword resume * @see #pause() */ - public function resume () : void; - public function startFrameEvents () : void; + public function resume () : void; + public function startFrameEvents () : void; /** * Sets Flash Player to the first frame of the animation. * If the animation was playing, it continues playing from the first frame. * If the animation was stopped, it remains stopped at the first frame. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword rewind */ - public function rewind () : void; + public function rewind () : void; /** * @private */ - private function handleLastFrame (reset:Boolean = false, stopEnterFrame:Boolean = true) : void; + private function handleLastFrame (reset:Boolean = false, stopEnterFrame:Boolean = true) : void; /** * @private */ - private function handleEnterFrame (event:Event) : void; - } - internal class AnimatorParent - { - public var parent : MovieClip; - public var animators : Array; - public var lastFrameHandled : int; - - } -} + private function handleEnterFrame (event:Event) : void; + } + internal class AnimatorParent + { + public var parent : MovieClip; + public var animators : Array; + public var lastFrameHandled : int; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactory.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactory.as index 0da6b7d291..ee93380979 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactory.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactory.as @@ -1,23 +1,23 @@ -package fl.motion -{ - import flash.display.DisplayObject; - import flash.display.MovieClip; - import flash.events.Event; - import flash.geom.Point; - import flash.utils.Dictionary; - +package fl.motion +{ + import flash.display.DisplayObject; + import flash.display.MovieClip; + import flash.events.Event; + import flash.geom.Point; + import flash.utils.Dictionary; + /** * The AnimatorFactory class provides ActionScript-based support to associate one Motion object with multiple * display objects. *

    Use the AnimatorFactory constructor to create an AnimatorFactory instance. Then, * use the methods inherited from the * AnimatorFactoryBase class to associate the desired properties with display objects.

    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.Animator * @see fl.motion.AnimatorFactoryBase * @see fl.motion.Motion * @see fl.motion.MotionBase */ - public class AnimatorFactory extends AnimatorFactoryBase - { + public class AnimatorFactory extends AnimatorFactoryBase + { /** * Creates an AnimatorFactory instance you can use to assign the properties of * a MotionBase object to display objects. * @param motion The MotionBase object containing the desired motion properties. * . * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.Animator * @see fl.motion.AnimatorFactoryBase * @see fl.motion.Motion * @see fl.motion.MotionBase */ - public function AnimatorFactory (motion:MotionBase); + public function AnimatorFactory (motion:MotionBase); /** * @private */ - protected function getNewAnimator () : AnimatorBase; - } -} + protected function getNewAnimator () : AnimatorBase; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactory3D.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactory3D.as index 60af3a3056..b3a4678301 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactory3D.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactory3D.as @@ -1,19 +1,19 @@ -package fl.motion -{ - import flash.geom.Vector3D; - +package fl.motion +{ + import flash.geom.Vector3D; + /** * The AnimatorFactory3D class provides ActionScript-based support to associate one Motion object containing * three-dimensional properties with multiple * display objects. If the Motion does not contain three-dimensional properties, use the AnimatorFactory class. *

    Use the AnimatorFactory3D constructor to create an AnimatorFactory3D instance. Then, * use the methods inherited from the * AnimatorFactoryBase class to associate the desired properties with display objects.

    * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @see fl.motion.Animator * @see fl.motion.AnimatorFactoryBase * @see fl.motion.Motion * @see fl.motion.MotionBase */ - public class AnimatorFactory3D extends AnimatorFactoryBase - { + public class AnimatorFactory3D extends AnimatorFactoryBase + { /** * Creates an AnimatorFactory3D instance you can use to assign the properties of * a MotionBase object to display objects. * @param motion The MotionBase object containing the desired three-dimensional motion properties. * . * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @see fl.motion.Animator * @see fl.motion.AnimatorFactoryBase * @see fl.motion.Motion * @see fl.motion.MotionBase */ - public function AnimatorFactory3D (motion:MotionBase); + public function AnimatorFactory3D (motion:MotionBase); /** * @private */ - protected function getNewAnimator () : AnimatorBase; - } -} + protected function getNewAnimator () : AnimatorBase; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactoryBase.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactoryBase.as index 3883b1a828..ff0d8a1d92 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactoryBase.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/AnimatorFactoryBase.as @@ -1,60 +1,60 @@ -package fl.motion -{ - import flash.display.DisplayObject; - import flash.display.DisplayObjectContainer; - import flash.display.MovieClip; - import flash.events.Event; - import flash.geom.Point; - import flash.utils.Dictionary; - import flash.display.SimpleButton; - +package fl.motion +{ + import flash.display.DisplayObject; + import flash.display.DisplayObjectContainer; + import flash.display.MovieClip; + import flash.events.Event; + import flash.geom.Point; + import flash.utils.Dictionary; + import flash.display.SimpleButton; + /** * The AnimatorFactoryBase class provides ActionScript-based support to display and tween multiple targeted objects with one Motion dynamically at runtime. * AnimatorFactoryBase uses the AnimatorBase class to assign one Motion (derived from MotionBase) * to multiple tween instances (targeted objects) * whereas the AnimatorBase class associates a single Motion instance with a single targeted tween object. * The AnimatorFactoryBase class should not be used on its own. Use its subclasses: AnimatorFactory or AnimatorFactory3D, instead. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.Animator * @see fl.motion.AnimatorFactory */ - public class AnimatorFactoryBase - { - private var _motion : MotionBase; - private var _animators : Dictionary; + public class AnimatorFactoryBase + { + private var _motion : MotionBase; + private var _animators : Dictionary; /** * @private */ - protected var _transformationPoint : Point; - protected var _transformationPointZ : int; + protected var _transformationPoint : Point; + protected var _transformationPointZ : int; /** * @private */ - protected var _is3D : Boolean; + protected var _is3D : Boolean; /** * @private */ - protected var _sceneName : String; - + protected var _sceneName : String; + /** * The MotionBase instance that the AnimatorFactoryBase instance and its target objects are associated with. * The MotionBase instance stores the animated properties and their values. * @category Property[read-only] * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.Motion */ - public function get motion () : MotionBase; + public function get motion () : MotionBase; /** * The point of reference for rotating or scaling a display object. * The transformationPoint property (or setter) is overridden in the AnimatorFactory3D subclass, * In 3D, the points are not percentages like they are in 2D; they are absolute values of the original object's transformation point. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ - public function set transformationPoint (p:Point) : void; - public function set transformationPointZ (z:int) : void; - public function set sceneName (name:String) : void; - + public function set transformationPoint (p:Point) : void; + public function set transformationPointZ (z:int) : void; + public function set sceneName (name:String) : void; + /** * Creates an instance of the AnimatorFactoryBase class. * * @param motion The associated MotionBase instance. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public function AnimatorFactoryBase (motion:MotionBase); + public function AnimatorFactoryBase (motion:MotionBase); /** * Creates and returns an AnimatorBase instance whose target property is set to the DisplayObject (if applicable) * that is the targetName property of the targetParent, * and whose Motion property is stored in the AnimatorFactoryBase instance upon creation. * * @param target The display object using the motion tween. * @param repeatCount The number of times the animation should play. The default value is 0, which means the animation will loop indefinitely. * @param autoPlay The value (default is true) specifying whether the animation automatically begins to play. * @param startFrame The frame on which the animation starts relative to the parent's timeline. * If the parent's timeline is shorter than the duration of the associated Motion, * then startFrame indicates the number of frames after this addTarget call is made before the target animation begins. * @param useCurrentFrame A flag specifying, if true, to use the parent's currentFrame property * to determine which animation frame the target object should be on. * @return A new AnimatorBase instance. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see #addTargetInfo() * @see fl.motion.Animator * @see fl.motion.Motion * @see flash.display.DisplayObject */ - public function addTarget (target:DisplayObject, repeatCount:int = 0, autoPlay:Boolean = true, startFrame:int = -1, useCurrentFrame:Boolean = false) : AnimatorBase; + public function addTarget (target:DisplayObject, repeatCount:int = 0, autoPlay:Boolean = true, startFrame:int = -1, useCurrentFrame:Boolean = false) : AnimatorBase; /** * @private */ - protected function getNewAnimator () : AnimatorBase; + protected function getNewAnimator () : AnimatorBase; /** * References the parent DisplayObjectContainer and then creates and returns an AnimatorBase * instance whose target property is set to the DisplayObject (if applicable) * that is the targetName property of the targetParent, * and whose Motion property is stored in the AnimatorFactoryBase instance upon creation. * * @param targetParent The parent DisplayObjectContainer. * @param targetName The target's instance name as seen by its parent. * @param repeatCount The number of times the animation should play. The default value is 0, which means the animation will loop indefinitely. * @param autoPlay The value (default is true) specifying whether the animation automatically begins to play. * @param startFrame The frame on which the animation starts relative to the parent's timeline. * If the parent's timeline is shorter than the duration of the associated Motion, * then startFrame indicates the number of frames after this addTarget call is made before the target animation begins. * @param useCurrentFrame A flag specifying, if true, to use the parent's currentFrame property * to determine which animation frame the target object should be on. * @return A new AnimatorBase instance. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see #addTarget() * @see fl.motion.Animator * @see fl.motion.Motion * @see flash.display.DisplayObjectContainer */ - public function addTargetInfo (targetParent:DisplayObject, targetName:String, repeatCount:int = 0, autoPlay:Boolean = true, startFrame:int = -1, useCurrentFrame:Boolean = false, initialPosition:Array = null) : AnimatorBase; - } -} + public function addTargetInfo (targetParent:DisplayObject, targetName:String, repeatCount:int = 0, autoPlay:Boolean = true, startFrame:int = -1, useCurrentFrame:Boolean = false, initialPosition:Array = null) : AnimatorBase; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/BezierEase.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/BezierEase.as index db08e348da..060426765e 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/BezierEase.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/BezierEase.as @@ -1,49 +1,49 @@ -package fl.motion -{ - import flash.geom.Point; - +package fl.motion +{ + import flash.geom.Point; + /** * The BezierEase class provides precise easing control for a motion tween between two keyframes. * You can apply an instance of this class to all properties of a keyframe at once, * or you can define different curves for different properties. *

    Both this class and the CustomEase class use one or more cubic Bezier curves to define the interpolation. * However, the BezierEase class defines its coordinates slightly differently than the CustomEase class.

    * *

    The BezierEase class uses literal values for the y coordinates of the curve, rather than * normalized values between 0 and 1. * This allows you to create curves that cannot be created with custom easing. For example, * you can create a curve where the start and end values are identical, but the curve rises and falls * in between those values. Also, depending on the context, you may want to define the easing * curve with literal values instead of percentages.

    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword BezierEase, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements * @see CustomEase CustomEase class */ - public class BezierEase implements ITween - { + public class BezierEase implements ITween + { /** * An ordered collection of points in the custom easing curve. * Each item in the array is a flash.geom.Point instance, with x and y properties. *

    The x coordinate of each point represents the time coordinate of the ease, as a percentage. * The x value is normalized to fall between 0 and 1, * where 0 is the beginning of the tween and 1 is the end of the tween. * The y coordinate of each point contains the literal value of the animation property at that point * in the ease. The y value is not normalized to fall between 0 and 1.

    *

    The first and last points of the curve are not included in the array, * because the first point is locked to the starting value, defined by the current keyframe, * and the last point is locked to the ending value, defined by the next keyframe.

    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword points * @see flash.geom.Point */ - public var points : Array; + public var points : Array; /** * @private */ - private var firstNode : Point; + private var firstNode : Point; /** * @private */ - private var lastNode : Point; + private var lastNode : Point; /** * @private */ - private var _target : String; - + private var _target : String; + /** * The name of the animation property to target. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword target * @see fl.motion.ITween#target * @default "" */ - public function get target () : String; + public function get target () : String; /** * @private (setter) */ - public function set target (value:String) : void; - + public function set target (value:String) : void; + /** * Constructor for BezierEase instances. * * @param xml Optional E4X XML object defining a BezierEase in Motion XML format. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword BezierEase */ - function BezierEase (xml:XML = null); + function BezierEase (xml:XML = null); /** * @private */ - private function parseXML (xml:XML = null) : BezierEase; + private function parseXML (xml:XML = null) : BezierEase; /** * Calculates an interpolated value for a numerical property of animation, * using a Bezier easing curve. * The percent value is read from the BezierEase instance's points property, * rather than being passed into the method. * Using the points property value allows the function signature to match the ITween interface. * * @param time The time value, which must be between 0 and duration, inclusive. * The unit can be freely chosen (for example, frames, seconds, milliseconds), * but must match the duration unit. * * @param begin The value of the animation property at the start of the tween, when time is 0. * * @param change The change in the value of the animation property over the course of the tween. * This value can be positive or negative. For example, if an object rotates from 90 to 60 degrees, the change is -30. * * @param duration The length of time for the tween. This value must be greater than zero. * The unit can be freely chosen (for example, frames, seconds, milliseconds), * but must match the time unit. * * @return The interpolated value at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword BezierEase * @see #points */ - public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; - } -} + public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/BezierSegment.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/BezierSegment.as index 337cdf30cf..2c988c705f 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/BezierSegment.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/BezierSegment.as @@ -1,56 +1,56 @@ -package fl.motion -{ - import flash.geom.Point; - +package fl.motion +{ + import flash.geom.Point; + /** * A Bezier segment consists of four Point objects that define a single cubic Bezier curve. * The BezierSegment class also contains methods to find coordinate values along the curve. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword BezierSegment, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class BezierSegment - { + public class BezierSegment + { /** * The first point of the Bezier curve. * It is a node, which means it falls directly on the curve. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript */ - public var a : Point; + public var a : Point; /** * The second point of the Bezier curve. * It is a control point, which means the curve moves toward it, * but usually does not pass through it. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript */ - public var b : Point; + public var b : Point; /** * The third point of the Bezier curve. * It is a control point, which means the curve moves toward it, * but usually does not pass through it. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript */ - public var c : Point; + public var c : Point; /** * The fourth point of the Bezier curve. * It is a node, which means it falls directly on the curve. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript */ - public var d : Point; - + public var d : Point; + /** * Constructor for BezierSegment instances. * * @param a The first point of the curve, a node. * * @param b The second point of the curve, a control point. * * @param c The third point of the curve, a control point. * * @param d The fourth point of the curve, a node. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript * @see #propertyDetail property details */ - function BezierSegment (a:Point, b:Point, c:Point, d:Point); + function BezierSegment (a:Point, b:Point, c:Point, d:Point); /** * Calculates the location of a two-dimensional cubic Bezier curve at a specific time. * * @param t The time or degree of progress along the curve, as a decimal value between 0 and 1. *

    Note: The t parameter does not necessarily move along the curve at a uniform speed. For example, a t value of 0.5 does not always produce a value halfway along the curve.

    * * @return A point object containing the x and y coordinates of the Bezier curve at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript */ - public function getValue (t:Number) : Point; + public function getValue (t:Number) : Point; /** * Calculates the value of a one-dimensional cubic Bezier equation at a specific time. * By contrast, a Bezier curve is usually two-dimensional * and uses two of these equations, one for the x coordinate and one for the y coordinate. * * @param t The time or degree of progress along the curve, as a decimal value between 0 and 1. *

    Note: The t parameter does not necessarily move along the curve at a uniform speed. For example, a t value of 0.5 does not always produce a value halfway along the curve.

    * * @param a The first value of the Bezier equation. * * @param b The second value of the Bezier equation. * * @param c The third value of the Bezier equation. * * @param d The fourth value of the Bezier equation. * * @return The value of the Bezier equation at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript */ - public static function getSingleValue (t:Number, a:Number = 0, b:Number = 0, c:Number = 0, d:Number = 0) : Number; + public static function getSingleValue (t:Number, a:Number = 0, b:Number = 0, c:Number = 0, d:Number = 0) : Number; /** * Finds the y value of a cubic Bezier curve at a given x coordinate. * Some Bezier curves overlap themselves horizontally, * resulting in more than one y value for a given x value. * In that case, this method will return whichever value is most logical. * * Used by CustomEase and BezierEase interpolation. * * @param x An x coordinate that lies between the first and last point, inclusive. * * @param coefficients An optional array of number values that represent the polynomial * coefficients for the Bezier. This array can be used to optimize performance by precalculating * values that are the same everywhere on the curve and do not need to be recalculated for each iteration. * * @return The y value of the cubic Bezier curve at the given x coordinate. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, Copy Motion as ActionScript */ - public function getYForX (x:Number, coefficients:Array = null) : Number; + public function getYForX (x:Number, coefficients:Array = null) : Number; /** * Calculates the coefficients for a cubic polynomial equation, * given the values of the corresponding cubic Bezier equation. * * @param a The first value of the Bezier equation. * * @param b The second value of the Bezier equation. * * @param c The third value of the Bezier equation. * * @param d The fourth value of the Bezier equation. * * @return An array containing four number values, * which are the coefficients for a cubic polynomial. * The coefficients are ordered from the highest degree to the lowest, * so the first number in the array would be multiplied by t^3, the second by t^2, and so on. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript * @see #getCubicRoots() */ - public static function getCubicCoefficients (a:Number, b:Number, c:Number, d:Number) : Array; + public static function getCubicCoefficients (a:Number, b:Number, c:Number, d:Number) : Array; /** * Finds the real solutions, if they exist, to a cubic polynomial equation of the form: at^3 + bt^2 + ct + d. * This method is used to evaluate custom easing curves. * * @param a The first coefficient of the cubic equation, which is multiplied by the cubed variable (t^3). * * @param b The second coefficient of the cubic equation, which is multiplied by the squared variable (t^2). * * @param c The third coefficient of the cubic equation, which is multiplied by the linear variable (t). * * @param d The fourth coefficient of the cubic equation, which is the constant. * * @return An array of number values, indicating the real roots of the equation. * There may be no roots, or as many as three. * Imaginary or complex roots are ignored. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript */ - public static function getCubicRoots (a:Number = 0, b:Number = 0, c:Number = 0, d:Number = 0) : Array; + public static function getCubicRoots (a:Number = 0, b:Number = 0, c:Number = 0, d:Number = 0) : Array; /** * Finds the real solutions, if they exist, to a quadratic equation of the form: at^2 + bt + c. * * @param a The first coefficient of the quadratic equation, which is multiplied by the squared variable (t^2). * * @param b The second coefficient of the quadratic equation, which is multiplied by the linear variable (t). * * @param c The third coefficient of the quadratic equation, which is the constant. * * @return An array of number values, indicating the real roots of the equation. * There may be no roots, or as many as two. * Imaginary or complex roots are ignored. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Bezier curve, node, Copy Motion as ActionScript */ - public static function getQuadraticRoots (a:Number, b:Number, c:Number) : Array; - } -} + public static function getQuadraticRoots (a:Number, b:Number, c:Number) : Array; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Color.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Color.as index 409113e8e3..1ec905fe02 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Color.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Color.as @@ -1,75 +1,75 @@ -package fl.motion -{ - import fl.motion.*; - import flash.display.*; - import flash.geom.ColorTransform; - +package fl.motion +{ + import fl.motion.*; + import flash.display.*; + import flash.geom.ColorTransform; + /** * The Color class extends the Flash Player ColorTransform class, * adding the ability to control brightness and tint. * It also contains static methods for interpolating between two ColorTransform objects * or between two color numbers. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Color, Copy Motion as ActionScript * @see flash.geom.ColorTransform ColorTransform class * @see ../../motionXSD.html Motion XML Elements */ - public class Color extends ColorTransform - { + public class Color extends ColorTransform + { /** * @private */ - private var _tintColor : Number; + private var _tintColor : Number; /** * @private */ - private var _tintMultiplier : Number; - + private var _tintMultiplier : Number; + /** * The percentage of brightness, as a decimal between -1 and 1. * Positive values lighten the object, and a value of 1 turns the object completely white. * Negative values darken the object, and a value of -1 turns the object completely black. * * @default 0 * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword brightness, Copy Motion as ActionScript */ - public function get brightness () : Number; + public function get brightness () : Number; /** * @private (setter) */ - public function set brightness (value:Number) : void; + public function set brightness (value:Number) : void; /** * The tinting color value in the 0xRRGGBB format. * * * @default 0x000000 (black) * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword tint, Copy Motion as ActionScript */ - public function get tintColor () : uint; + public function get tintColor () : uint; /** * @private (setter) */ - public function set tintColor (value:uint) : void; + public function set tintColor (value:uint) : void; /** * The percentage to apply the tint color, as a decimal value between 0 and 1. * When tintMultiplier = 0, the target object is its original color and no tint color is visible. * When tintMultiplier = 1, the target object is completely tinted and none of its original color is visible. * @default 0 * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword tint, Copy Motion as ActionScript */ - public function get tintMultiplier () : Number; + public function get tintMultiplier () : Number; /** * @private (setter) */ - public function set tintMultiplier (value:Number) : void; - + public function set tintMultiplier (value:Number) : void; + /** * Constructor for Color instances. * * @param redMultiplier The percentage to apply the color, as a decimal value between 0 and 1. * @param greenMultiplier The percentage to apply the color, as a decimal value between 0 and 1. * @param blueMultiplier The percentage to apply the color, as a decimal value between 0 and 1. * @param alphaMultiplier A decimal value that is multiplied with the alpha transparency channel value, as a decimal value between 0 and 1. * @param redOffset A number from -255 to 255 that is added to the red channel value after it has been multiplied by the redMultiplier value. * @param greenOffset A number from -255 to 255 that is added to the green channel value after it has been multiplied by the greenMultiplier value. * @param blueOffset A number from -255 to 255 that is added to the blue channel value after it has been multiplied by the blueMultiplier value. * @param alphaOffset A number from -255 to 255 that is added to the alpha channel value after it has been multiplied by the alphaMultiplier value. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Color */ - function Color (redMultiplier:Number = 1.0, greenMultiplier:Number = 1.0, blueMultiplier:Number = 1.0, alphaMultiplier:Number = 1.0, redOffset:Number = 0, greenOffset:Number = 0, blueOffset:Number = 0, alphaOffset:Number = 0); + function Color (redMultiplier:Number = 1.0, greenMultiplier:Number = 1.0, blueMultiplier:Number = 1.0, alphaMultiplier:Number = 1.0, redOffset:Number = 0, greenOffset:Number = 0, blueOffset:Number = 0, alphaOffset:Number = 0); /** * Sets the tint color and amount at the same time. * * @param tintColor The tinting color value in the 0xRRGGBB format. * * @param tintMultiplier The percentage to apply the tint color, as a decimal value between 0 and 1. * When tintMultiplier = 0, the target object is its original color and no tint color is visible. * When tintMultiplier = 1, the target object is completely tinted and none of its original color is visible. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword brightness, Copy Motion as ActionScript */ - public function setTint (tintColor:uint, tintMultiplier:Number) : void; + public function setTint (tintColor:uint, tintMultiplier:Number) : void; /** * @private */ - private function deriveTintColor () : uint; + private function deriveTintColor () : uint; /** * Creates a Color instance from XML. * * @param xml An E4X XML object containing a <color> node from Motion XML. * * @return A Color instance that matches the XML description. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword color, Copy Motion as ActionScript */ - public static function fromXML (xml:XML) : Color; + public static function fromXML (xml:XML) : Color; /** * @private */ - private function parseXML (xml:XML = null) : Color; + private function parseXML (xml:XML = null) : Color; /** * Blends smoothly from one ColorTransform object to another. * * @param fromColor The starting ColorTransform object. * * @param toColor The ending ColorTransform object. * * @param progress The percent of the transition as a decimal, where 0 is the start and 1 is the end. * * @return The interpolated ColorTransform object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword blend, Copy Motion as ActionScript */ - public static function interpolateTransform (fromColor:ColorTransform, toColor:ColorTransform, progress:Number) : ColorTransform; + public static function interpolateTransform (fromColor:ColorTransform, toColor:ColorTransform, progress:Number) : ColorTransform; /** * Blends smoothly from one color value to another. * * @param fromColor The starting color value, in the 0xRRGGBB or 0xAARRGGBB format. * * @param toColor The ending color value, in the 0xRRGGBB or 0xAARRGGBB format. * * @param progress The percent of the transition as a decimal, where 0 is the start and 1 is the end. * * @return The interpolated color value, in the 0xRRGGBB or 0xAARRGGBB format. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @refpath * @keyword blend, Copy Motion as ActionScript */ - public static function interpolateColor (fromColor:uint, toColor:uint, progress:Number) : uint; - } -} + public static function interpolateColor (fromColor:uint, toColor:uint, progress:Number) : uint; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/ColorMatrix.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/ColorMatrix.as index 95a06a854a..e18cb2873f 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/ColorMatrix.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/ColorMatrix.as @@ -1,53 +1,53 @@ -package fl.motion -{ +package fl.motion +{ /** * The ColorMatrix class calculates and stores color matrixes based on given values. * This class extends the DynamicMatrix class and also supports the ColorMatrixFilter class. * @playerversion Flash 9 * @langversion 3.0 * @see fl.motion.DynamicMatrix * @see flash.filters.ColorMatrixFilter */ - public class ColorMatrix extends DynamicMatrix - { + public class ColorMatrix extends DynamicMatrix + { /** * @private */ - protected static const LUMINANCER : Number = 0.3086; + protected static const LUMINANCER : Number = 0.3086; /** * @private */ - protected static const LUMINANCEG : Number = 0.6094; + protected static const LUMINANCEG : Number = 0.6094; /** * @private */ - protected static const LUMINANCEB : Number = 0.0820; - + protected static const LUMINANCEB : Number = 0.0820; + /** * Calculates and stores color matrixes based on given values. * @playerversion Flash 9 * @langversion 3.0 * @see DynamicMatrix */ - public function ColorMatrix (); + public function ColorMatrix (); /** * Calculates and stores a brightness matrix based on the given value. * @playerversion Flash 9 * @langversion 3.0 * @param value 0-255 */ - public function SetBrightnessMatrix (value:Number) : void; + public function SetBrightnessMatrix (value:Number) : void; /** * Calculates and stores a contrast matrix based on the given value. * @playerversion Flash 9 * @langversion 3.0 * @param value 0-255 */ - public function SetContrastMatrix (value:Number) : void; + public function SetContrastMatrix (value:Number) : void; /** * Calculates and stores a saturation matrix based on the given value. * @playerversion Flash 9 * @langversion 3.0 * @param value 0-255 */ - public function SetSaturationMatrix (value:Number) : void; + public function SetSaturationMatrix (value:Number) : void; /** * Calculates and stores a hue matrix based on the given value. * @playerversion Flash 9 * @langversion 3.0 * @param value 0-255 */ - public function SetHueMatrix (angle:Number) : void; + public function SetHueMatrix (angle:Number) : void; /** * Calculates and returns a flat array of 20 numerical values representing the four matrixes set in this object. * @playerversion Flash 9 * @langversion 3.0 * @return An array of 20 items. */ - public function GetFlatArray () : Array; - } - internal class XFormData - { - public var ox : Number; - public var oy : Number; - public var oz : Number; - - } -} + public function GetFlatArray () : Array; + } + internal class XFormData + { + public var ox : Number; + public var oy : Number; + public var oz : Number; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/CustomEase.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/CustomEase.as index 639d892d01..4803f663f8 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/CustomEase.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/CustomEase.as @@ -1,53 +1,53 @@ -package fl.motion -{ - import flash.geom.Point; - +package fl.motion +{ + import flash.geom.Point; + /** * The CustomEase class is used to modify specific properties of the easing behavior of a motion tween as * the tween progresses over time. * A custom easing curve is composed of one or more cubic Bezier curves. * You can apply the custom easing curve to all properties at once, * or you can define different curves for different properties. *

    The implementation of this class parallels the Flash CS4 Custom Ease In/Ease Out dialog box. Flash CS4 * displays a graph in the Custom Ease In/Ease Out dialog box representing the degree of motion over time. * The horizontal axis represents frames, and the vertical axis represents the percent of change of a property * through the progression of the tween. The first keyframe is represented as 0%, and the last keyframe is * represented as 100%. The slope of the graph's curve represents the rate of change of the object. When the * curve is horizontal (no slope), the velocity is zero; when the curve is vertical, an instantaneous rate of * change occurs.

    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class CustomEase implements ITween - { + public class CustomEase implements ITween + { /** * An ordered collection of points in the custom easing curve. * Each item in the array is a flash.geom.Point instance. * The x and y properties of each point are normalized to fall between 0 and 1, * where 0 is the value of the animation property at the beginning of the tween, * and 1 is the value at the end of the tween. * The first and last points of the curve are not included in the array * because the first point is locked to the starting value defined by the current keyframe, * and the last point is locked to the ending value defined by the next keyframe. * On the custom easing curve, these points correspond to values of (0, 0) and (1, 1), respectively. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, points, Copy Motion as ActionScript * @see flash.geom.Point * */ - public var points : Array; + public var points : Array; /** * @private */ - private var firstNode : Point; + private var firstNode : Point; /** * @private */ - private var lastNode : Point; + private var lastNode : Point; /** * @private */ - private var _target : String; - + private var _target : String; + /** * The name of the animation property to target. * @default "" * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Animation, target, Copy Motion as ActionScript * @see fl.motion.ITween#target */ - public function get target () : String; + public function get target () : String; /** * @private (setter) */ - public function set target (value:String) : void; - + public function set target (value:String) : void; + /** * Constructor for CustomEase instances. * * @param xml Optional E4X XML object defining a CustomEase in Motion XML format. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword CustomEase, Copy Motion as ActionScript */ - function CustomEase (xml:XML = null); + function CustomEase (xml:XML = null); /** * @private */ - private function parseXML (xml:XML = null) : CustomEase; + private function parseXML (xml:XML = null) : CustomEase; /** * Calculates an interpolated value for a numerical property of animation, * using a custom easing curve. * The percent value is read from the CustomEase instance's points property, * rather than being passed into the method. * Using the property value allows the function signature to match the ITween interface. * * @param time The time value, which must lie between 0 and duration, inclusive. * You can choose any unit (for example. frames, seconds, milliseconds), * but your choice must match the duration unit. * * @param begin The value of the animation property at the start of the tween, when time is 0. * * @param change The change in the value of the animation property over the course of the tween. * The value can be positive or negative. For example, if an object rotates from 90 to 60 degrees, the change is -30. * * @param duration The length of time for the tween. This value must be greater than zero. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the time unit. * * @return The interpolated value at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword CustomEase, Copy Motion as ActionScript * @see #points */ - public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; + public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; /** * @private */ - static function getYForPercent (percent:Number, pts:Array) : Number; - } -} + static function getYForPercent (percent:Number, pts:Array) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/DynamicMatrix.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/DynamicMatrix.as index bde63eb325..c1457e5b8d 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/DynamicMatrix.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/DynamicMatrix.as @@ -1,78 +1,78 @@ -package fl.motion -{ +package fl.motion +{ /** * The DynamicMatrix class calculates and stores a matrix based on given values. * This class supports the ColorMatrixFilter and can be extended by the ColorMatrix class. * @playerversion Flash 9 * @langversion 3.0 * @see fl.motion.ColorMatrix * @see flash.filters.ColorMatrixFilter */ - public class DynamicMatrix - { + public class DynamicMatrix + { /** * Specifies that a matrix is prepended for concatenation. * @playerversion Flash 9 * @langversion 3.0 */ - public static const MATRIX_ORDER_PREPEND : int = 0; + public static const MATRIX_ORDER_PREPEND : int = 0; /** * Specifies that a matrix is appended for concatenation. * @playerversion Flash 9 * @langversion 3.0 */ - public static const MATRIX_ORDER_APPEND : int = 1; + public static const MATRIX_ORDER_APPEND : int = 1; /** * @private */ - protected var m_width : int; + protected var m_width : int; /** * @private */ - protected var m_height : int; + protected var m_height : int; /** * @private */ - protected var m_matrix : Array; - + protected var m_matrix : Array; + /** * Constructs a matrix with the given number of rows and columns. * @param width Number of columns. * @param height Number of rows. * @playerversion Flash 9 * @langversion 3.0 */ - public function DynamicMatrix (width:int, height:int); + public function DynamicMatrix (width:int, height:int); /** * @private */ - protected function Create (width:int, height:int) : void; + protected function Create (width:int, height:int) : void; /** * @private */ - protected function Destroy () : void; + protected function Destroy () : void; /** * Returns the number of columns in the current matrix. * @return The number of columns. * @playerversion Flash 9 * @langversion 3.0 * @see #GetHeight */ - public function GetWidth () : Number; + public function GetWidth () : Number; /** * Returns the number of rows in the current matrix. * @return The number of rows. * @playerversion Flash 9 * @langversion 3.0 */ - public function GetHeight () : Number; + public function GetHeight () : Number; /** * Returns the value at the specified zero-based row and column in the current matrix. * @param row The row containing the value you want. * @param col The column containing the value you want. * @return Number The value at the specified row and column location. * @playerversion Flash 9 * @langversion 3.0 */ - public function GetValue (row:int, col:int) : Number; + public function GetValue (row:int, col:int) : Number; /** * Sets the value at a specified zero-based row and column in the current matrix. * @param row The row containing the value you want to set. * @param col The column containing the value you want to set. * @param value The number to insert into the matrix. * @playerversion Flash 9 * @langversion 3.0 */ - public function SetValue (row:int, col:int, value:Number) : void; + public function SetValue (row:int, col:int, value:Number) : void; /** * Sets the current matrix to an identity matrix. * @playerversion Flash 9 * @langversion 3.0 * @see flash.geom.Matrix#identity() */ - public function LoadIdentity () : void; + public function LoadIdentity () : void; /** * Sets all values in the current matrix to zero. * @playerversion Flash 9 * @langversion 3.0 */ - public function LoadZeros () : void; + public function LoadZeros () : void; /** * Multiplies the current matrix with a specified matrix; and either * appends or prepends the specified matrix. Use the * second parameter of the DynamicMatrix.Multiply() method to * append or prepend the specified matrix. * @param inMatrix The matrix to add to the current matrix. * @param order Specifies whether to append or prepend the matrix from the * inMatrix parameter; either MATRIX_ORDER_APPEND * or MATRIX_ORDER_PREPEND. * @return A Boolean value indicating whether the multiplication succeeded (true) or * failed (false). The value is false if either the current matrix or * specified matrix (the inMatrix parameter) is null, or if the order is to append and the * current matrix's width is not the same as the supplied matrix's height; or if the order is to prepend * and the current matrix's height is not equal to the supplied matrix's width. * * @playerversion Flash 9 * @langversion 3.0 * @see #MATRIX_ORDER_PREPEND * @see #MATRIX_ORDER_APPEND */ - public function Multiply (inMatrix:DynamicMatrix, order:int = MATRIX_ORDER_PREPEND) : Boolean; + public function Multiply (inMatrix:DynamicMatrix, order:int = MATRIX_ORDER_PREPEND) : Boolean; /** * Multiplies a number with each item in the matrix and stores the results in * the current matrix. * @param value A number to multiply by each item in the matrix. * @return A Boolean value indicating whether the multiplication succeeded (true) * or failed (false). * @playerversion Flash 9 * @langversion 3.0 */ - public function MultiplyNumber (value:Number) : Boolean; + public function MultiplyNumber (value:Number) : Boolean; /** * Adds the current matrix with a specified matrix. The * current matrix becomes the result of the addition (in other * words the DynamicMatrix.Add() method does * not create a new matrix to contain the result). * @param inMatrix The matrix to add to the current matrix. * @return A Boolean value indicating whether the addition succeeded (true) * or failed (false). If the dimensions of the matrices are not * the same, DynamicMatrix.Add() returns false. * @playerversion Flash 9 * @langversion 3.0 */ - public function Add (inMatrix:DynamicMatrix) : Boolean; - } -} + public function Add (inMatrix:DynamicMatrix) : Boolean; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/FunctionEase.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/FunctionEase.as index 1188c956da..5590b3105e 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/FunctionEase.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/FunctionEase.as @@ -1,57 +1,57 @@ -package fl.motion -{ - import flash.utils.*; - +package fl.motion +{ + import flash.utils.*; + /** * The FunctionEase class allows custom interpolation functions to be used with * the fl.motion framework in place of other interpolations like SimpleEase and CustomEase. * The fl.motion framework includes several easing functions in the fl.motion.easing package. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @includeExample examples\FunctionEaseExample.as -noswf * @see ../../motionXSD.html Motion XML Elements * @see fl.motion.easing */ - public class FunctionEase implements ITween - { + public class FunctionEase implements ITween + { /** * @private */ - private var _functionName : String; + private var _functionName : String; /** * A reference to a function with a (t, b, c, d) signature like * the methods in the fl.motion.easing classes. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Easing, Copy Motion as ActionScript * @see fl.motion.easing */ - public var easingFunction : Function; + public var easingFunction : Function; /** * An optional array of values to be passed to the easing function as additional arguments. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Easing, Copy Motion as ActionScript */ - public var parameters : Array; + public var parameters : Array; /** * @private */ - private var _target : String; - + private var _target : String; + /** * The fully qualified name of an easing function, such as fl.motion.easing.Bounce.easeOut(). * The function must be a method of a class (Bounce, Cubic, Elastic, another class). * If Flash Player cannot find the class, an exception is thrown. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Easing, Copy Motion as ActionScript * @see fl.motion.easing */ - public function get functionName () : String; + public function get functionName () : String; /** * @private (setter) */ - public function set functionName (newName:String) : void; + public function set functionName (newName:String) : void; /** * The name of the animation property to target. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Easing, Copy Motion as ActionScript * @see fl.motion.ITween#target */ - public function get target () : String; + public function get target () : String; /** * @private (setter) */ - public function set target (value:String) : void; - + public function set target (value:String) : void; + /** * Constructor for FunctionEase instances. * * @param xml An optional E4X XML instance. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Easing, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - function FunctionEase (xml:XML = null); + function FunctionEase (xml:XML = null); /** * @private */ - private function parseXML (xml:XML = null) : FunctionEase; + private function parseXML (xml:XML = null) : FunctionEase; /** * Calculates an interpolated value for a numerical property of animation, * using the specified easing function. * If the parameters array has been set beforehand, * those values will be passed to the easing function in addition to the * time, begin, change, and duration values. * * @param time The time value, which must lie between 0 and duration, inclusive. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the duration unit. * * @param begin The value of the animation property at the start of the tween, when time is 0. * * @param change The change in the value of the animation property over the course of the tween. * The value can be positive or negative. For example, if an object rotates from 90 to 60 degrees, the change is -30. * * @param duration The length of time for the tween. Must be greater than zero. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the time unit. * * @return The interpolated value at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Easing, Copy Motion as ActionScript */ - public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; - } -} + public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/ITween.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/ITween.as index 81263d80de..259656de55 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/ITween.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/ITween.as @@ -1,22 +1,22 @@ -package fl.motion -{ +package fl.motion +{ /** * The ITween interface defines the application programming interface (API) that interpolation * classes implement in order to work with the fl.motion classes. * The SimpleEase, CustomEase, BezierEase, and FunctionEase classes implement the ITween interface. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public interface ITween - { + public interface ITween + { /** * The name of the animation property to target. *

    The default value is "" (empty quotes), which targets all properties. * The other acceptable values are "x", "y", "position" (which targets both x and y), * "scaleX", "scaleY", "scale" (which targets both scaleX and scaleY), * "skewX", "skewY", "rotation" (which targets both scaleX and scaleY), "color", and "filters".

    * * @default "" * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword ITween, Copy Motion as ActionScript */ - public function get target () : String; + public function get target () : String; /** * @private (setter) */ - public function set target (value:String) : void; - + public function set target (value:String) : void; + /** * Calculates an interpolated value for a numerical property of animation. * The function signature matches that of the easing functions in the fl.motion.easing package. * Various ITween classes will produce different styles of interpolation for the same inputs. * * @param time The time value, which must be between 0 and duration, inclusive. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the duration unit. * * @param begin The value of the animation property at the start of the tween, when time is 0. * * @param change The change in the value of the animation property over the course of the tween. * This value can be positive or negative. For example, if an object rotates from 90 to 60 degrees, the change is -30. * * @param duration The length of time for the tween. This value must be greater than zero. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the time unit. * * @return The interpolated value at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword ITween, Copy Motion as ActionScript * @see fl.motion.easing */ - public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; - } -} + public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Keyframe.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Keyframe.as index 9aee078a28..c2dc0503f7 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Keyframe.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Keyframe.as @@ -1,61 +1,61 @@ -package fl.motion -{ - import flash.display.BlendMode; - import flash.filters.BitmapFilter; - import flash.filters.ColorMatrixFilter; - import flash.utils.*; - +package fl.motion +{ + import flash.display.BlendMode; + import flash.filters.BitmapFilter; + import flash.filters.ColorMatrixFilter; + import flash.utils.*; + /** * The Keyframe class defines the visual state at a specific time in a motion tween. * The primary animation properties are position, scale, rotation, skew, and color. * A keyframe can, optionally, define one or more of these properties. * For instance, one keyframe may affect only position, * while another keyframe at a different point in time may affect only scale. * Yet another keyframe may affect all properties at the same time. * Within a motion tween, each time index can have only one keyframe. * A keyframe also has other properties like blend mode, filters, and cacheAsBitmap, * which are always available. For example, a keyframe always has a blend mode. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements * @see fl.motion.KeyframeBase */ - public class Keyframe extends KeyframeBase - { + public class Keyframe extends KeyframeBase + { /** * An array that contains each tween object to be applied to the target object at a particular keyframe. * One tween can target all animation properties (as with standard tweens on the Flash authoring tool's timeline), * or multiple tweens can target individual properties (as with separate custom easing curves). * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var tweens : Array; + public var tweens : Array; /** * A flag that controls whether scale will be interpolated during a tween. * If false, the display object will stay the same size during the tween, until the next keyframe. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var tweenScale : Boolean; + public var tweenScale : Boolean; /** * Stores the value of the Snap checkbox for motion tweens, which snaps the object to a motion guide. * This property is used in the Copy and Paste Motion feature in Flash CS4 * but does not affect motion tweens defined using ActionScript. * It is included here for compatibility with the Flex 2 compiler. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var tweenSnap : Boolean; + public var tweenSnap : Boolean; /** * Stores the value of the Sync checkbox for motion tweens, which affects graphic symbols only. * This property is used in the Copy and Paste Motion feature in Flash CS4 * but does not affect motion tweens defined using ActionScript. * It is included here for compatibility with the Flex 2 compiler. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var tweenSync : Boolean; - - public function get tweensLength () : int; - + public var tweenSync : Boolean; + + public function get tweensLength () : int; + /** * Constructor for keyframe instances. * * @param xml Optional E4X XML object defining a keyframe in Motion XML format. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - function Keyframe (xml:XML = null); + function Keyframe (xml:XML = null); /** * @private */ - private function parseXML (xml:XML = null) : KeyframeBase; + private function parseXML (xml:XML = null) : KeyframeBase; /** * @private */ - private static function splitNumber (valuesString:String) : Array; + private static function splitNumber (valuesString:String) : Array; /** * @private */ - private static function splitUint (valuesString:String) : Array; + private static function splitUint (valuesString:String) : Array; /** * @private */ - private static function splitInt (valuesString:String) : Array; + private static function splitInt (valuesString:String) : Array; /** * Retrieves an ITween object for a specific animation property. * * @param target The name of the property being tweened. * @see fl.motion.ITween#target * * @return An object that implements the ITween interface. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public function getTween (target:String = '') : ITween; + public function getTween (target:String = '') : ITween; /** * @private */ - protected function hasTween () : Boolean; - } -} + protected function hasTween () : Boolean; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/KeyframeBase.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/KeyframeBase.as index 160719153a..4191daf9f2 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/KeyframeBase.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/KeyframeBase.as @@ -1,161 +1,161 @@ -package fl.motion -{ - import flash.display.BlendMode; - import flash.filters.BitmapFilter; - import flash.filters.ColorMatrixFilter; - import flash.utils.*; - +package fl.motion +{ + import flash.display.BlendMode; + import flash.filters.BitmapFilter; + import flash.filters.ColorMatrixFilter; + import flash.utils.*; + /** * The KeyframeBase class defines the visual state at a specific time in a motion tween. * The primary animation properties are position, scale, rotation, skew, and color. * To use KeyframeBase, all properties must have values for every KeyframeBase, * and there must be a KeyframeBase defined for every frame in the motion. * Within a motion tween, each time index can have only one keyframe. * A keyframe also has other properties like blend mode, filters, and cacheAsBitmap, * which are always available. For example, a keyframe always has a blend mode. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class KeyframeBase - { + public class KeyframeBase + { /** * @private */ - private var _index : int; + private var _index : int; /** * The horizontal position of the target object's transformation point in its parent's coordinate space. * A value of NaN means that the keyframe does not affect this property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var x : Number; + public var x : Number; /** * The vertical position of the target object's transformation point in its parent's coordinate space. * A value of NaN means that the keyframe does not affect this property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var y : Number; + public var y : Number; /** * Indicates the horizontal scale as a percentage of the object as applied from the transformation point. * A value of 1 is 100% of normal size. * A value of NaN means that the keyframe does not affect this property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var scaleX : Number; + public var scaleX : Number; /** * Indicates the vertical scale as a percentage of the object as applied from the transformation point. * A value of 1 is 100% of normal size. * A value of NaN means that the keyframe does not affect this property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var scaleY : Number; + public var scaleY : Number; /** * Indicates the horizontal skew angle of the target object in degrees as applied from the transformation point. * A value of NaN means that the keyframe does not affect this property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var skewX : Number; + public var skewX : Number; /** * Indicates the vertical skew angle of the target object in degrees as applied from the transformation point. * A value of NaN means that the keyframe does not affect this property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var skewY : Number; + public var skewY : Number; /** * The rotation (z-axis) values of the target object in the motion relative to previous orientation as applied from the transformation point, * as opposed to absolute rotation values, and separate from skewY values. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var rotationConcat : Number; + public var rotationConcat : Number; /** * If set to true, this property causes the target object to rotate when data for motion is supplied by addpropertyarray. * Also when true, the rotationConcat property is used instead of rotation. The default is * false. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var useRotationConcat : Boolean; + public var useRotationConcat : Boolean; /** * An array that contains each filter object to be applied to the target object at a particular keyframe. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var filters : Array; + public var filters : Array; /** * A color object that adjusts the color transform in the target object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var color : fl.motion.Color; + public var color : fl.motion.Color; /** * A string used to describe the keyframe. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var label : String; + public var label : String; /** * Stores the value of the Loop checkbox for motion tweens, which affects graphic symbols only. * This property is used in the Copy and Paste Motion feature in Flash CS4 * but does not affect motion tweens defined using ActionScript. * It is included here for compatibility with the Flex 2 compiler. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var loop : String; + public var loop : String; /** * Stores the name of the first frame for motion tweens, which affects graphic symbols only. * This property is used in the Copy and Paste Motion feature in Flash CS4 * but does not affect motion tweens defined using ActionScript. * It is included here for compatibility with the Flex 2 compiler. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var firstFrame : String; + public var firstFrame : String; /** * If set to true, Flash Player caches an internal bitmap representation of the display object. * Using this property often allows faster rendering than the default use of vectors. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var cacheAsBitmap : Boolean; + public var cacheAsBitmap : Boolean; /** * A value from the BlendMode class that specifies how Flash Player * mixes the display object's colors with graphics underneath it. * * @see flash.display.BlendMode * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var blendMode : String; + public var blendMode : String; /** * Controls how the target object rotates during a motion tween, * with a value from the RotateDirection class. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript * @see fl.motion.RotateDirection */ - public var rotateDirection : String; + public var rotateDirection : String; /** * Adds rotation to the target object during a motion tween, in addition to any existing rotation. * This rotation is dependent on the value of the rotateDirection property, * which must be set to RotateDirection.CW or RotateDirection.CCW. * The rotateTimes value must be an integer that is equal to or greater than zero. * *

    For example, if the object would normally rotate from 0 to 40 degrees, * setting rotateTimes to 1 and rotateDirection to RotateDirection.CW * will add a full turn, for a total rotation of 400 degrees.

    * * If rotateDirection is set to RotateDirection.CCW, * 360 degrees will be subtracted from the normal rotation, * resulting in a counterclockwise turn of 320 degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript * @see #rotateDirection */ - public var rotateTimes : uint; + public var rotateTimes : uint; /** * If set to true, this property causes the target object to rotate automatically * to follow the angle of its path. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var orientToPath : Boolean; + public var orientToPath : Boolean; /** * Indicates that the target object should not be displayed on this keyframe. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public var blank : Boolean; + public var blank : Boolean; /** * Stores matrix3d property if one exists for this keyframe. matrix3d is used for non-tween frames containing 3D. * You can use either the matrix3d property or the other 3D properties (z, rotationX, rotationY), but not both sets together. * If matrix3d is set to something other than null, then it is used instead of any other properties (2D properties included). * * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ - public var matrix3D : Object; + public var matrix3D : Object; /** * The depth (z-axis) position of the target object's transformation point in its parent's coordinate space. * When referring to a 3D plane, a z-axis refers to the depth of a 3D object. * A value of NaN means that the keyframe does not affect this property. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 */ - public var z : Number; + public var z : Number; /** * Stores rotationX property for this keyframe. This property is the rotation of the target object around the x-axis from its original orientation. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public var rotationX : Number; + public var rotationX : Number; /** * Stores rotationY property for this keyframe. This property is the rotation of the target object around the y-axis from its original orientation. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public var rotationY : Number; + public var rotationY : Number; /** * Stores AdjustColor instances mapped to their corresponding index in the filters Array for this keyframe. * This is used for Flash authoring's AdjustColor filters, which correspond to ColorMatrixFilters in Flash Player. * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public var adjustColorObjects : Dictionary; - + public var adjustColorObjects : Dictionary; + /** * The keyframe's unique time value in the motion tween. The first frame in a motion tween has an index of 0. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public function get index () : int; + public function get index () : int; /** * @private (setter) */ - public function set index (value:int) : void; + public function set index (value:int) : void; /** * Indicates the rotation of the target object in degrees * from its original orientation as applied from the transformation point. * A value of NaN means that the keyframe does not affect this property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public function get rotation () : Number; + public function get rotation () : Number; /** * @private (setter) */ - public function set rotation (value:Number) : void; - public function get tweensLength () : int; - + public function set rotation (value:Number) : void; + public function get tweensLength () : int; + /** * Constructor for keyframe instances. * * @param xml Optional E4X XML object defining a keyframe in Motion XML format. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - function KeyframeBase (xml:XML = null); + function KeyframeBase (xml:XML = null); /** * @private */ - private function setDefaults () : void; + private function setDefaults () : void; /** * Retrieves the value of a specific tweenable property on the keyframe. * * @param tweenableName The name of a tweenable property, such as "x" * or "rotation". * * @return The numerical value of the tweenable property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public function getValue (tweenableName:String) : Number; + public function getValue (tweenableName:String) : Number; /** * Changes the value of a specific tweenable property on the keyframe. * * @param tweenableName The name of a tweenable property, such as "x" * or "rotation". * * @param newValue A numerical value to assign to the tweenable property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public function setValue (tweenableName:String, newValue:Number) : void; + public function setValue (tweenableName:String, newValue:Number) : void; /** * @private */ - protected function hasTween () : Boolean; + protected function hasTween () : Boolean; /** * Indicates whether the keyframe has an influence on a specific animation property. * * @param tweenableName The name of a tweenable property, such as "x" * or "rotation". * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Keyframe, Copy Motion as ActionScript */ - public function affectsTweenable (tweenableName:String = '') : Boolean; + public function affectsTweenable (tweenableName:String = '') : Boolean; /** * Sets one of the four AdjustColor properties to the AdjustColor object for the given filter index. * It creates the AdjustColor instance if one does not exist for that index yet. * The four properties that can be set are: *
    • adjustColorBrightness
    • *
    • adjustColorContrast
    • *
    • adjustColorSaturation
    • *
    • adjustColorHue
    * All four AdjustColor properties must be set in order for the filter to be created. * Once all four properties are set on an AdjustColor instance, * the function gets from the AdjustColor object a flat array of 20 values representing all four properties, * and creates a ColorMatrixFilter instance, which requires the flattened array. * @param filterIndex The index position of the filter in the filters array to add the * propertyName property. * @param propertyName One of the four allowed properties values: "adjustColorBrightness", * "adjustColorContrast", "adjustColorSaturation", or "adjustColorHue". * @param value The value to set for the specified property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.AdjustColor */ - public function setAdjustColorProperty (filterIndex:int, propertyName:String, value:*) : void; - } -} + public function setAdjustColorProperty (filterIndex:int, propertyName:String, value:*) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MatrixTransformer.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MatrixTransformer.as index fd5ddb875c..8b50b5f2a8 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MatrixTransformer.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MatrixTransformer.as @@ -1,87 +1,87 @@ -package fl.motion -{ - import flash.geom.*; - +package fl.motion +{ + import flash.geom.*; + /** * The MatrixTransformer class contains methods for modifying individual properties of a transformation matrix: * horizontal and vertical scale, horizontal and vertical skew, and rotation. * This class also has methods for rotating around a given transformation point rather than the typical (0, 0) point. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword MatrixTransformer, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements * @see flash.geom */ - public class MatrixTransformer - { + public class MatrixTransformer + { /** * Calculates the horizontal scale present in a matrix. * * @param m A Matrix instance. * * @return The horizontal scale. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function getScaleX (m:Matrix) : Number; + public static function getScaleX (m:Matrix) : Number; /** * Changes the horizontal scale in a matrix. * * @param m A Matrix instance to be modified. * * @param scaleX The new horizontal scale. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function setScaleX (m:Matrix, scaleX:Number) : void; + public static function setScaleX (m:Matrix, scaleX:Number) : void; /** * Calculates the vertical scale present in a matrix. * * @param m A Matrix instance. * * @return The vertical scale. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function getScaleY (m:Matrix) : Number; + public static function getScaleY (m:Matrix) : Number; /** * Changes the vertical scale in a matrix. * * @param m A Matrix instance to be modified. * * @param scaleY The new vertical scale. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function setScaleY (m:Matrix, scaleY:Number) : void; + public static function setScaleY (m:Matrix, scaleY:Number) : void; /** * Calculates the angle of horizontal skew present in a matrix, in radians. * * @param m A Matrix instance. * * @return The angle of horizontal skew, in radians. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function getSkewXRadians (m:Matrix) : Number; + public static function getSkewXRadians (m:Matrix) : Number; /** * Changes the horizontal skew in a matrix. * * @param m A Matrix instance to be modified. * * @param skewX The new horizontal skew, in radians. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function setSkewXRadians (m:Matrix, skewX:Number) : void; + public static function setSkewXRadians (m:Matrix, skewX:Number) : void; /** * Calculates the angle of vertical skew present in a matrix, in radians. * * @param m A Matrix instance. * * @return The angle of vertical skew, in radians. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function getSkewYRadians (m:Matrix) : Number; + public static function getSkewYRadians (m:Matrix) : Number; /** * Changes the vertical skew in a matrix. * * @param m A Matrix instance to be modified. * * @param skewY The new vertical skew, in radians. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function setSkewYRadians (m:Matrix, skewY:Number) : void; + public static function setSkewYRadians (m:Matrix, skewY:Number) : void; /** * Calculates the angle of horizontal skew present in a matrix, in degrees. * * @param m A Matrix instance. * * @return The angle of horizontal skew, in degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function getSkewX (m:Matrix) : Number; + public static function getSkewX (m:Matrix) : Number; /** * Changes the horizontal skew in a matrix. * * @param m A Matrix instance to be modified. * * @param skewX The new horizontal skew, in degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function setSkewX (m:Matrix, skewX:Number) : void; + public static function setSkewX (m:Matrix, skewX:Number) : void; /** * Calculates the angle of vertical skew present in a matrix, in degrees. * * @param m A Matrix instance. * * @return The angle of vertical skew, in degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function getSkewY (m:Matrix) : Number; + public static function getSkewY (m:Matrix) : Number; /** * Changes the vertical skew in a matrix. * * @param m A Matrix instance to be modified. * * @param skewX The new vertical skew, in degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function setSkewY (m:Matrix, skewY:Number) : void; + public static function setSkewY (m:Matrix, skewY:Number) : void; /** * Calculates the angle of rotation present in a matrix, in radians. * If the horizontal and vertical skews are not equal, * the vertical skew value is used. * * @param m A Matrix instance. * * @return The angle of rotation, in radians. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function getRotationRadians (m:Matrix) : Number; + public static function getRotationRadians (m:Matrix) : Number; /** * Changes the angle of rotation in a matrix. * If the horizontal and vertical skews are not equal, * the vertical skew is set to the rotation value * and the horizontal skew is increased by the difference between the * old rotation and the new rotation. * This matches the rotation behavior in Flash Player. * * @param m A Matrix instance. * * @param rotation The angle of rotation, in radians. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function setRotationRadians (m:Matrix, rotation:Number) : void; + public static function setRotationRadians (m:Matrix, rotation:Number) : void; /** * Calculates the angle of rotation present in a matrix, in degrees. * If the horizontal and vertical skews are not equal, * the vertical skew value is used. * This matches the rotation behavior in Flash Player. * * @param m A Matrix instance. * * @return The angle of rotation, in degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function getRotation (m:Matrix) : Number; + public static function getRotation (m:Matrix) : Number; /** * Changes the angle of rotation in a matrix. * If the horizontal and vertical skews are not equal, * the vertical skew is set to the rotation value * and the horizontal skew is increased by the difference between the * old rotation and the new rotation. * This matches the rotation behavior in Flash Player. * * @param m A Matrix instance. * * @param rotation The angle of rotation, in degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function setRotation (m:Matrix, rotation:Number) : void; + public static function setRotation (m:Matrix, rotation:Number) : void; /** * Rotates a matrix about a point defined inside the matrix's transformation space. * This can be used to rotate a movie clip around a transformation point inside itself. * * @param m A Matrix instance. * * @param x The x coordinate of the point. * * @param y The y coordinate of the point. * * @param angleDegrees The angle of rotation in degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function rotateAroundInternalPoint (m:Matrix, x:Number, y:Number, angleDegrees:Number) : void; + public static function rotateAroundInternalPoint (m:Matrix, x:Number, y:Number, angleDegrees:Number) : void; /** * Rotates a matrix about a point defined outside the matrix's transformation space. * This can be used to rotate a movie clip around a transformation point in its parent. * * @param m A Matrix instance. * * @param x The x coordinate of the point. * * @param y The y coordinate of the point. * * @param angleDegrees The angle of rotation in degrees. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function rotateAroundExternalPoint (m:Matrix, x:Number, y:Number, angleDegrees:Number) : void; + public static function rotateAroundExternalPoint (m:Matrix, x:Number, y:Number, angleDegrees:Number) : void; /** * Moves a matrix as necessary to align an internal point with an external point. * This can be used to match a point in a transformed movie clip with one in its parent. * * @param m A Matrix instance. * * @param internalPoint A Point instance defining a position within the matrix's transformation space. * * @param externalPoint A Point instance defining a reference position outside the matrix's transformation space. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Matrix, Copy Motion as ActionScript * @see flash.geom.Matrix */ - public static function matchInternalPointWithExternal (m:Matrix, internalPoint:Point, externalPoint:Point) : void; - } -} + public static function matchInternalPointWithExternal (m:Matrix, internalPoint:Point, externalPoint:Point) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Motion.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Motion.as index 898a68c329..50e9b456cd 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Motion.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Motion.as @@ -1,75 +1,75 @@ -package fl.motion -{ - import flash.filters.*; - import flash.geom.ColorTransform; - import flash.utils.*; - +package fl.motion +{ + import flash.filters.*; + import flash.geom.ColorTransform; + import flash.utils.*; + /** * The Motion class stores a keyframe animation sequence that can be applied to a visual object. * The animation data includes position, scale, rotation, skew, color, filters, and easing. * The Motion class has methods for retrieving data at specific points in time, and * interpolating values between keyframes automatically. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class Motion extends MotionBase - { + public class Motion extends MotionBase + { /** * An object that stores information about the context in which the motion was created, * such as frame rate, dimensions, transformation point, and initial position, scale, rotation, and skew. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript */ - public var source : Source; + public var source : Source; /** * @private */ - private var _keyframesCompact : Array; + private var _keyframesCompact : Array; /** * @private */ - private static var typeCache : Object; - + private static var typeCache : Object; + /** * A compact array of keyframes, where each index is occupied by a keyframe. * By contrast, a sparse array has empty indices (as in the keyframes property). * In the compact array, no null values are used to fill indices between keyframes. * However, the index of a keyframe in keyframesCompact likely does not match its index in the keyframes array. *

    This property is primarily used for compatibility with the Flex MXML compiler, * which generates a compact array from the motion XML.

    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see #keyframes */ - public function get keyframesCompact () : Array; + public function get keyframesCompact () : Array; /** * @private (setter) */ - public function set keyframesCompact (compactArray:Array) : void; - + public function set keyframesCompact (compactArray:Array) : void; + /** * Constructor for Motion instances. * By default, one initial keyframe is created automatically, with default transform properties. * * @param xml Optional E4X XML object defining a Motion instance. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript */ - function Motion (xml:XML = null); + function Motion (xml:XML = null); /** * Retrieves an interpolated ColorTransform object at a specific time index in the Motion instance. * * @param index The time index of a frame in the Motion instance, as an integer greater than or equal to zero. * * @return The interpolated ColorTransform object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see flash.geom.ColorTransform */ - public function getColorTransform (index:int) : ColorTransform; + public function getColorTransform (index:int) : ColorTransform; /** * Retrieves an interpolated array of filters at a specific time index in the Motion instance. * * @param index The time index of a frame in the Motion instance, as an integer greater than or equal to zero. * * @return The interpolated array of filters. * If there are no applicable filters, returns an empty array. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see flash.filters */ - public function getFilters (index:Number) : Array; + public function getFilters (index:Number) : Array; /** * @private */ - protected function findTweenedValue (index:Number, tweenableName:String, curKeyframeBase:KeyframeBase, timeFromKeyframe:Number, begin:Number) : Number; + protected function findTweenedValue (index:Number, tweenableName:String, curKeyframeBase:KeyframeBase, timeFromKeyframe:Number, begin:Number) : Number; /** * @private */ - private function parseXML (xml:XML) : Motion; + private function parseXML (xml:XML) : Motion; /** * A method needed to create a Motion instance from a string of XML. * * @param xmlString A string of motion XML. * * @return A new Motion instance. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript */ - public static function fromXMLString (xmlString:String) : Motion; + public static function fromXMLString (xmlString:String) : Motion; /** * Blends filters smoothly from one array of filter objects to another. * * @param fromFilters The starting array of filter objects. * * @param toFilters The ending array of filter objects. * * @param progress The percent of the transition as a decimal, where 0 is the start and 1 is the end. * * @return The interpolated array of filter objects. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see flash.filters */ - public static function interpolateFilters (fromFilters:Array, toFilters:Array, progress:Number) : Array; + public static function interpolateFilters (fromFilters:Array, toFilters:Array, progress:Number) : Array; /** * Blends filters smoothly from one filter object to another. * * @param fromFilters The starting filter object. * * @param toFilters The ending filter object. * * @param progress The percent of the transition as a decimal, where 0 is the start and 1 is the end. * * @return The interpolated filter object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see flash.filters */ - public static function interpolateFilter (fromFilter:BitmapFilter, toFilter:BitmapFilter, progress:Number) : BitmapFilter; + public static function interpolateFilter (fromFilter:BitmapFilter, toFilter:BitmapFilter, progress:Number) : BitmapFilter; /** * @private */ - private static function getTypeInfo (o:*) : XML; + private static function getTypeInfo (o:*) : XML; /** * @private */ - protected function getNewKeyframe (xml:XML = null) : KeyframeBase; - } -} + protected function getNewKeyframe (xml:XML = null) : KeyframeBase; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MotionBase.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MotionBase.as index 8f8a7adabf..d14f7cc4d0 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MotionBase.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MotionBase.as @@ -1,111 +1,111 @@ -package fl.motion -{ - import flash.filters.*; - import flash.geom.ColorTransform; - import flash.utils.*; - +package fl.motion +{ + import flash.filters.*; + import flash.geom.ColorTransform; + import flash.utils.*; + /** * The MotionBase class stores a keyframe animation sequence that can be applied to a visual object. * The animation data includes position, scale, rotation, skew, color, filters, and easing. * The MotionBase class has methods for retrieving data at specific keyframe points. To get * interpolated values between keyframes, use the Motion class. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see fl.motion.Motion Motion class * @see ../../motionXSD.html Motion XML Elements */ - public class MotionBase - { + public class MotionBase + { /** * An array of keyframes that define the motion's behavior over time. * This property is a sparse array, where a keyframe is placed at an index in the array * that matches its own index. A motion object with keyframes at 0 and 5 has * a keyframes array with a length of 6. * Indices 0 and 5 in the array each contain a keyframe, * and indices 1 through 4 have null values. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript */ - public var keyframes : Array; + public var keyframes : Array; /** * @private */ - private var _duration : int; - private var _is3D : Boolean; + private var _duration : int; + private var _is3D : Boolean; /** * Indicates whether property values for scale, skew, and rotate added in subsequent * calls to addPropertyArray should be made relative to the first value, or used as-is, * such that they override the target object's initial target transform. */ - private var _overrideScale : Boolean; - private var _overrideSkew : Boolean; - private var _overrideRotate : Boolean; - + private var _overrideScale : Boolean; + private var _overrideSkew : Boolean; + private var _overrideRotate : Boolean; + /** * Controls the Motion instance's length of time, measured in frames. * The duration cannot be less than the time occupied by the Motion instance's keyframes. * @default 0 * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript */ - public function get duration () : int; + public function get duration () : int; /** * @private (setter) */ - public function set duration (value:int) : void; + public function set duration (value:int) : void; /** * Specifies whether the motion contains 3D property changes. If true, the * motion contains 3D property changes. * @default false * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript */ - public function get is3D () : Boolean; + public function get is3D () : Boolean; /** * Sets flag that indicates whether the motion contains 3D properties. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript */ - public function set is3D (enable:Boolean) : void; - + public function set is3D (enable:Boolean) : void; + /** * Constructor for MotionBase instances. * By default, one initial keyframe is created automatically, with default transform properties. * * @param xml Optional E4X XML object defining a Motion instance. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript */ - function MotionBase (xml:XML = null); - public function overrideTargetTransform (scale:Boolean = true, skew:Boolean = true, rotate:Boolean = true) : void; + function MotionBase (xml:XML = null); + public function overrideTargetTransform (scale:Boolean = true, skew:Boolean = true, rotate:Boolean = true) : void; /** * @private */ - private function indexOutOfRange (index:int) : Boolean; + private function indexOutOfRange (index:int) : Boolean; /** * Retrieves the keyframe that is currently active at a specific frame in the Motion instance. * A frame that is not a keyframe derives its values from the keyframe that preceded it. * *

    This method can also filter values by the name of a specific tweenables property. * You can find the currently active keyframe for x, which may not be * the same as the currently active keyframe in general.

    * * @param index The index of a frame in the Motion instance, as an integer greater than or equal to zero. * * @param tweenableName Optional name of a tweenable's property (like "x" or "rotation"). * * @return The closest matching keyframe at or before the supplied frame index. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see fl.motion.Tweenables */ - public function getCurrentKeyframe (index:int, tweenableName:String = '') : KeyframeBase; + public function getCurrentKeyframe (index:int, tweenableName:String = '') : KeyframeBase; /** * Retrieves the next keyframe after a specific frame in the Motion instance. * If a frame is not a keyframe, and is in the middle of a tween, * this method derives its values from both the preceding keyframe and the following keyframe. * *

    This method also allows you to filter by the name of a specific tweenables property * to find the next keyframe for a property, which might not be * the same as the next keyframe in general.

    * * @param index The index of a frame in the Motion instance, as an integer greater than or equal to zero. * * @param tweenableName Optional name of a tweenable's property (like "x" or "rotation"). * * @return The closest matching keyframe after the supplied frame index. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see fl.motion.Tweenables */ - public function getNextKeyframe (index:int, tweenableName:String = '') : KeyframeBase; + public function getNextKeyframe (index:int, tweenableName:String = '') : KeyframeBase; /** * Sets the value of a specific tweenables property at a given time index in the Motion instance. * If a keyframe doesn't exist at the index, one is created automatically. * * @param index The time index of a frame in the Motion instance, as an integer greater than zero. * If the index is zero, no change is made. * Transformation properties are relative to the starting transformation values of the target object, * the values for the first frame (zero index value) are always default values and should not be changed. * * @param tweenableName The name of a tweenable's property as a string (like "x" or "rotation"). * * @param value The new value of the tweenable property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see fl.motion.Tweenables */ - public function setValue (index:int, tweenableName:String, value:Number) : void; + public function setValue (index:int, tweenableName:String, value:Number) : void; /** * Retrieves an interpolated ColorTransform object at a specific time index in the Motion instance. * * @param index The time index of a frame in the Motion instance, as an integer greater than or equal to zero. * * @return The interpolated ColorTransform object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see flash.geom.ColorTransform */ - public function getColorTransform (index:int) : ColorTransform; + public function getColorTransform (index:int) : ColorTransform; /** * Returns the Matrix3D object for the specified index position of * the frame of animation. * @param index The zero-based index position of the frame of animation containing the 3D matrix. * @return The Matrix3D object, or null value. This method can return a null value even if * MotionBase.is3D is true, because other 3D motion tween property changes can be used * without a Matrix3D object. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see flash.geom.Matrix3D */ - public function getMatrix3D (index:int) : Object; + public function getMatrix3D (index:int) : Object; /** * Rotates the target object when data for the motion is supplied by the addPropertyArray() method. * @playerversion Flash 10 * @playerversion AIR 1.5 * @langversion 3.0 * @param index The index position of the frame of animation. * @return Indicates whether the target object will rotate using the stored property from * KeyframeBase.rotationConcat. * @keyword Motion, Copy Motion as ActionScript * @see #addPropertyArray() * @see fl.motion.KeyframeBase#rotationConcat */ - public function useRotationConcat (index:int) : Boolean; + public function useRotationConcat (index:int) : Boolean; /** * Retrieves an interpolated array of filters at a specific time index in the Motion instance. * * @param index The time index of a frame in the Motion, as an integer greater than or equal to zero. * * @return The interpolated array of filters. * If there are no applicable filters, returns an empty array. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see flash.filters */ - public function getFilters (index:Number) : Array; + public function getFilters (index:Number) : Array; /** * @private */ - protected function findTweenedValue (index:Number, tweenableName:String, curKeyframeBase:KeyframeBase, timeFromKeyframe:Number, begin:Number) : Number; + protected function findTweenedValue (index:Number, tweenableName:String, curKeyframeBase:KeyframeBase, timeFromKeyframe:Number, begin:Number) : Number; /** * Retrieves the value for an animation property at a point in time. * * @param index The time index of a frame in the Motion instance, as an integer greater than or equal to zero. * * @param tweenableName The name of a tweenable's property (like "x" or "rotation"). * @return The number value for the property specified in the tweenableName parameter. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see fl.motion.Tweenables */ - public function getValue (index:Number, tweenableName:String) : Number; + public function getValue (index:Number, tweenableName:String) : Number; /** * Adds a keyframe object to the Motion instance. * * @param newKeyframe A keyframe object with an index property already set. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see fl.motion.Keyframe */ - public function addKeyframe (newKeyframe:KeyframeBase) : void; + public function addKeyframe (newKeyframe:KeyframeBase) : void; /** * Stores an array of values in corresponding keyframes for a declared property of the Motion class. * The order of the values in the array determines the assignment of each value to a keyframe. For each * non-null value in the given values array, this method finds the keyframe * corresponding to the value's index position in the array, or creates a new keyframe for that index * position, and stores the property name/value pair in the keyframe. * * @param name The name of the Motion class property to store in each keyframe. * * @param values The array of values for the property specified in the name * parameter. Each non-null value is assigned to a keyframe that corresponds to the value's * order in the array. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see fl.motion.Motion */ - public function addPropertyArray (name:String, values:Array, startFrame:int = -1, endFrame:int = -1) : void; + public function addPropertyArray (name:String, values:Array, startFrame:int = -1, endFrame:int = -1) : void; /** * Initializes the filters list for the target object and copies the list of filters to each Keyframe * instance of the Motion object. * * @param filterClasses An array of filter classes. Each item in the array is the fully qualified * class name (in String form) for the filter type occupying that index. * * @param gradientSubarrayLengths An array of numbers containing a value for every filter that will be in the filters * list for the motion (every class name in the filterClasses array). A value in the * gradientSubarrayLengths array is only used if the filter class entry at the same index position in the * filterClasses array is GradientGlowFilter or GradientBevelFilter. * The corresponding value in the gradientSubarrayLengths array is a number that determines the length for the arrays * that initialize the colors, alphas, and ratios parameters for the * GradientGlowFilter and GradientBevelFilter constructor functions. * * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see flash.filters * @see flash.filters.GradientGlowFilter * @see flash.filters.GradientBevelFilter */ - public function initFilters (filterClasses:Array, gradientSubarrayLengths:Array, startFrame:int = -1, endFrame:int = -1) : void; + public function initFilters (filterClasses:Array, gradientSubarrayLengths:Array, startFrame:int = -1, endFrame:int = -1) : void; /** * Modifies a filter property in all corresponding keyframes for a Motion object. Call initFilters() before * using this method. The order of the values in the array determines the assignment of each value * to the filter property for all keyframes. For each non-null value in the specified values * array, this method finds the keyframe corresponding to the value's index position in the array, * and stores the property name/value pair for the filter in the keyframe. * * @param index The zero-based index position in the array of filters. * * @param name The name of the filter property to store in each keyframe. * * @param values The array of values for the property specified in the name * parameter. Each non-null value is assigned to the filter in a keyframe that corresponds to * the value's index in the array. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Motion, Copy Motion as ActionScript * @see #initFilters() * @see flash.filters */ - public function addFilterPropertyArray (index:int, name:String, values:Array, startFrame:int = -1, endFrame:int = -1) : void; + public function addFilterPropertyArray (index:int, name:String, values:Array, startFrame:int = -1, endFrame:int = -1) : void; /** * @private */ - protected function getNewKeyframe (xml:XML = null) : KeyframeBase; - } -} + protected function getNewKeyframe (xml:XML = null) : KeyframeBase; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MotionEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MotionEvent.as index a2c6e15f70..bb4d23970a 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MotionEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/MotionEvent.as @@ -1,36 +1,36 @@ -package fl.motion -{ - import flash.events.Event; - +package fl.motion +{ + import flash.events.Event; + /** * The MotionEvent class represents events that are broadcast by the fl.motion.Animator class. * Use these events with an event listener to initiate custom functions. For example, if you * have an Animator instance named abox_animator, Flash Player executes the following * trace statement when the animation is complete: * * import fl.motion.MotionEvent; * abox_animator.addEventListener(MotionEvent.MOTION_END,afterMotion); * function afterMotion(e:MotionEvent) { * trace("animation complete!"); * } * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword MotionEvent, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements * @see fl.motion.Animator * @see flash.events.IEventDispatcher */ - public class MotionEvent extends Event - { + public class MotionEvent extends Event + { /** * Indicates that the Motion instance has started playing. *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.Animator#event:motionStart * * @eventType motionStart */ - public static const MOTION_START : String = 'motionStart'; + public static const MOTION_START : String = 'motionStart'; /** * Indicates that the motion has stopped, * whether by an explicit call to Animator.stop() or Animator.end(), * or by reaching the end of the Motion instance. *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.Animator#event:motionEnd * * @eventType motionEnd */ - public static const MOTION_END : String = 'motionEnd'; + public static const MOTION_END : String = 'motionEnd'; /** * Indicates that the Motion instance has changed and the screen has been updated. *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.Animator#event:motionUpdate * * @eventType motionUpdate */ - public static const MOTION_UPDATE : String = 'motionUpdate'; + public static const MOTION_UPDATE : String = 'motionUpdate'; /** * Indicates that the Animator instance's time value has changed, * but the screen has not yet been updated (Flash Player has not dispatched the motionUpdate event). *

    The properties of the event object have the following values:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @see fl.motion.Animator#event:timeChange * * @eventType timeChange */ - public static const TIME_CHANGE : String = 'timeChange'; - + public static const TIME_CHANGE : String = 'timeChange'; + /** * Constructor. * * @param type The event type; indicates the action that caused the event. * * @param bubbles Specifies whether the event can bubble up the display list hierarchy. * * @param cancelable Specifies whether the behavior associated with the event can be prevented. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * */ - public function MotionEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false); + public function MotionEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false); /** * @private */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/RotateDirection.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/RotateDirection.as index eea1a82ca9..790e588d65 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/RotateDirection.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/RotateDirection.as @@ -1,26 +1,26 @@ -package fl.motion -{ +package fl.motion +{ /** * The RotateDirection class provides constant values for rotation behavior during a tween. * Used by the rotateDirection property of the fl.motion.Keyframe class. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword RotateDirection, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements * @see fl.motion.Keyframe#rotateDirection */ - public class RotateDirection - { + public class RotateDirection + { /** * Chooses a direction of rotation that requires the least amount of turning. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword RotateDirection, Copy Motion as ActionScript */ - public static const AUTO : String = 'auto'; + public static const AUTO : String = 'auto'; /** * Prevents the object from rotating during a tween until the next keyframe is reached. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword RotateDirection, Copy Motion as ActionScript */ - public static const NONE : String = 'none'; + public static const NONE : String = 'none'; /** * Ensures that the object rotates clockwise during a tween * to match the rotation of the object in the following keyframe. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword RotateDirection, Copy Motion as ActionScript */ - public static const CW : String = 'cw'; + public static const CW : String = 'cw'; /** * Ensures that the object rotates counterclockwise during a tween * to match the rotation of the object in the following keyframe. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword RotateDirection, Copy Motion as ActionScript */ - public static const CCW : String = 'ccw'; - - } -} + public static const CCW : String = 'ccw'; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/SimpleEase.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/SimpleEase.as index 9df8c8020f..95a3207e1e 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/SimpleEase.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/SimpleEase.as @@ -1,55 +1,55 @@ -package fl.motion -{ +package fl.motion +{ /** * The SimpleEase class allows you to control an animation with * the kind of percentage easing that is used in the Flash timeline. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword SimpleEase, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class SimpleEase implements ITween - { + public class SimpleEase implements ITween + { /** * @private */ - private var _ease : Number; + private var _ease : Number; /** * @private */ - private var _target : String; - + private var _target : String; + /** * A percentage between -1 (100% ease in or acceleration) and 1 (100% ease out or deceleration). * Defaults to 0, which means that the tween animates at a constant speed, without acceleration or deceleration. * @default 0 * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword SimpleEase, Copy Motion as ActionScript */ - public function get ease () : Number; + public function get ease () : Number; /** * @private (setter) */ - public function set ease (value:Number) : void; + public function set ease (value:Number) : void; /** * The name of the animation property to target. * @see fl.motion.ITween#target * @default "" * @playerversion Flash 9.0.28.0 * @langversion 3.0 */ - public function get target () : String; + public function get target () : String; /** * @private (setter) */ - public function set target (value:String) : void; - + public function set target (value:String) : void; + /** * Constructor for SimpleEase instances. * * @param xml Optional E4X XML object defining a SimpleEase object in Motion XML format. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword SimpleEase, Copy Motion as ActionScript */ - function SimpleEase (xml:XML = null); + function SimpleEase (xml:XML = null); /** * @private */ - private function parseXML (xml:XML = null) : SimpleEase; + private function parseXML (xml:XML = null) : SimpleEase; /** * Calculates an interpolated value for a numerical property of animation, * using a percentage of quadratic easing. * The function signature matches that of the easing functions in the fl.motion.easing package. * * @param time This value is between 0 and duration, inclusive. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the duration unit. * * @param begin The value of the animation property at the start of the tween, when time is 0. * * @param change The change in the value of the animation property over the course of the tween. * This value can be positive or negative. For example, if an object rotates from 90 to 60 degrees, the change is -30. * * @param duration The length of time for the tween. This value must be greater than zero. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the time unit. * * @param percent A percentage between -1 (100% ease in or acceleration) and 1 (100% ease out or deceleration). * * @return The interpolated value at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword SimpleEase, Copy Motion as ActionScript * @see fl.motion.easing */ - public static function easeQuadPercent (time:Number, begin:Number, change:Number, duration:Number, percent:Number) : Number; + public static function easeQuadPercent (time:Number, begin:Number, change:Number, duration:Number, percent:Number) : Number; /** * Calculates an interpolated value for a numerical property of animation, * using a linear tween of constant velocity. * The function signature matches that of the easing functions in the fl.motion.easing package. * * @param time This value is between 0 and duration, inclusive. * You can choose any unit(for example, frames, seconds, milliseconds), * but your choice must match the duration unit. * * @param begin The value of the animation property at the start of the tween, when time is 0. * * @param change The change in the value of the animation property over the course of the tween. * This value can be positive or negative. For example, if an object rotates from 90 to 60 degrees, the change is -30. * * @param duration The length of time for the tween. This value must be greater than zero. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the time unit. * * @return The interpolated value at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword SimpleEase, Copy Motion as ActionScript * @see fl.motion.easing */ - public static function easeNone (time:Number, begin:Number, change:Number, duration:Number) : Number; + public static function easeNone (time:Number, begin:Number, change:Number, duration:Number) : Number; /** * Calculates an interpolated value for a numerical property of animation, * using a percentage of quadratic easing. * The percent value is read from the SimpleEase instance's ease property * rather than being passed into the method. * Using this property allows the function signature to match the ITween interface. * * @param time This value is between 0 and duration, inclusive. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the duration unit. * * @param begin The value of the animation property at the start of the tween, when time is 0. * * @param change The change in the value of the animation property over the course of the tween. * This value can be positive or negative. For example, if an object rotates from 90 to 60 degrees, the change is -30. * * @param duration The length of time for the tween. This value must be greater than zero. * You can choose any unit (for example, frames, seconds, milliseconds), * but your choice must match the time unit. * * @return The interpolated value at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword SimpleEase, Copy Motion as ActionScript * @see #ease */ - public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; - } -} + public function getValue (time:Number, begin:Number, change:Number, duration:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Source.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Source.as index e97bec309a..d615ca2b16 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Source.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Source.as @@ -1,78 +1,78 @@ -package fl.motion -{ - import fl.motion.*; - import flash.geom.Point; - import flash.geom.Rectangle; - +package fl.motion +{ + import fl.motion.*; + import flash.geom.Point; + import flash.geom.Rectangle; + /** * The Source class stores information about the context in which a Motion instance was generated. * Many of its properties do not affect animation created using ActionScript with the Animator class * but are present to store data from the Motion XML. * The transformationPoint property is the most important for an ActionScript Motion instance. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements */ - public class Source - { + public class Source + { /** * Indicates the frames per second of the movie in which the Motion instance was generated. * This property stores data from Motion XML but does not affect Motion instances created using ActionScript. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript */ - public var frameRate : Number; + public var frameRate : Number; /** * Indicates the type of object from which the Motion instance was generated. * Possible values are "rectangle object", "oval object", "drawing object", "group", "bitmap", "compiled clip", "video", "text" * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript */ - public var elementType : String; + public var elementType : String; /** * Indicates the name of the symbol from which the Motion instance was generated. * This property stores data from Motion XML but does not affect Motion instances created using ActionScript. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript */ - public var symbolName : String; + public var symbolName : String; /** * Indicates the instance name given to the movie clip from which the Motion instance was generated. * This property stores data from Motion XML but does not affect Motion instances created using ActionScript. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript */ - public var instanceName : String; + public var instanceName : String; /** * Indicates the library linkage identifier for the symbol from which the Motion instance was generated. * This property stores data from Motion XML but does not affect Motion instances created using ActionScript. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript */ - public var linkageID : String; + public var linkageID : String; /** * Indicates the x value of the original object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript * @see fl.motion.Keyframe#x */ - public var x : Number; + public var x : Number; /** * Indicates the y value of the original object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript * @see fl.motion.Keyframe#y */ - public var y : Number; + public var y : Number; /** * Indicates the scaleX value of the original object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript * @see fl.motion.Keyframe#scaleX */ - public var scaleX : Number; + public var scaleX : Number; /** * Indicates the scaleY value of the original object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript * @see fl.motion.Keyframe#scaleY */ - public var scaleY : Number; + public var scaleY : Number; /** * Indicates the skewX value of the original object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript * @see fl.motion.Keyframe#skewX */ - public var skewX : Number; + public var skewX : Number; /** * Indicates the skewY value of the original object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript * @see fl.motion.Keyframe#skewY */ - public var skewY : Number; + public var skewY : Number; /** * Indicates the rotation value of the original object. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript * @see fl.motion.Keyframe#rotation */ - public var rotation : Number; + public var rotation : Number; /** * Specifies the location of the transformation or "pivot" point of the original object, * from which transformations are applied. * The coordinates of the transformation point are defined as a percentage of the visual object's dimensions (its bounding box). If the transformation point is at the upper-left * corner of the bounding box, the coordinates are (0, 0). The lower-right corner of the * bounding box is (1, 1). This property allows the transformation point to be applied * consistently to objects of different proportions * and registration points. The transformation point can lie outside of the bounding box, * in which case the coordinates may be less than 0 or greater than 1. * This property has a strong effect on Motion instances created using ActionScript. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript */ - public var transformationPoint : Point; + public var transformationPoint : Point; /** * Indicates the position and size of the bounding box of the object from which the Motion instance was generated. * This property stores data from Motion XML but does not affect Motion instances created using ActionScript. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript */ - public var dimensions : Rectangle; - + public var dimensions : Rectangle; + /** * Constructor for Source instances. * * @param xml Optional E4X XML object defining a Source instance in Motion XML format. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Source, Copy Motion as ActionScript */ - function Source (xml:XML = null); + function Source (xml:XML = null); /** * @private */ - private function parseXML (xml:XML = null) : Source; - } -} + private function parseXML (xml:XML = null) : Source; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Tweenables.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Tweenables.as index 8bdae82084..d30f3fba8c 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Tweenables.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/Tweenables.as @@ -1,54 +1,54 @@ -package fl.motion -{ +package fl.motion +{ /** * The Tweenables class provides constant values for the names of animation properties used in the MotionBase and KeyframeBase classes. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see ../../motionXSD.html Motion XML Elements * @see fl.motion.MotionBase * @see fl.motion.KeyframeBase */ - public class Tweenables - { + public class Tweenables + { /** * Constant for the x property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#x */ - public static const X : String = 'x'; + public static const X : String = 'x'; /** * Constant for the y property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#y */ - public static const Y : String = 'y'; + public static const Y : String = 'y'; /** * Constant for the z property. * @playerversion Flash 10 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#z */ - public static const Z : String = 'z'; + public static const Z : String = 'z'; /** * Constant for the scaleX property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#scaleX */ - public static const SCALE_X : String = 'scaleX'; + public static const SCALE_X : String = 'scaleX'; /** * Constant for the scaleY property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#scaleY */ - public static const SCALE_Y : String = 'scaleY'; + public static const SCALE_Y : String = 'scaleY'; /** * Constant for the skewX property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#skewX */ - public static const SKEW_X : String = 'skewX'; + public static const SKEW_X : String = 'skewX'; /** * Constant for the skewY property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#skewY */ - public static const SKEW_Y : String = 'skewY'; + public static const SKEW_Y : String = 'skewY'; /** * Constant for the rotation property. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#rotation */ - public static const ROTATION : String = 'rotation'; + public static const ROTATION : String = 'rotation'; /** * Constant for the rotationX property. * @playerversion Flash 10 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#rotationX */ - public static const ROTATION_X : String = 'rotationX'; + public static const ROTATION_X : String = 'rotationX'; /** * Constant for the rotationY property. * @playerversion Flash 10 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#rotationY */ - public static const ROTATION_Y : String = 'rotationY'; + public static const ROTATION_Y : String = 'rotationY'; /** * Constant for the rotationConcat property. * @playerversion Flash 10 * @langversion 3.0 * @keyword Tweenables, Copy Motion as ActionScript * @see fl.motion.KeyframeBase#rotationConcat */ - public static const ROTATION_CONCAT : String = 'rotationConcat'; - - } -} + public static const ROTATION_CONCAT : String = 'rotationConcat'; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Back.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Back.as index 3bbe6d7550..89d3615ee1 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Back.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Back.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Back class defines three easing functions to implement * motion with ActionScript animations. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Back - { + public class Back + { /** * The easeIn() method starts * the motion by backtracking and * then reversing direction and moving toward the target. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param s Specifies the amount of overshoot, where the higher the value, * the greater the overshoot. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; /** * The easeOut() method starts the motion by * moving towards the target, overshooting it slightly, * and then reversing direction back toward the target. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param s Specifies the amount of overshoot, where the higher the value, * the greater the overshoot. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion by backtracking, then reversing direction and * moving toward the target, overshooting the target slightly, reversing * direction again, and then moving back toward the target. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param s Specifies the amount of overshoot, where the higher the value, * the greater the overshoot. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Bounce.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Bounce.as index 303d2f0440..612d21e334 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Bounce.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Bounce.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Bounce class defines three easing functions to implement * bouncing motion with ActionScript animation, similar to a ball * falling and bouncing on a floor with several decaying rebounds. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Bounce - { + public class Bounce + { /** * The easeOut() method starts the bounce motion fast * and then decelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeIn() method starts the bounce motion slowly * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the bounce motion slowly, accelerate motion, then decelerate. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Circular.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Circular.as index 31ac42bac0..fd336bf78d 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Circular.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Circular.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Circular class defines three easing functions to implement * motion with ActionScript animation. The acceleration of motion for a Circular * easing equation produces an abrupt change in velocity. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Circular - { + public class Circular + { /** * The easeIn() method starts motion from zero velocity * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, accelerate motion, * then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Cubic.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Cubic.as index 97de3b2517..b1083285d6 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Cubic.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Cubic.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Cubic class defines three easing functions to implement * motion with ActionScript animation. The acceleration of motion for a Cubic easing * equation is greater than for a Quadratic easing equation. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Cubic - { + public class Cubic + { /** * The easeIn() method starts motion from zero velocity * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, accelerate motion, * then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Elastic.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Elastic.as index d0093250c1..a79896056e 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Elastic.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Elastic.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Elastic class defines three easing functions to implement * motion with ActionScript animation, where the motion is defined by * an exponentially decaying sine wave. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Elastic - { + public class Elastic + { /** * The easeIn() method starts motion slowly * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param a Specifies the amplitude of the sine wave. * * @param p Specifies the period of the sine wave. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param a Specifies the amplitude of the sine wave. * * @param p Specifies the period of the sine wave. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion slowly, accelerate motion, then decelerate. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param a Specifies the amplitude of the sine wave. * * @param p Specifies the period of the sine wave. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Exponential.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Exponential.as index 3c265eebb8..91a35c0e10 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Exponential.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Exponential.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Exponential class defines three easing functions to implement * motion with ActionScript animation. It produces * an effect similar to the popular * "Zeno's paradox" style of scripted easing, * where each interval of time decreases the remaining * distance by a constant proportion. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Exponential - { + public class Exponential + { /** * The easeIn() method starts motion slowly * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial position of a component. * * @param c Specifies the total change in position of the component. * * @param d Specifies the duration of the effect, in milliseconds. * * @return Number corresponding to the position of the component. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, accelerate motion, * then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Linear.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Linear.as index 6aa8a41999..899bb80252 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Linear.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Linear.as @@ -1,25 +1,25 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Linear class defines easing functions to implement * non-accelerated motion with ActionScript animations. * Its methods all produce the same effect, a constant motion. * The various names easeIn, easeOut and so on, * are provided in the interest of polymorphism. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Linear - { + public class Linear + { /** * The easeNone() method defines a constant motion * with no acceleration. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeNone (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeNone (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeIn() method defines a constant motion * with no acceleration. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method defines a constant motion * with no acceleration. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method defines a constant motion * with no acceleration. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quadratic.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quadratic.as index eb87cbc71d..4680931c34 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quadratic.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quadratic.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Quadratic class defines three easing functions to implement * accelerated motion with ActionScript animations. The acceleration of motion * for a Quadratic easing equation is the same as for a timeline tween at 100% easing * and is less dramatic than for the Cubic easing equation. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Quadratic - { + public class Quadratic + { /** * The easeIn() method starts motion from a zero velocity * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, * accelerate motion, then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quartic.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quartic.as index 7fc75506c7..b4edbc9ceb 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quartic.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quartic.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Quartic class defines three easing functions to implement * motion with ActionScript animation. The acceleration of motion for a Quartic easing * equation is greater than for a Cubic easing equation. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Quartic - { + public class Quartic + { /** * The easeIn() method starts motion from zero velocity * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, accelerate motion, * then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quintic.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quintic.as index 1c9eb0eb49..a38b36fa2e 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quintic.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Quintic.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Quintic class defines three easing functions to implement * motion with ActionScript animation. The acceleration of motion for a Quintic easing * equation is greater than for a Quartic easing equation. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Quintic - { + public class Quintic + { /** * The easeIn() method starts motion from zero velocity * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, accelerate motion, * then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Sine.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Sine.as index 7e3550640a..1cd8be4633 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Sine.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/motion/easing/Sine.as @@ -1,21 +1,21 @@ -package fl.motion.easing -{ +package fl.motion.easing +{ /** * The Sine class defines three easing functions to implement * motion with ActionScript animation. The acceleration of motion for a Sine * easing equation is less than that for a Quadratic equation. * * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see ../../../motionXSD.html Motion XML Elements * @see fl.motion.FunctionEase */ - public class Sine - { + public class Sine + { /** * The easeIn() method starts motion from zero velocity * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, accelerate motion, * then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * @playerversion Flash 9.0.28.0 * @langversion 3.0 * @keyword Ease, Copy Motion as ActionScript * @see fl.motion.FunctionEase */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Blinds.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Blinds.as index 3345d42139..6d42272c6f 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Blinds.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Blinds.as @@ -1,54 +1,54 @@ -package fl.transitions -{ - import flash.display.MovieClip; - import flash.geom.*; - +package fl.transitions +{ + import flash.display.MovieClip; + import flash.geom.*; + /** * The Blinds class reveals the movie clip object by using appearing or disappearing rectangles. * This effect requires the following parameters: *
    • numStrips: The number of masking strips in the Blinds effect. * The recommended range is 1 to 50.
    • *
    • dimension: An integer that indicates whether the masking strips are * to be vertical (0) or horizontal (1).
    *

    For example, the following code uses the Blinds transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:Blinds, direction:Transition.IN, duration:2, easing:None.easeNone, numStrips:10, dimension:0}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Blinds, Transitions * @see fl.transitions.TransitionManager */ - public class Blinds extends Transition - { + public class Blinds extends Transition + { /** * @private */ - protected var _numStrips : uint; + protected var _numStrips : uint; /** * @private */ - protected var _dimension : uint; + protected var _dimension : uint; /** * @private */ - protected var _mask : MovieClip; + protected var _mask : MovieClip; /** * @private */ - protected var _innerMask : MovieClip; - + protected var _innerMask : MovieClip; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Blinds (content:MovieClip, transParams:Object, manager:TransitionManager); + function Blinds (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - public function start () : void; + public function start () : void; /** * @private */ - public function cleanUp () : void; + public function cleanUp () : void; /** * @private */ - protected function _initMask () : void; + protected function _initMask () : void; /** * @private */ - protected function _render (p:Number) : void; - } -} + protected function _render (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Fade.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Fade.as index 5a9bf1967e..fa700e4971 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Fade.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Fade.as @@ -1,29 +1,29 @@ -package fl.transitions -{ - import flash.display.*; - +package fl.transitions +{ + import flash.display.*; + /** * The Fade class fades the movie clip object in or out. This effect requires no additional parameters. *

    For example, the following code uses the Fade transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:Fade, direction:Transition.IN, duration:9, easing:Strong.easeOut}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Fade, Transitions * @see fl.transitions.TransitionManager */ - public class Fade extends Transition - { + public class Fade extends Transition + { /** * @private */ - protected var _alphaFinal : Number; - + protected var _alphaFinal : Number; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Fade (content:MovieClip, transParams:Object, manager:TransitionManager); + function Fade (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - protected function _render (p:Number) : void; - } -} + protected function _render (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Fly.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Fly.as index bc51cefc52..480d8d5ee4 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Fly.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Fly.as @@ -1,54 +1,54 @@ -package fl.transitions -{ - import flash.display.*; - import flash.geom.*; - +package fl.transitions +{ + import flash.display.*; + import flash.geom.*; + /** * The Fly class slides the movie clip object in from a specified direction. This effect requires the * following parameters: *
    • startPoint: An integer indicating a starting position; the range * is 1 to 9: Top Left:1; Top Center:2, Top Right:3; Left Center:4; Center:5; Right Center:6; Bottom Left:7; Bottom Center:8, Bottom Right:9.
    *

    For example, the following code uses the Fly transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:Fly, direction:Transition.IN, duration:3, easing:Elastic.easeOut, startPoint:9}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Fly, Transitions * @see fl.transitions.TransitionManager */ - public class Fly extends Transition - { + public class Fly extends Transition + { /** * @private */ - public var className : String; + public var className : String; /** * @private */ - protected var _startPoint : Number; + protected var _startPoint : Number; /** * @private */ - protected var _xFinal : Number; + protected var _xFinal : Number; /** * @private */ - protected var _yFinal : Number; + protected var _yFinal : Number; /** * @private */ - protected var _xInitial : Number; + protected var _xInitial : Number; /** * @private */ - protected var _yInitial : Number; + protected var _yInitial : Number; /** * @private */ - protected var _stagePoints : Object; - + protected var _stagePoints : Object; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Fly (content:MovieClip, transParams:Object, manager:TransitionManager); + function Fly (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - protected function _render (p:Number) : void; - } -} + protected function _render (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Iris.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Iris.as index 83c421bc8a..07f68ade6f 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Iris.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Iris.as @@ -1,94 +1,94 @@ -package fl.transitions -{ - import flash.display.MovieClip; - import flash.geom.*; - +package fl.transitions +{ + import flash.display.MovieClip; + import flash.geom.*; + /** * The Iris class reveals the movie clip object by using an animated mask of a square shape or a * circle shape that zooms in or out. This effect requires the * following parameters: *
    • startPoint: An integer indicating a starting position; the range * is 1 to 9: Top Left:1; Top Center:2, Top Right:3; Left Center:4; Center:5; Right Center:6; Bottom Left:7; Bottom Center:8, Bottom Right:9.
    • *
    • shape: A mask shape of either fl.transitions.Iris.SQUARE (a square) or fl.transitions.Iris.CIRCLE (a circle).
    *

    For example, the following code uses a circle-shaped animated mask transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:Iris, direction:Transition.IN, duration:2, easing:Strong.easeOut, startPoint:5, shape:Iris.CIRCLE}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Iris, Transitions * @see fl.transitions.TransitionManager */ - public class Iris extends Transition - { + public class Iris extends Transition + { /** * Used to specify a square mask shape for the transition effect. * @playerversion Flash 9 * @langversion 3.0 * @keyword Iris, Transitions */ - public static const SQUARE : String = "SQUARE"; + public static const SQUARE : String = "SQUARE"; /** * Used to specify a circle mask shape for the transition effect. * @playerversion Flash 9 * @langversion 3.0 * @keyword Iris, Transitions */ - public static const CIRCLE : String = "CIRCLE"; + public static const CIRCLE : String = "CIRCLE"; /** * @private */ - protected var _mask : MovieClip; + protected var _mask : MovieClip; /** * @private */ - protected var _startPoint : uint; + protected var _startPoint : uint; /** * @private */ - protected var _cornerMode : Boolean; + protected var _cornerMode : Boolean; /** * @private */ - protected var _shape : String; + protected var _shape : String; /** * @private */ - protected var _maxDimension : Number; + protected var _maxDimension : Number; /** * @private */ - protected var _minDimension : Number; + protected var _minDimension : Number; /** * @private */ - protected var _renderFunction : Function; - + protected var _renderFunction : Function; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Iris (content:MovieClip, transParams:Object, manager:TransitionManager); + function Iris (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - public function start () : void; + public function start () : void; /** * @private */ - public function cleanUp () : void; + public function cleanUp () : void; /** * @private */ - protected function _initMask () : void; + protected function _initMask () : void; /** * @private stub--dynamically overwritten by one of the other render methods */ - protected function _render (p:Number) : void; + protected function _render (p:Number) : void; /** * @private */ - protected function _renderCircle (p:Number) : void; + protected function _renderCircle (p:Number) : void; /** * @private */ - protected function _drawQuarterCircle (mc:MovieClip, r:Number) : void; + protected function _drawQuarterCircle (mc:MovieClip, r:Number) : void; /** * @private */ - protected function _drawHalfCircle (mc:MovieClip, r:Number) : void; + protected function _drawHalfCircle (mc:MovieClip, r:Number) : void; /** * @private */ - protected function _renderSquareEdge (p:Number) : void; + protected function _renderSquareEdge (p:Number) : void; /** * @private */ - protected function _renderSquareCorner (p:Number) : void; - } -} + protected function _renderSquareCorner (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Photo.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Photo.as index 3ee45b340d..baf3219a87 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Photo.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Photo.as @@ -1,34 +1,34 @@ -package fl.transitions -{ - import flash.display.MovieClip; - import flash.geom.*; - +package fl.transitions +{ + import flash.display.MovieClip; + import flash.geom.*; + /** * Makes the movie clip object appear or disappear like a photographic flash. * This effect requires no additional parameters. *

    For example, the following code uses the Photo transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start (img1_mc, {type:Photo, direction:Transition.IN, duration:1, easing:None.easeNone}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Photo, Transitions * @see fl.transitions.TransitionManager */ - public class Photo extends Transition - { + public class Photo extends Transition + { /** * @private */ - protected var _alphaFinal : Number; + protected var _alphaFinal : Number; /** * @private */ - protected var _colorControl : ColorTransform; - + protected var _colorControl : ColorTransform; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Photo (content:MovieClip, transParams:Object, manager:TransitionManager); + function Photo (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - protected function _render (p:Number) : void; - } -} + protected function _render (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/PixelDissolve.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/PixelDissolve.as index d80e2641bd..ec127b87d9 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/PixelDissolve.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/PixelDissolve.as @@ -1,66 +1,66 @@ -package fl.transitions -{ - import flash.display.MovieClip; - import flash.geom.*; - +package fl.transitions +{ + import flash.display.MovieClip; + import flash.geom.*; + /** * The PixelDissolve class reveals reveals the movie clip object by using randomly appearing or disappearing rectangles * in a checkerboard pattern. This effect requires the following parameters: *
    • xSections: An integer that indicates the number of masking * rectangle sections along the horizontal axis. The recommended range is 1 to 50.
    • *
    • ySections: An integer that indicates the number of masking rectangle * sections along the vertical axis. The recommended range is 1 to 50.
    *

    For example, the following code uses the PixelDissolve transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:PixelDissolve, direction:Transition.IN, duration:2, easing:Regular.easeIn, xSections:10, ySections:10}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword PixelDissolve, Transitions * @see fl.transitions.TransitionManager */ - public class PixelDissolve extends Transition - { + public class PixelDissolve extends Transition + { /** * @private */ - protected var _xSections : Number; + protected var _xSections : Number; /** * @private */ - protected var _ySections : Number; + protected var _ySections : Number; /** * @private */ - protected var _numSections : uint; + protected var _numSections : uint; /** * @private */ - protected var _indices : Array; + protected var _indices : Array; /** * @private */ - protected var _mask : MovieClip; + protected var _mask : MovieClip; /** * @private */ - protected var _innerMask : MovieClip; - + protected var _innerMask : MovieClip; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function PixelDissolve (content:MovieClip, transParams:Object, manager:TransitionManager); + function PixelDissolve (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - public function start () : void; + public function start () : void; /** * @private */ - public function cleanUp () : void; + public function cleanUp () : void; /** * @private */ - protected function _initMask () : void; + protected function _initMask () : void; /** * @private */ - protected function _shuffleArray (a:Array) : void; + protected function _shuffleArray (a:Array) : void; /** * @private */ - protected function _render (p:Number) : void; - } -} + protected function _render (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Rotate.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Rotate.as index 68451246e6..d7eb8d6121 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Rotate.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Rotate.as @@ -1,33 +1,33 @@ -package fl.transitions -{ - import flash.display.*; - +package fl.transitions +{ + import flash.display.*; + /** * The Rotate class rotates the movie clip object. This effect requires the * following parameters: *
    • ccw: A boolean value: false for clockwise rotation; * true for counter-clockwise rotation.
    • *
    • degrees: An integer that indicates the number of degrees the object is to be rotated. The recommended range is 1 to 9999. For example, a degrees setting of 1080 would rotate the object completely three times.
    *

    For example, the following code uses the Rotate transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:Rotate, direction:Transition.IN, duration:3, easing:Strong.easeInOut, ccw:false, degrees:720}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Rotate, Transitions * @see fl.transitions.TransitionManager */ - public class Rotate extends Transition - { + public class Rotate extends Transition + { /** * @private */ - protected var _rotationFinal : Number; + protected var _rotationFinal : Number; /** * @private */ - protected var _degrees : Number; - + protected var _degrees : Number; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Rotate (content:MovieClip, transParams:Object, manager:TransitionManager); + function Rotate (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - protected function _render (p:Number) : void; - } -} + protected function _render (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Squeeze.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Squeeze.as index eeddc1d907..840cf895bf 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Squeeze.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Squeeze.as @@ -1,33 +1,33 @@ -package fl.transitions -{ - import flash.display.MovieClip; - +package fl.transitions +{ + import flash.display.MovieClip; + /** * The Squeeze class scales the movie clip object horizontally or vertically. This effect requires the * following parameters: *
    • dimension: An integer that indicates whether the Squeeze effect should be horizontal (0) or vertical (1).
    *

    For example, the following code uses the Squeeze transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:Squeeze, direction:Transition.IN, duration:2, easing:Elastic.easeOut, dimension:1}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Squeeze, Transitions * @see fl.transitions.TransitionManager */ - public class Squeeze extends Transition - { + public class Squeeze extends Transition + { /** * @private */ - protected var _scaleProp : String; + protected var _scaleProp : String; /** * @private */ - protected var _scaleFinal : Number; - + protected var _scaleFinal : Number; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Squeeze (content:MovieClip, transParams:Object, manager:TransitionManager); + function Squeeze (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - protected function _render (p:Number) : void; - } -} + protected function _render (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Transition.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Transition.as index e8cd4bc4e1..fa63458e57 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Transition.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Transition.as @@ -1,155 +1,155 @@ -package fl.transitions -{ - import flash.events.EventDispatcher; - import flash.display.*; - import flash.geom.*; - import flash.events.Event; - +package fl.transitions +{ + import flash.events.EventDispatcher; + import flash.display.*; + import flash.geom.*; + import flash.events.Event; + /** * The Transition class is the base class for all transition classes. You do not use or access this class directly. It allows transition-based classes to share some common behaviors and properties that are accessed by an instance of the TransitionManager class. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition * @see fl.transitions.TransitionManager * @see fl.transitions.Tween * @see fl.transitions.easing */ - public class Transition extends EventDispatcher - { + public class Transition extends EventDispatcher + { /** * Constant for the direction property that determines the type of easing. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition */ - public static const IN : uint = 0; + public static const IN : uint = 0; /** * Constant for the direction property that determines the type of easing. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition */ - public static const OUT : uint = 1; + public static const OUT : uint = 1; /** * @private */ - public var ID : int; + public var ID : int; /** * @private */ - protected var _content : MovieClip; + protected var _content : MovieClip; /** * @private */ - protected var _manager : TransitionManager; + protected var _manager : TransitionManager; /** * @private */ - protected var _direction : uint; + protected var _direction : uint; /** * @private */ - protected var _duration : Number; + protected var _duration : Number; /** * @private */ - protected var _easing : Function; + protected var _easing : Function; /** * @private */ - protected var _progress : Number; + protected var _progress : Number; /** * @private */ - protected var _innerBounds : Rectangle; + protected var _innerBounds : Rectangle; /** * @private */ - protected var _outerBounds : Rectangle; + protected var _outerBounds : Rectangle; /** * @private */ - protected var _width : Number; + protected var _width : Number; /** * @private */ - protected var _height : Number; + protected var _height : Number; /** * @private */ - protected var _twn : Tween; - + protected var _twn : Tween; + /** * @private */ - public function get type () : Class; + public function get type () : Class; /** * @private */ - public function set manager (mgr:TransitionManager) : void; + public function set manager (mgr:TransitionManager) : void; /** * @private */ - public function get manager () : TransitionManager; + public function get manager () : TransitionManager; /** * @private */ - public function set content (c:MovieClip) : void; + public function set content (c:MovieClip) : void; /** * @private */ - public function get content () : MovieClip; + public function get content () : MovieClip; /** * Determines the easing direction for the Tween instance. Use one of the constants from * the Transition class: Transition.IN or Transition.OUT. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition */ - public function set direction (direction:Number) : void; - public function get direction () : Number; + public function set direction (direction:Number) : void; + public function get direction () : Number; /** * Determines the length of time for the Tween instance. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition */ - public function set duration (d:Number) : void; - public function get duration () : Number; + public function set duration (d:Number) : void; + public function get duration () : Number; /** * Sets the tweening effect for the animation. Use one of the effects in the fl.transitions or * fl.transitions.easing packages. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition */ - public function set easing (e:Function) : void; - public function get easing () : Function; + public function set easing (e:Function) : void; + public function get easing () : Function; /** * @private */ - public function set progress (p:Number) : void; + public function set progress (p:Number) : void; /** * @private */ - public function get progress () : Number; - + public function get progress () : Number; + /** * @private */ - function Transition (content:MovieClip, transParams:Object, manager:TransitionManager); + function Transition (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - public function start () : void; + public function start () : void; /** * @private */ - public function stop () : void; + public function stop () : void; /** * @private remove any movie clips, masks, etc. created by this transition */ - public function cleanUp () : void; + public function cleanUp () : void; /** * @private */ - public function drawBox (mc:MovieClip, x:Number, y:Number, w:Number, h:Number) : void; + public function drawBox (mc:MovieClip, x:Number, y:Number, w:Number, h:Number) : void; /** * @private */ - public function drawCircle (mc:MovieClip, x:Number, y:Number, r:Number) : void; + public function drawCircle (mc:MovieClip, x:Number, y:Number, r:Number) : void; /** * @private abstract method - to be overridden in subclasses */ - protected function _render (p:Number) : void; + protected function _render (p:Number) : void; /** * @private */ - private function _resetTween () : void; + private function _resetTween () : void; /** * @private */ - private function _noEase (t:Number, b:Number, c:Number, d:Number) : Number; + private function _noEase (t:Number, b:Number, c:Number, d:Number) : Number; /** * @private event that comes from an instance of fl.transitions.Tween */ - public function onMotionFinished (src:Object) : void; - } -} + public function onMotionFinished (src:Object) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/TransitionManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/TransitionManager.as index 743b579c4e..d21999330a 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/TransitionManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/TransitionManager.as @@ -1,133 +1,133 @@ -package fl.transitions -{ - import flash.events.EventDispatcher; - import flash.display.*; - import flash.geom.Rectangle; - import flash.events.Event; - +package fl.transitions +{ + import flash.events.EventDispatcher; + import flash.display.*; + import flash.geom.Rectangle; + import flash.events.Event; + /** * The TransitionManager class defines animation effects. It allows you to apply one of ten * animation effects to movie clips. When creating custom components, you can use the * TransitionManager class to apply animation effects to movie clips in your component's * visual interface. The transition effects in fl.transitions.easing are defined as a set of * transition classes that all extend the base class fl.transitions.Transition. You apply * transitions through an instance of a TransitionManager only; you do not instantiate them * directly. The TransitionManager class implements animation events. *

    You can create a TransitionManager instance in two ways:

    *
    • Call the TransitionManager.start() method. This is the simplest and recommended way to create a TransitionManager instance.
    • *
    • Use the new operator. You then designate the transition properties * and start the transition effect in a second step by calling the * TransitionManager.startTransition() method.
    * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition * @see #start() TransitionManager.start() * @see #TransitionManager() TransitionManager constructor function * @see #startTransition() TransitionManager.startTransition() * @see fl.transitions.Tween * @see fl.transitions.easing */ - public class TransitionManager extends EventDispatcher - { + public class TransitionManager extends EventDispatcher + { /** * @private */ - private static var IDCount : int; + private static var IDCount : int; /** * @private */ - public var type : Object; + public var type : Object; /** * @private */ - public var className : String; + public var className : String; /** * @private */ - private var _content : MovieClip; + private var _content : MovieClip; /** * @private */ - private var _transitions : Object; + private var _transitions : Object; /** * @private */ - public var _innerBounds : Rectangle; + public var _innerBounds : Rectangle; /** * @private */ - public var _outerBounds : Rectangle; + public var _outerBounds : Rectangle; /** * @private */ - public var _width : Number; + public var _width : Number; /** * @private */ - public var _height : Number; + public var _height : Number; /** * @private */ - private var _contentAppearance : Object; + private var _contentAppearance : Object; /** * @private */ - private var _visualPropList : Object; + private var _visualPropList : Object; /** * @private */ - private var _triggerEvent : String; - + private var _triggerEvent : String; + /** * The movie clip instance to which TransitionManager is to apply a transition. * @playerversion Flash 9 * @langversion 3.0 * @keyword content, Transition */ - public function set content (c:MovieClip) : void; - public function get content () : MovieClip; + public function set content (c:MovieClip) : void; + public function get content () : MovieClip; /** * @private this was changed from get transitions() to get transitionsList() because hitting compile error */ - public function get transitionsList () : Object; + public function get transitionsList () : Object; /** * @private */ - public function get numTransitions () : Number; + public function get numTransitions () : Number; /** * @private */ - public function get numInTransitions () : Number; + public function get numInTransitions () : Number; /** * @private */ - public function get numOutTransitions () : Number; + public function get numOutTransitions () : Number; /** * An object that contains the saved visual properties of the content (target movie clip) * to which the transitions will be applied. * @playerversion Flash 9 * @langversion 3.0 * @keyword contentAppearance, Transition */ - public function get contentAppearance () : Object; - + public function get contentAppearance () : Object; + /** * Creates a new TransitionManager instance, designates the target object, applies a transition, and starts the transition. Specifically, calling this method creates an instance of the TransitionManager class if one does not already exist, creates an instance of the specified transition class designated in the transParams parameter, and then starts the transition. The transition is applied to the movie clip that is designated in the content parameter. *

    For example:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(myMovieClip, {type:Zoom, direction:Transition.IN, duration:1, easing:Bounce.easeOut}); * * @param content The MovieClip object to which to apply the transition effect. * @param transParams A collection of parameters that are passed within an object. The * transParams object should contain a type parameter that indicates * the transition effect class to be applied, followed by direction, duration, * and easing parameters. In addition, you must include any parameters required by that * transition effect class. For example, the fl.transitions.Iris transition effect class requires additional * startPoint and shape parameters. So, in addition to the * type, duration, and easing parameters that every * transition requires, you would also add (to the transParams object) the * startPoint and shape parameters that the fl.transitions.Iris * effect requires. * @return The Transition instance. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition */ - public static function start (content:MovieClip, transParams:Object) : Transition; + public static function start (content:MovieClip, transParams:Object) : Transition; /** * Constructor function for creating a new TransitionManager instance. However, the TransitionManager.start() method is a more efficient way of creating and implementing a TransitionManager instance. If you do use the TransitionManager constructor function to create an instance, use the new operator then designate the transition properties and start the transition effect in a second step by calling the TransitionManager.startTransition() method. *

    For example:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * var myTransitionManager:TransitionManager = new TransitionManager(myMovieClip); * myTransitionManager.startTransition({type:Zoom, direction:Transition.IN, duration:1, easing:Bounce.easeOut}); * * @param content The MovieClip object to which to apply the transition effect. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition * @see #start() TransitionManager.start() * @see #startTransition() TransitionManager.startTransition() */ - function TransitionManager (content:MovieClip); + function TransitionManager (content:MovieClip); /** * Creates a transition instance and starts it. If a matching transition already exists, * the existing transition is removed and a new transition is created and started. This method * is used in conjunction with the constructor function. *

    For example:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * var myTransitionManager:TransitionManager = new TransitionManager(myMovieClip); * myTransitionManager.startTransition({type:Zoom, direction:Transition.IN, duration:1, easing:Bounce.easeOut}); * *

    Alternatively, you can use the TransitionManager.start() method, which is * a more efficient way of implementing a transition effect.

    * @param transParams A collection of parameters that are passed within an object. The * transParams object should contain a type parameter that indicates * the transition effect class to be applied, followed by direction, duration, and easing * parameters. In addition, you must include any parameters required by that transition effect * class. For example, the fl.transitions.Iris transition effect class requires additional * startPoint and shape parameters. So, in addition to the * type, duration, and easing parameters that every * transition requires, you would also add (to the transParams object) the * startPoint and shape parameters that the fl.transitions.Iris * effect requires. * @return The Transition instance. * @playerversion Flash 9 * @langversion 3.0 * @keyword Transition * @see #start() TransitionManager.start() * @see #TransitionManager() TransitionManager constructor function */ - public function startTransition (transParams:Object) : Transition; + public function startTransition (transParams:Object) : Transition; /** * @private */ - public function addTransition (trans:Transition) : Transition; + public function addTransition (trans:Transition) : Transition; /** * @private */ - public function removeTransition (trans:Transition) : Boolean; + public function removeTransition (trans:Transition) : Boolean; /** * @private */ - public function findTransition (transParams:Object) : Transition; + public function findTransition (transParams:Object) : Transition; /** * @private */ - public function removeAllTransitions () : void; + public function removeAllTransitions () : void; /** * @private */ - public function saveContentAppearance () : void; + public function saveContentAppearance () : void; /** * @private */ - public function restoreContentAppearance () : void; + public function restoreContentAppearance () : void; /** * @private */ - function transitionInDone (e:Object) : void; + function transitionInDone (e:Object) : void; /** * @private */ - function transitionOutDone (e:Object) : void; - } -} + function transitionOutDone (e:Object) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Tween.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Tween.as index 70a71ad152..ff1dde0ee4 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Tween.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Tween.as @@ -1,228 +1,228 @@ -package fl.transitions -{ - import flash.events.*; - import flash.display.*; - import flash.utils.*; - +package fl.transitions +{ + import flash.events.*; + import flash.display.*; + import flash.utils.*; + /** * @eventType fl.transitions.TweenEvent.MOTION_CHANGE * * @playerversion Flash 9 * @langversion 3.0 */ - [Event(name="motionChange", type="fl.transitions.TweenEvent")] + [Event(name="motionChange", type="fl.transitions.TweenEvent")] /** * @eventType fl.transitions.TweenEvent.MOTION_FINISH * * @playerversion Flash 9 * @langversion 3.0 */ - [Event(name="motionFinish", type="fl.transitions.TweenEvent")] + [Event(name="motionFinish", type="fl.transitions.TweenEvent")] /** * @eventType fl.transitions.TweenEvent.MOTION_LOOP * * @playerversion Flash 9 * @langversion 3.0 */ - [Event(name="motionLoop", type="fl.transitions.TweenEvent")] + [Event(name="motionLoop", type="fl.transitions.TweenEvent")] /** * @eventType fl.transitions.TweenEvent.MOTION_RESUME * * @playerversion Flash 9 * @langversion 3.0 */ - [Event(name="motionResume", type="fl.transitions.TweenEvent")] + [Event(name="motionResume", type="fl.transitions.TweenEvent")] /** * @eventType fl.transitions.TweenEvent.MOTION_START * * @playerversion Flash 9 * @langversion 3.0 */ - [Event(name="motionStart", type="fl.transitions.TweenEvent")] + [Event(name="motionStart", type="fl.transitions.TweenEvent")] /** * @eventType fl.transitions.TweenEvent.MOTION_STOP * * @playerversion Flash 9 * @langversion 3.0 */ - [Event(name="motionStop", type="fl.transitions.TweenEvent")] - + [Event(name="motionStop", type="fl.transitions.TweenEvent")] + /** * The Tween class lets you use ActionScript to move, resize, and fade movie clips * by specifying a property of the target movie clip to animate over a number * of frames or seconds. * *

    The Tween class also lets you specify a variety of easing methods. "Easing" refers to * gradual acceleration or deceleration during an animation, which helps your animations appear * more realistic. The fl.transitions.easing package provides many easing methods that contain * equations for this acceleration and deceleration, which change the easing animation * accordingly.

    * *

    To use the methods and properties of the Tween class, you use the new * operator with the constructor function to create an instance of the class, and you specify an easing * method as a parameter. For example:

    * * import fl.transitions.Tween; * import fl.transitions.easing.~~; * var myTween:Tween = new Tween(myObject, "x", Elastic.easeOut, 0, 300, 3, true); * * * @keyword Tween, Transition * * @see fl.transitions.TransitionManager * @see fl.transitions.easing * @see #Tween() * * @playerversion Flash 9 * @langversion 3.0 */ - public class Tween extends EventDispatcher - { + public class Tween extends EventDispatcher + { /** * @private */ - protected static var _mc : MovieClip; + protected static var _mc : MovieClip; /** * Indicates whether the tween is currently playing. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public var isPlaying : Boolean; + public var isPlaying : Boolean; /** * The target object that is being tweened. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public var obj : Object; + public var obj : Object; /** * The name of the property affected by the tween of the target object. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public var prop : String; + public var prop : String; /** * The initial value of the target object's designated property before the tween starts. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public var begin : Number; + public var begin : Number; /** * @private */ - public var change : Number; + public var change : Number; /** * Indicates whether the tween plays over a period of frames or seconds. A value of true will * cause the tween to animate over a period of seconds specified by the duration property. A * value of false will cause the tween to animate over a period of frames. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public var useSeconds : Boolean; + public var useSeconds : Boolean; /** * @private */ - public var prevTime : Number; + public var prevTime : Number; /** * @private */ - public var prevPos : Number; + public var prevPos : Number; /** * Indicates whether the tween will loop. If the value is true, the tween will restart * indefinitely each time the tween has completed. If the value is false, the tween * will play only once. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public var looping : Boolean; + public var looping : Boolean; /** * @private */ - private var _duration : Number; + private var _duration : Number; /** * @private */ - private var _time : Number; + private var _time : Number; /** * @private */ - private var _fps : Number; + private var _fps : Number; /** * @private */ - private var _position : Number; + private var _position : Number; /** * @private */ - private var _startTime : Number; + private var _startTime : Number; /** * @private */ - private var _intervalID : uint; + private var _intervalID : uint; /** * @private */ - private var _finish : Number; + private var _finish : Number; /** * @private */ - private var _timer : Timer; - + private var _timer : Timer; + /** * The current time within the duration of the animation. * * @param t The current number of seconds that have passed within the duration of the * animation if the useSeconds parameter was set to true when * creating the Tween instance. If the useSeconds parameter of the animation * was set to false, Tween.time returns the current number of * frames that have passed in the Tween object animation. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function get time () : Number; + public function get time () : Number; /** * @private (setter) */ - public function set time (t:Number) : void; + public function set time (t:Number) : void; /** * The duration of the tweened animation in frames or seconds. This property is set as * a parameter when creating a new Tween instance or when calling the * Tween.yoyo() method. * * @param d A number indicating the duration of the tweened animation in frames or seconds. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function get duration () : Number; + public function get duration () : Number; /** * @private (setter) */ - public function set duration (d:Number) : void; + public function set duration (d:Number) : void; /** * The number of frames per second calculated into the tweened animation. By default the * current Stage frame rate is used to calculate the tweened animation. Setting this property * recalculates the number of increments in the animated property that is displayed each second * to the Tween.FPS property rather than the current Stage frame rate. Setting the * Tween.FPS property does not change the actual frame rate of the Stage. *

    Note: The Tween.FPS property returns undefined unless it * is first set explicitly.

    * * @param fps The number of frames per second of the tweened animation. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function get FPS () : Number; + public function get FPS () : Number; /** * @private (setter) */ - public function set FPS (fps:Number) : void; + public function set FPS (fps:Number) : void; /** * The current value of the target object property being tweened. This value updates * with each drawn frame of the tweened animation. * * @param p The current value of the target movie clip's property being tweened. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function get position () : Number; + public function get position () : Number; /** * @private (setter) */ - public function set position (p:Number) : void; + public function set position (p:Number) : void; /** * A number indicating the ending value of the target object property that is to be tweened. * This property is set as a parameter when creating a new Tween instance or when calling the * Tween.yoyo() method. * * @keyword Tween * * @see #yoyo() * * @playerversion Flash 9 * @langversion 3.0 */ - public function get finish () : Number; + public function get finish () : Number; /** * @private (setter) */ - public function set finish (value:Number) : void; - + public function set finish (value:Number) : void; + /** * The easing function which is used with the tween. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function func (t:Number, b:Number, c:Number, d:Number) : Number; + public function func (t:Number, b:Number, c:Number, d:Number) : Number; /** * @private */ - public function getPosition (t:Number = NaN) : Number; + public function getPosition (t:Number = NaN) : Number; /** * @private */ - public function setPosition (p:Number) : void; + public function setPosition (p:Number) : void; /** * Creates an instance of the Tween class. Use the constructor function with the new operator: var myTween:Tween = new Tween(). * * @param obj Object that the Tween targets. * @param prop Name of the property (obj parameter value) that will be affected. * @param func Name of the easing function to use. * @param begin Starting value of the prop parameter. * @param finish A number indicating the ending value of prop parameter (the target object property to be tweened). * @param duration Length of time of the motion; set to infinity if negative or omitted. * @param useSeconds A flag specifying whether to use seconds instead of frames. The function uses seconds if true or frames in relation to the value specified in the duration parameter if false. * * @keyword Transitions * * @see fl.transitions.easing * * @playerversion Flash 9 * @langversion 3.0 */ - function Tween (obj:Object, prop:String, func:Function, begin:Number, finish:Number, duration:Number, useSeconds:Boolean = false); + function Tween (obj:Object, prop:String, func:Function, begin:Number, finish:Number, duration:Number, useSeconds:Boolean = false); /** * Instructs the tweened animation to continue tweening from its current animation point to * a new finish and duration point. * * @param finish A number indicating the ending value of the target object property that is * to be tweened. * * @param duration A number indicating the length of time or number of frames for the tween * motion; duration is measured in length of time if the Tween.start() * useSeconds parameter is set to true, or measured in frames if * it is set to false. * * @keyword Tween * * @see #start() * * @playerversion Flash 9 * @langversion 3.0 */ - public function continueTo (finish:Number, duration:Number) : void; + public function continueTo (finish:Number, duration:Number) : void; /** * Instructs the tweened animation to play in reverse from its last direction of tweened * property increments. If this method is called before a Tween object's animation is complete, * the animation abruptly jumps to the end of its play and then plays in a reverse direction * from that point. You can achieve an effect of an animation completing its entire play and * then reversing its entire play by calling the Tween.yoyo() method within a * TweenEvent.MOTION_FINISH event handler. This process ensures that the reverse * effect of the Tween.yoyo() method does not begin until the current tweened * animation is complete. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function yoyo () : void; + public function yoyo () : void; /** * @private */ - protected function startEnterFrame () : void; + protected function startEnterFrame () : void; /** * @private */ - protected function stopEnterFrame () : void; + protected function stopEnterFrame () : void; /** * Starts the play of a tweened animation from its starting point. This method is used for * restarting a Tween from the beginning of its animation after it stops or has completed * its animation. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function start () : void; + public function start () : void; /** * Stops the play of a tweened animation at its current value. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function stop () : void; + public function stop () : void; /** * Resumes the play of a tweened animation that has been stopped. Use this method to continue * a tweened animation after you have stopped it by using the Tween.stop() method. * *

    Note: Use this method on frame-based tweens only. A tween is set * to be frame based at its creation by setting the useSeconds parameter to false.

    * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function resume () : void; + public function resume () : void; /** * Moves the play of a tweened animation back to its starting value. If * Tween.rewind() is called while the tweened animation is still playing, the * animation rewinds to its starting value and continues playing. If * Tween.rewind() is called while the tweened animation has been stopped or has * finished its animation, the tweened animation rewinds to its starting value and remains * stopped. Use this method to rewind a tweened animation to its starting point after you have * stopped it by using the Tween.stop() method or to rewind a tweened animation * during its play. * * @param t Starting value. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function rewind (t:Number = 0) : void; + public function rewind (t:Number = 0) : void; /** * Forwards the tweened animation directly to the final value of the tweened animation. * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function fforward () : void; + public function fforward () : void; /** * Forwards the tweened animation to the next frame of an animation that was stopped. Use this * method to forward a frame at a time of a tweened animation after you use the * Tween.stop() method to stop it. * *

    Note: Use this method on frame-based tweens only. A tween is * set to frame based at its creation by setting the useSeconds parameter to * false.

    * * @keyword Tween * * @playerversion Flash 9 * @langversion 3.0 */ - public function nextFrame () : void; + public function nextFrame () : void; /** * @private */ - protected function onEnterFrame (event:Event) : void; + protected function onEnterFrame (event:Event) : void; /** * @private */ - protected function timerHandler (timerEvent:TimerEvent) : void; + protected function timerHandler (timerEvent:TimerEvent) : void; /** * Plays the previous frame of the tweened animation from the current stopping point of an * animation that was stopped. Use this method to play a tweened animation backwards one frame * at a time after you use the Tween.stop() method to stop it. * *

    Note: Use this method on frame-based tweens only. A tween is set * to frame based at its creation by setting the Tween.start() * useSeconds parameter to false.

    * * @keyword Tween * * @see #start() * * @playerversion Flash 9 * @langversion 3.0 */ - public function prevFrame () : void; + public function prevFrame () : void; /** * @private */ - private function fixTime () : void; + private function fixTime () : void; /** * @private */ - private function update () : void; - } -} + private function update () : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/TweenEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/TweenEvent.as index 05c2467743..a8ad921a02 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/TweenEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/TweenEvent.as @@ -1,52 +1,52 @@ -package fl.transitions -{ - import flash.events.Event; - +package fl.transitions +{ + import flash.events.Event; + /** * The TweenEvent class represents events that are broadcast by the fl.transitions.Tween class. * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event * @see fl.transitions.Tween */ - public class TweenEvent extends Event - { + public class TweenEvent extends Event + { /** * Indicates that the motion has started playing. *

    The properties of the event object have the following values:

    * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget property.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    timeThe time of the Tween when the event occurred.
    positionThe value of the property controlled by the Tween, when the event occurred.
    * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event * @eventType motionStart */ - public static const MOTION_START : String = 'motionStart'; + public static const MOTION_START : String = 'motionStart'; /** * Indicates that the Tween has been stopped * with an explicit call to Tween.stop(). *

    The properties of the event object have the following values:

    * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget property.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    timeThe time of the Tween when the event occurred.
    positionThe value of the property controlled by the Tween, when the event occurred.
    * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event * @eventType motionStop */ - public static const MOTION_STOP : String = 'motionStop'; + public static const MOTION_STOP : String = 'motionStop'; /** * Indicates that the Tween has reached the end and finished. *

    The properties of the event object have the following values:

    * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget property.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    timeThe time of the Tween when the event occurred.
    positionThe value of the property controlled by the Tween, when the event occurred.
    * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event * @eventType motionFinish */ - public static const MOTION_FINISH : String = 'motionFinish'; + public static const MOTION_FINISH : String = 'motionFinish'; /** * Indicates that the Tween has changed and the screen has been updated. *

    The properties of the event object have the following values:

    * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget property.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    timeThe time of the Tween when the event occurred.
    positionThe value of the property controlled by the Tween, when the event occurred.
    * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event * @eventType motionChange */ - public static const MOTION_CHANGE : String = 'motionChange'; + public static const MOTION_CHANGE : String = 'motionChange'; /** * Indicates that the Tween has resumed playing after being paused. *

    The properties of the event object have the following values:

    * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget property.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    timeThe time of the Tween when the event occurred.
    positionThe value of the property controlled by the Tween, when the event occurred.
    * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event * @eventType motionResume */ - public static const MOTION_RESUME : String = 'motionResume'; + public static const MOTION_RESUME : String = 'motionResume'; /** * Indicates that the Tween has restarted playing from the beginning in looping mode. *

    The properties of the event object have the following values:

    * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse
    currentTargetThe object that defines the * event listener that handles the event. For example, if you use * myButton.addEventListener() to register an event listener, * myButton is the value of the currentTarget property.
    targetThe object that dispatched the event; * it is not always the object listening for the event. * Use the currentTarget property to always access the * object listening for the event.
    timeThe time of the Tween when the event occurred.
    positionThe value of the property controlled by the Tween, when the event occurred.
    * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event * @eventType motionLoop */ - public static const MOTION_LOOP : String = 'motionLoop'; + public static const MOTION_LOOP : String = 'motionLoop'; /** * The time of the Tween when the event occurred. * * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event */ - public var time : Number; + public var time : Number; /** * The value of the property controlled by the Tween, when the event occurred. * * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event */ - public var position : Number; - + public var position : Number; + /** * Constructor function for a TweenEvent object. * * @param type The event type; indicates the action that caused the event. * @param time The time within the duration of the animation. * @param position The frame of the tween. * @param bubbles Specifies whether the event can bubble up the display list hierarchy. * @param cancelable Specifies whether the behavior associated with the event can be prevented. * * @playerversion Flash 9 * @langversion 3.0 * @keyword Tween event */ - public function TweenEvent (type:String, time:Number, position:Number, bubbles:Boolean = false, cancelable:Boolean = false); + public function TweenEvent (type:String, time:Number, position:Number, bubbles:Boolean = false, cancelable:Boolean = false); /** * @private */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Wipe.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Wipe.as index 9d57cad926..49b5150e68 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Wipe.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Wipe.as @@ -1,58 +1,58 @@ -package fl.transitions -{ - import flash.display.MovieClip; - import flash.geom.*; - +package fl.transitions +{ + import flash.display.MovieClip; + import flash.geom.*; + /** * The Wipe class reveals or hides the movie clip object by using an animated mask of a shape that moves * horizontally. This effect requires the * following parameter: *
    • startPoint: An integer indicating a starting position; the range * is 1 to 9: Top Left:1; Top Center:2, Top Right:3; Left Center:4; Center:5; Right Center:6; Bottom Left:7; Bottom Center:8, Bottom Right:9.
    *

    For example, the following code uses the Wipe transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:Wipe, direction:Transition.IN, duration:2, easing:None.easeNone, startPoint:1}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Wipe, Transitions * @see fl.transitions.TransitionManager */ - public class Wipe extends Transition - { + public class Wipe extends Transition + { /** * @private */ - protected var _mask : MovieClip; + protected var _mask : MovieClip; /** * @private */ - protected var _innerMask : MovieClip; + protected var _innerMask : MovieClip; /** * @private */ - protected var _startPoint : uint; + protected var _startPoint : uint; /** * @private */ - protected var _cornerMode : Boolean; - + protected var _cornerMode : Boolean; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Wipe (content:MovieClip, transParams:Object, manager:TransitionManager); + function Wipe (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - public function start () : void; + public function start () : void; /** * @private */ - public function cleanUp () : void; + public function cleanUp () : void; /** * @private */ - protected function _initMask () : void; + protected function _initMask () : void; /** * @private */ - protected function _render (p:Number) : void; + protected function _render (p:Number) : void; /** * @private */ - protected function _drawSlant (mc:MovieClip, p:Number) : void; - } -} + protected function _drawSlant (mc:MovieClip, p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Zoom.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Zoom.as index 2505e390bf..22e864a64c 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Zoom.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/Zoom.as @@ -1,33 +1,33 @@ -package fl.transitions -{ - import flash.display.MovieClip; - +package fl.transitions +{ + import flash.display.MovieClip; + /** * The Zoom class zooms the movie clip object in or out by scaling it in proportion. * This effect requires no additional parameters: *

    For example, the following code uses the Zoom transition for the movie clip * instance img1_mc:

    * * import fl.transitions.~~; * import fl.transitions.easing.~~; * * TransitionManager.start(img1_mc, {type:Zoom, direction:Transition.IN, duration:2, easing:Elastic.easeOut}); * * @playerversion Flash 9 * @langversion 3.0 * @keyword Zoom, Transitions * @see fl.transitions.TransitionManager */ - public class Zoom extends Transition - { + public class Zoom extends Transition + { /** * @private */ - protected var _scaleXFinal : Number; + protected var _scaleXFinal : Number; /** * @private */ - protected var _scaleYFinal : Number; - + protected var _scaleYFinal : Number; + /** * @private */ - public function get type () : Class; - + public function get type () : Class; + /** * @private */ - function Zoom (content:MovieClip, transParams:Object, manager:TransitionManager); + function Zoom (content:MovieClip, transParams:Object, manager:TransitionManager); /** * @private */ - protected function _render (p:Number) : void; - } -} + protected function _render (p:Number) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Back.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Back.as index b7d1658c19..0d6336ac02 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Back.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Back.as @@ -1,21 +1,21 @@ -package fl.transitions.easing -{ +package fl.transitions.easing +{ /** * The Back class defines three easing functions to implement * motion with ActionScript animations. * * @see fl.transitions.TransitionManager * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition */ - public class Back - { + public class Back + { /** * The easeIn() method starts the motion by backtracking and * then reversing direction and moving toward the target. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param s Specifies the amount of overshoot, where the higher the value, * the greater the overshoot. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Back.easeIn.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transitions */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; /** * The easeOut() method starts the motion by * moving towards the target, overshooting it slightly, * and then reversing direction back toward the target. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param s Specifies the amount of overshoot, where the higher the value, * the greater the overshoot. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Back.easeOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transitions */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion by backtracking, then reversing direction and * moving toward the target, overshooting the target slightly, reversing * direction again, and then moving back toward the target. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param s Specifies the amount of overshoot, where the higher the value, * the greater the overshoot. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Back.easeInOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transitions */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number, s:Number = 0) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Bounce.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Bounce.as index 4b636e5226..f0de88e15e 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Bounce.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Bounce.as @@ -1,21 +1,21 @@ -package fl.transitions.easing -{ +package fl.transitions.easing +{ /** * The Bounce class defines three easing functions to implement * bouncing motion with ActionScript animation, similar to a ball * falling and bouncing on a floor with several decaying rebounds. * * @see fl.transitions.TransitionManager * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition */ - public class Bounce - { + public class Bounce + { /** * The easeOut() method starts the bounce motion fast * and then decelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Bounce.easeOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeIn() method starts the bounce motion slowly * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Bounce.easeIn.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the bounce motion slowly, accelerate motion, then decelerate. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Bounce.easeInOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Elastic.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Elastic.as index b5538eeae8..ea0cdf027a 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Elastic.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Elastic.as @@ -1,21 +1,21 @@ -package fl.transitions.easing -{ +package fl.transitions.easing +{ /** * The Elastic class defines three easing functions to implement * motion with ActionScript animation, where the motion is defined by * an exponentially decaying sine wave. * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public class Elastic - { + public class Elastic + { /** * The easeIn() method starts motion slowly * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param a Specifies the amplitude of the sine wave. * * @param p Specifies the period of the sine wave. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Elastic.easeIn.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param a Specifies the amplitude of the sine wave. * * @param p Specifies the period of the sine wave. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Elastic.easeOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion slowly, accelerate motion, then decelerate. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @param a Specifies the amplitude of the sine wave. * * @param p Specifies the period of the sine wave. * * @return The value of the interpolated property at the specified time. * * @see fl.transitions.TransitionManager * * @includeExample examples/Elastic.easeInOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number, a:Number = 0, p:Number = 0) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/None.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/None.as index f6a66497ca..3b050149a8 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/None.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/None.as @@ -1,25 +1,25 @@ -package fl.transitions.easing -{ +package fl.transitions.easing +{ /** * The None class defines easing functions to implement * nonaccelerated motion with ActionScript animations. * Its methods all produce the same effect, a constant motion. * The various names, easeIn, easeOut and so on * are provided in the interest of polymorphism. * The None class is identical to the fl.motion.easing.Linear class in functionality. * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public class None - { + public class None + { /** * The easeNone() method defines a constant motion, * with no acceleration. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeNone (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeNone (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeIn() method defines a constant motion, * with no acceleration. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/None.easeIn.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method defines a constant motion, * with no acceleration. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/None.easeOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method defines a constant motion, * with no acceleration. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/None.easeInOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Regular.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Regular.as index cf6ceb7a9d..d21469c10c 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Regular.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Regular.as @@ -1,21 +1,21 @@ -package fl.transitions.easing -{ +package fl.transitions.easing +{ /** * The Regular class defines three easing functions to implement * accelerated motion with ActionScript animations. The acceleration of motion * for a Regular easing equation is the same as for a timeline tween at 100% easing * and is less dramatic than for the Strong easing equation. * The Regular class is identical to the fl.motion.easing.Quadratic class in functionality. * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public class Regular - { + public class Regular + { /** * The easeIn() method starts motion from a zero velocity * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Regular.easeIn.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Regular.easeOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, * accelerate motion, then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Regular.easeInOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Strong.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Strong.as index 99b6e64dd9..2ef99f68bd 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Strong.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/transitions/easing/Strong.as @@ -1,21 +1,21 @@ -package fl.transitions.easing -{ +package fl.transitions.easing +{ /** * The Strong class defines three easing functions to implement * motion with ActionScript animation. The acceleration of motion for a Strong easing * equation is greater than for a Regular easing equation. * The Strong class is identical to the fl.motion.easing.Quintic class in functionality. * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public class Strong - { + public class Strong + { /** * The easeIn() method starts motion from zero velocity * and then accelerates motion as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Strong.easeIn.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeIn (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeOut() method starts motion fast * and then decelerates motion to a zero velocity as it executes. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Strong.easeOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; + public static function easeOut (t:Number, b:Number, c:Number, d:Number) : Number; /** * The easeInOut() method combines the motion * of the easeIn() and easeOut() methods * to start the motion from a zero velocity, accelerate motion, * then decelerate to a zero velocity. * * @param t Specifies the current time, between 0 and duration inclusive. * * @param b Specifies the initial value of the animation property. * * @param c Specifies the total change in the animation property. * * @param d Specifies the duration of the motion. * * @return The value of the interpolated property at the specified time. * * @includeExample examples/Strong.easeInOut.1.as -noswf * * @playerversion Flash 9.0 * @langversion 3.0 * @keyword Ease, Transition * @see fl.transitions.TransitionManager */ - public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; - } -} + public static function easeInOut (t:Number, b:Number, c:Number, d:Number) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/AutoLayoutEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/AutoLayoutEvent.as index 2fc7e2137d..156f7010cc 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/AutoLayoutEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/AutoLayoutEvent.as @@ -1,35 +1,35 @@ -package fl.video -{ - import flash.events.Event; - import flash.geom.Rectangle; - +package fl.video +{ + import flash.events.Event; + import flash.geom.Rectangle; + /** * Flash® Player dispatches an AutoLayoutEvent object when the video player is resized * and laid out automatically. A video player is * laid out automatically when the * maintainAspectRatio property or autoSize property is set to * true or when a new FLV file is loaded. * *

    There is only one type of AutoLayoutEvent object: * AutoLayoutEvent.AUTO_LAYOUT.

    * *

    After an attempt to automatically lay out a video player * occurs, the event object is dispatched even if the dimensions were * not changed.

    * *

    A LayoutEvent object is also dispatched in these three scenarios:

    *
      *
    • If the video player that laid itself out is visible.
    • *
    • If there are two video players of different sizes or positions and the * visibleVideoPlayerIndex property is switched from one video player to another.
    • *
    • If methods or properties that change the size or location of the video player, such * as setSize(), setScale(), * width, height, scaleX, scaleY, * registrationWidth, and registrationHeight, are called.
    • *
    * *

    If multiple video player instances are in use, this event may * not apply to the visible video player.

    * * @see #AUTO_LAYOUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class AutoLayoutEvent extends LayoutEvent implements IVPEvent - { + public class AutoLayoutEvent extends LayoutEvent implements IVPEvent + { /** * Defines the value of the * type property of an * autoLayout event object. * *

    This event has the following properties:

    * * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default behavior to cancel.
    oldBoundsThe values of the x, y, * width, and height properties of the target before the autoLayout event occurs.
    oldRegistrationBoundsThe values of the registrationX, * registrationY, registrationWidth, and * registrationHeight properties of the target before the autoLayout event occurs.
    vpThe index of the VideoPlayer object.
    * * @eventType autoLayout * @see FLVPlayback#event:autoLayout * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const AUTO_LAYOUT : String = "autoLayout"; - private var _vp : uint; - + public static const AUTO_LAYOUT : String = "autoLayout"; + private var _vp : uint; + /** * The index of the VideoPlayer object involved in this event. * * @see FLVPlayback#activeVideoPlayerIndex * @see FLVPlayback#visibleVideoPlayerIndex * @see FLVPlayback#getVideoPlayer() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get vp () : uint; + public function get vp () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set vp (n:uint) : void; - + public function set vp (n:uint) : void; + /** * Creates an Event object that contains information about autoLayout events. * Event objects are passed as parameters to event listeners. * * @param type The type of the event. Event listeners can access this information * through the inherited type property. There is only one type of * auto layout event: AutoLayoutEvent.AUTO_LAYOUT. * * @param bubbles Determines whether the Event object participates in the bubbling * stage of the event flow. Event listeners can access this information through * the inherited bubbles property. * * @param cancelable Determines whether the Event object can be canceled. Event listeners * can access this information through the inherited cancelable property. * * @param oldBounds Indicates the values of the x, y, * width, and height properties of * the target before the autoLayout event occurs. Event listeners can access this information through * the LayoutEvent.oldBounds property. * * @param oldRegistrationBounds Indicates the values of the registrationX, * registrationY, registrationWidth, and * registrationHeight properties of the target before the autoLayout event occurs. * Event listeners can access this information through * the LayoutEvent.oldRegistrationBounds property. * * @param vp The index of the VideoPlayer object involved in this event. * * @see LayoutEvent#oldBounds * @see LayoutEvent#oldRegistrationBounds * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function AutoLayoutEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, oldBounds:Rectangle = null, oldRegistrationBounds:Rectangle = null, vp:uint = 0); + public function AutoLayoutEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, oldBounds:Rectangle = null, oldRegistrationBounds:Rectangle = null, vp:uint = 0); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CaptionChangeEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CaptionChangeEvent.as index fe0aca9209..0346bed7f5 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CaptionChangeEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CaptionChangeEvent.as @@ -1,43 +1,43 @@ -package fl.video -{ - import flash.events.Event; - +package fl.video +{ + import flash.events.Event; + /** * The CaptionChangeEvent is dispatched any time a caption is added or removed from the caption target text field. * *

    The event is also dispatched when the following conditions are true:

    *
      *
    • the captionTargetName property is not set
    • *
    • the captionTarget property is not set
    • *
    • the FLVPlaybackCaptioning instance creates a TextField object automatically for captioning.
    • *
    * * @tiptext CaptionChangeEvent class * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class CaptionChangeEvent extends Event - { + public class CaptionChangeEvent extends Event + { /** * Defines the value of the * type property of a captionChange event object. * *

    This event has the following properties:

    * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default behavior to cancel.
    addedA Boolean that indicates whether the caption was added or removed from the display.
    captionCuePointObjectThe cue point object for this caption.
    * @eventType captionChange * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const CAPTION_CHANGE : String = "captionChange"; - private var _added : Boolean; - private var _captionCuePointObject : Object; - + public static const CAPTION_CHANGE : String = "captionChange"; + private var _added : Boolean; + private var _captionCuePointObject : Object; + /** * A Boolean value that determines whether the caption was added or removed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get added () : Boolean; + public function get added () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set added (b:Boolean) : void; + public function set added (b:Boolean) : void; /** * The cue point object for the caption that was added or removed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get captionCuePointObject () : Object; + public function get captionCuePointObject () : Object; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set captionCuePointObject (o:Object) : void; - + public function set captionCuePointObject (o:Object) : void; + /** * Creates an Event object that contains information about captionChange events. * Event objects are passed as parameters to event listeners. * * @param type The type of the event. Event listeners can access this information * through the inherited type property. There is only one type of * captionChange event: CaptionChangeEvent.CAPTION_CHANGE. * * @param bubbles Determines whether the Event object participates in the bubbling * stage of the event flow. Event listeners can access this information through the * inherited bubbles property. * * @param cancelable Determines whether the Event object can be canceled. Event listeners can * access this information through the inherited cancelable property. * * @param added A Boolean value that indicates whether the caption was added or removed from the * display. * * @param captionCuePointObject The cue point object for this caption. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function CaptionChangeEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, added:Boolean = true, captionCuePointObject:Object = null); + public function CaptionChangeEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, added:Boolean = true, captionCuePointObject:Object = null); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CaptionTargetEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CaptionTargetEvent.as index d1a30144d1..aae5b48355 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CaptionTargetEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CaptionTargetEvent.as @@ -1,35 +1,35 @@ -package fl.video -{ - import flash.display.DisplayObject; - import flash.events.Event; - +package fl.video +{ + import flash.display.DisplayObject; + import flash.events.Event; + /** * Type for the captionTargetCreated event, dispatched after the * captionTargetCreated event is created automatically and before any captions * have been added to it. This event is not dispatched if the * captionTarget property is set with a custom display object, or * if the captionTargetName property is set. This is useful for * customizing the properties of the TextField object, such as the * defaultTextFormat property. * * @tiptext CaptionTargetEvent class * @see flash.text.TextField#defaultTextFormat * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class CaptionTargetEvent extends Event - { + public class CaptionTargetEvent extends Event + { /** * The CaptionTargetEvent.CAPTION_TARGET_CREATED constant defines the value of the * type property of a captionTargetCreated event object. * *

    This event has the following properties:

    * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default behavior to cancel.
    captionTargetA display object that is from the captionTarget * property of the FLVPlaybackCaptioning instance.
    * @eventType captionTargetCreated * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const CAPTION_TARGET_CREATED : String = "captionTargetCreated"; - private var _captionTarget : DisplayObject; - + public static const CAPTION_TARGET_CREATED : String = "captionTargetCreated"; + private var _captionTarget : DisplayObject; + /** * The caption target from the FLVPlaybackCaptioning instance property of the * same name. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get captionTarget () : DisplayObject; + public function get captionTarget () : DisplayObject; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set captionTarget (d:DisplayObject) : void; - + public function set captionTarget (d:DisplayObject) : void; + /** * Creates an Event object that contains information about caption target events. * Event objects are passed as parameters to event listeners. * * @param type The type of the event. Event listeners can access this information * through the inherited type property. There is only one type of * captionTargetCreated event: CaptionTargetEvent.CAPTION_CHANGE. * * @param bubbles Determines whether the Event object participates in the bubbling * stage of the event flow. Event listeners can access this information through the * inherited bubbles property. * * @param cancelable Determines whether the Event object can be canceled. Event listeners can * access this information through the inherited cancelable property. * * @param captionTarget A display object which is from the captionTarget * property of the FLVPlaybackCaptioning instance. * * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function CaptionTargetEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, captionTarget:DisplayObject = null); + public function CaptionTargetEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, captionTarget:DisplayObject = null); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ComponentVersion.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ComponentVersion.as index c76e6d984a..14eba44bae 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ComponentVersion.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ComponentVersion.as @@ -1,8 +1,8 @@  /** * State variable indicating the long version number of the component. * The version number is useful when you have a FLA file and need to know the component version. * To determine the component version, type the following trace into the FLA file: * * trace (FLVPlaybackCaptioning.VERSION); * *

    The VERSION variable includes * the major and minor version numbers as well as the revision and build numbers, * for example, 2.0.0.xx. The SHORT_VERSION variable includes only the major * and minor version numbers, for example, 2.0.

    * * @see #SHORT_VERSION SHORT_VERSION variable * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const VERSION : String; + public static const VERSION : String; /** * State variable indicating the short version number of the component. * The version number is useful when you have a FLA file and need to know the component version. * To determine the component version, type the following trace into the FLA file: * * trace (FLVPlaybackCaptioning.SHORT_VERSION); * *

    The SHORT_VERSION variable includes only the major * and minor version numbers, for example, 2.0. The version variable includes * the major and minor version numbers as well as the revision and build numbers, * for example, 2.0.0.xx.

    * * @see #VERSION VERSION variable * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const SHORT_VERSION : String; + public static const SHORT_VERSION : String; diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ConnectClient.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ConnectClient.as index 375794101b..c340682ce7 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ConnectClient.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ConnectClient.as @@ -1,20 +1,20 @@ -package fl.video -{ - import flash.net.NetConnection; - +package fl.video +{ + import flash.net.NetConnection; + /** *

    Holds client-side functions for remote procedure calls (rpc) * from the FMS during initial connection. One of these objects * is created and passed to the NetConnection.client * property.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ConnectClient - { - public var owner : NCManager; - public var nc : NetConnection; - public var connIndex : uint; - public var pending : Boolean; - - public function ConnectClient (owner:NCManager, nc:NetConnection, connIndex:uint = 0); - public function close () : void; - public function onBWDone (...rest) : void; - public function onBWCheck (...rest) : Number; - } -} + public class ConnectClient + { + public var owner : NCManager; + public var nc : NetConnection; + public var connIndex : uint; + public var pending : Boolean; + + public function ConnectClient (owner:NCManager, nc:NetConnection, connIndex:uint = 0); + public function close () : void; + public function onBWDone (...rest) : void; + public function onBWCheck (...rest) : Number; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ConnectClientNative.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ConnectClientNative.as index 96b65328d1..f0cf20ad3f 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ConnectClientNative.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ConnectClientNative.as @@ -1,14 +1,14 @@ -package fl.video -{ - import flash.net.NetConnection; - +package fl.video +{ + import flash.net.NetConnection; + /** *

    Holds client-side functions for remote procedure calls (rpc) * from the FMS during initial connection for NCManager2. * One of these objects is created and passed to the NetConnection.client * property.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ConnectClientNative extends ConnectClient - { - public function ConnectClientNative (owner:NCManager, nc:NetConnection, connIndex:uint = 0); - public function _onbwdone (...rest) : void; - public function _onbwcheck (...rest) : *; - } -} + public class ConnectClientNative extends ConnectClient + { + public function ConnectClientNative (owner:NCManager, nc:NetConnection, connIndex:uint = 0); + public function _onbwdone (...rest) : void; + public function _onbwcheck (...rest) : *; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ControlData.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ControlData.as index 874705cd8b..7919692ff5 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ControlData.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ControlData.as @@ -1,43 +1,43 @@ -package fl.video -{ - import flash.display.*; - +package fl.video +{ + import flash.display.*; + /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ControlData - { - public var uiMgr : UIManager; - public var index : int; - public var ctrl : DisplayObject; - public var owner : DisplayObject; - public var enabled : Boolean; - public var avatar : DisplayObject; - public var state : uint; - public var state_mc : Array; - public var disabled_mc : DisplayObject; - public var currentState_mc : DisplayObject; - public var origX : Number; - public var origY : Number; - public var origScaleX : Number; - public var origScaleY : Number; - public var origWidth : Number; - public var origHeight : Number; - public var leftMargin : Number; - public var rightMargin : Number; - public var topMargin : Number; - public var bottomMargin : Number; - public var handle_mc : Sprite; - public var percentage : Number; - public var isDragging : Boolean; - public var hit_mc : Sprite; - public var progress_mc : DisplayObject; - public var fullness_mc : DisplayObject; - public var fill_mc : DisplayObject; - public var mask_mc : DisplayObject; - public var cachedFocusRect : Boolean; - public var captureFocus : Boolean; - - public function ControlData (uiMgr:UIManager, ctrl:DisplayObject, owner:DisplayObject, index:int); - } -} + public class ControlData + { + public var uiMgr : UIManager; + public var index : int; + public var ctrl : DisplayObject; + public var owner : DisplayObject; + public var enabled : Boolean; + public var avatar : DisplayObject; + public var state : uint; + public var state_mc : Array; + public var disabled_mc : DisplayObject; + public var currentState_mc : DisplayObject; + public var origX : Number; + public var origY : Number; + public var origScaleX : Number; + public var origScaleY : Number; + public var origWidth : Number; + public var origHeight : Number; + public var leftMargin : Number; + public var rightMargin : Number; + public var topMargin : Number; + public var bottomMargin : Number; + public var handle_mc : Sprite; + public var percentage : Number; + public var isDragging : Boolean; + public var hit_mc : Sprite; + public var progress_mc : DisplayObject; + public var fullness_mc : DisplayObject; + public var fill_mc : DisplayObject; + public var mask_mc : DisplayObject; + public var cachedFocusRect : Boolean; + public var captureFocus : Boolean; + + public function ControlData (uiMgr:UIManager, ctrl:DisplayObject, owner:DisplayObject, index:int); + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CuePointManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CuePointManager.as index e06a37a499..488e620216 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CuePointManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CuePointManager.as @@ -1,123 +1,123 @@ -package fl.video -{ +package fl.video +{ /** * Dispatched when a cue point is reached. Event Object has an * info property that contains the info object received by the * NetStream.onCuePoint callback for FLV cue points or * the object passed into the ActionScript cue point APIs for ActionScript cue points.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("cuePoint")] - + [Event("cuePoint")] + /** * The CuePointManager class manages ActionScript cue points and enabling/disabling FLV * embedded cue points for the FLVPlayback class. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class CuePointManager - { - private var _owner : FLVPlayback; - local var _metadataLoaded : Boolean; - local var _disabledCuePoints : Array; - local var _disabledCuePointsByNameOnly : Object; - local var _asCuePointIndex : int; - local var _asCuePointTolerance : Number; - local var _linearSearchTolerance : Number; - local var _id : uint; - static const DEFAULT_LINEAR_SEARCH_TOLERANCE : Number = 50; - local var allCuePoints : Array; - local var asCuePoints : Array; - local var flvCuePoints : Array; - local var navCuePoints : Array; - local var eventCuePoints : Array; - static var cuePointsReplace : Array; - + public class CuePointManager + { + private var _owner : FLVPlayback; + local var _metadataLoaded : Boolean; + local var _disabledCuePoints : Array; + local var _disabledCuePointsByNameOnly : Object; + local var _asCuePointIndex : int; + local var _asCuePointTolerance : Number; + local var _linearSearchTolerance : Number; + local var _id : uint; + static const DEFAULT_LINEAR_SEARCH_TOLERANCE : Number = 50; + local var allCuePoints : Array; + local var asCuePoints : Array; + local var flvCuePoints : Array; + local var navCuePoints : Array; + local var eventCuePoints : Array; + static var cuePointsReplace : Array; + /** * Has metadata been loaded. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get metadataLoaded () : Boolean; + public function get metadataLoaded () : Boolean; /** * Set by FLVPlayback to update _asCuePointTolerance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set playheadUpdateInterval (aTime:Number) : void; + public function set playheadUpdateInterval (aTime:Number) : void; /** * Corresponds to _vp and _cpMgr array index in FLVPlayback. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get id () : uint; - + public function get id () : uint; + /** * Constructor * * @helpid 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function CuePointManager (owner:FLVPlayback, id:uint); + public function CuePointManager (owner:FLVPlayback, id:uint); /** * Reset cue point lists. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function reset () : void; + public function reset () : void; /** * Add an ActionScript cue point. * *

    It is legal to add multiple AS cue points with the same * name and time. When removeASCuePoint is called with this * name and time, all will be removed.

    * * @param timeOrCuePoint If Object, then object describing the cue * point. Must have a name:String and time:Number (in seconds) * property. May have a parameters:Object property that holds * name/value pairs. May have type:String set to "actionscript", * if it is missing or set to something else it will be set * automatically. If the Object does not conform to these * conventions, a VideoError will be thrown. * *

    If Number, then time for new cue point to be added * and name parameter must follow.

    * * @param name Name for cuePoint if timeOrCuePoint parameter * is a Number. * * @param parameters Parameters for cuePoint if * timeOrCuePoint parameter is a Number. * * @return A copy of the cuePoint Object added. The copy has the * following additional properties: * *
      *
    • array - the array of all AS cue points. Treat * this array as read only as adding, removing or editing objects * within it can cause cue points to malfunction.
    • *
    • index - the index into the array for the * returned cuepoint.
    • *
    * * @throws VideoError if parameters are invalid * @see #removeASCuePoint() * @see #getCuePoint() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addASCuePoint (timeOrCuePoint:*, name:String = null, parameters:Object = null) : Object; + public function addASCuePoint (timeOrCuePoint:*, name:String = null, parameters:Object = null) : Object; /** * Remove an ActionScript cue point from the currently * loaded FLV. Only the name and time properties are used * from the cuePoint parameter to find the cue point to be * removed. * *

    If multiple AS cue points match the search criteria, only * one will be removed. To remove all, call this function * repeatedly in a loop with the same parameters until it returns * null.

    * * @param timeNameOrCuePoint If string, name of cue point to * remove; remove first cue point with this name. If number, time * of cue point to remove; remove first cue point at this time. * If Object, then object with name and time properties, remove * cue point with both this name and time. * * @returns The cue point that was removed. If there was no * matching cue point then null is returned. * * @see #addASCuePoint() * @see #getCuePoint() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeASCuePoint (timeNameOrCuePoint:*) : Object; + public function removeASCuePoint (timeNameOrCuePoint:*) : Object; /** *

    Enable or disable one or more FLV cue point. Disabled cue * points are disabled for being dispatched as events and * navigating to them with seekToPrevNavCuePoint(), * seekToNextNavCuePoint() and * seekToNavCuePoint().

    * *

    If this API is called just after setting the * contentPath property or if no FLV is loaded, then * the cue point will be enabled or disabled in the FLV to be * loaded. Otherwise, it will be enabled or disabled in the * currently loaded FLV (even if it is called immediately before * setting the contentPath property to load another * FLV).

    * *

    Changes caused by calls to this function will not be * reflected in results returned from * isFLVCuePointEnabled until * metadataLoaded is true.

    * * @param enabled whether to enable or disable FLV cue point * @param timeNameOrCuePoint If string, name of cue point to * enable/disable. If number, time of cue point to * enable/disable. If Object, then object with name and time * properties, enable/disable cue point that matches both name and * time. * @returns If metadataLoaded is true, returns number * of cue points whose enabled state was changed. If * metadataLoaded is false, always returns -1. * @see #isFLVCuePointEnabled() * @see #getCuePoint() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setFLVCuePointEnabled (enabled:Boolean, timeNameOrCuePoint:*) : int; + public function setFLVCuePointEnabled (enabled:Boolean, timeNameOrCuePoint:*) : int; /** * removes enabled cue points from _disabledCuePoints * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeCuePoints (cuePointArray:Array, cuePoint:Object) : Number; + public function removeCuePoints (cuePointArray:Array, cuePoint:Object) : Number; /** * Inserts cue points into array. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function insertCuePoint (insertIndex:int, cuePointArray:Array, cuePoint:Object) : Array; + public function insertCuePoint (insertIndex:int, cuePointArray:Array, cuePoint:Object) : Array; /** * Returns false if FLV embedded cue point is disabled by * ActionScript. Cue points are disabled via setting the * cuePoints property or by calling * setFLVCuePointEnabled(). * *

    The return value from this function is only meaningful when * metadata is true. It always returns false * when it is null.

    * * @param timeNameOrCuePoint If string, name of cue point to * check; return false only if ALL cue points with this name are * disabled. If number, time of cue point to check. If Object, * then object with name and time properties, check cue point that * matches both name and time. * @returns false if cue point(s) is found and is disabled, true * either if no such cue point exists or if it is not disabled. * If time given is undefined, null or less than 0 then returns * false only if all cue points with this name are disabled. * *

    The return value from this function is only meaningful when * metadata is true. It always returns true when it * is false.

    * @see #getCuePoint() * @see #setFLVCuePointEnabled() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function isFLVCuePointEnabled (timeNameOrCuePoint:*) : Boolean; + public function isFLVCuePointEnabled (timeNameOrCuePoint:*) : Boolean; /** * Called by FLVPlayback on "playheadUpdate" event * to throw "cuePoint" events when appropriate. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function dispatchASCuePoints () : void; + public function dispatchASCuePoints () : void; /** * When our place in the stream is changed, this is called * to reset our index into actionscript cue point array. * Another method is used when AS cue points are added * are removed. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function resetASCuePointIndex (time:Number) : void; + public function resetASCuePointIndex (time:Number) : void; /** * Called by FLVPlayback "metadataReceived" event handler to process flv * embedded cue points array. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function processFLVCuePoints (metadataCuePoints:Array) : void; + public function processFLVCuePoints (metadataCuePoints:Array) : void; /** *

    Process Array passed into FLVPlayback cuePoints property. * Array actually holds name value pairs. Each cue point starts * with 5 pairs: t,time,n,name,t,type,d,disabled,p,numparams. * time is a Number in milliseconds (e.g. 3000 = 3 seconds), name * is a String, type is a Number (0 = event, 1 = navigation, 2 = * actionscript), disabled is a Number (0 for false, 1 for true) * and numparams is a Number. After this, there are numparams * name/value pairs which could be any simple type.

    * *

    Note that all Strings are escaped with html/xml entities for * ampersand (&), double quote ("), single quote (') * and comma (,), so must be unescaped.

    * * @see FLVPlayback#cuePoints * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function processCuePointsProperty (cuePoints:Array) : void; + public function processCuePointsProperty (cuePoints:Array) : void; /** * Used by processCuePointsProperty * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function addOrDisable (disable:Boolean, cuePoint:Object) : void; + function addOrDisable (disable:Boolean, cuePoint:Object) : void; /** * Used by processCuePointsProperty * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function unescape (origStr:String) : String; + function unescape (origStr:String) : String; /** * Search for a cue point in an array sorted by time. See * closeIsOK parameter for search rules. * * @param cuePointArray array to search * @param closeIsOK If true, the behavior differs depending on the * parameters passed in: * *
      * *
    • If name is null or undefined, then if the specific time is * not found then the closest time earlier than that is returned. * If there is no cue point earlier than time, the first cue point * is returned.
    • * *
    • If time is null, undefined or less than 0 then the first * cue point with the given name is returned.
    • * *
    • If time and name are both defined then the closest cue * point, then if the specific time and name is not found then the * closest time earlier than that with that name is returned. If * there is no cue point with that name and with an earlier time, * then the first cue point with that name is returned. If there * is no cue point with that name, null is returned.
    • * *
    • If time is null, undefined or less than 0 and name is null * or undefined, a VideoError is thrown.
    • * *
    * *

    If closeIsOK is false the behavior is:

    * *
      * *
    • If name is null or undefined and there is a cue point with * exactly that time, it is returned. Otherwise null is * returned.
    • * *
    • If time is null, undefined or less than 0 then the first * cue point with the given name is returned.
    • * *
    • If time and name are both defined and there is a cue point * with exactly that time and name, it is returned. Otherwise null * is returned.
    • * *
    • If time is null, undefined or less than 0 and name is null * or undefined, a VideoError is thrown.
    • * *
    * @param time search criteria * @param name search criteria * @param start index of first item to be searched, used for * recursive implementation, defaults to 0 if undefined * @param len length of array to search, used for recursive * implementation, defaults to cuePointArray.length if undefined * @returns index for cue point in given array or -1 if no match found * @throws VideoError if time and/or name parameters are bad * @see #cuePointCompare() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function getCuePointIndex (cuePointArray:Array, closeIsOK:Boolean, time:Number = NaN, name:String = null, start:int = -1, len:int = -1) : int; + function getCuePointIndex (cuePointArray:Array, closeIsOK:Boolean, time:Number = NaN, name:String = null, start:int = -1, len:int = -1) : int; /** * Given a name, array and index, returns the next cue point in * that array after given index with the same name. Returns null * if no cue point after that one with that name. Throws * VideoError if argument is invalid. * * @returns index for cue point in given array or -1 if no match found. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function getNextCuePointIndexWithName (name:String, array:Array, index:int) : int; + function getNextCuePointIndexWithName (name:String, array:Array, index:int) : int; /** * Takes two cue point Objects and returns -1 if first sorts * before second, 1 if second sorts before first and 0 if they are * equal. First compares times with millisecond precision. If * they match, compares name if name parameter is not null or undefined. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - static function cuePointCompare (time:Number, name:String, cuePoint:Object) : int; + static function cuePointCompare (time:Number, name:String, cuePoint:Object) : int; /** *

    Search for a cue point in the given array at the given time * and/or with given name.

    * * @param closeIsOK If true, the behavior differs depending on the * parameters passed in: * *
      * *
    • If name is null or undefined, then if the specific time is * not found then the closest time earlier than that is returned. * If there is no cue point earlier than time, the first cue point * is returned.
    • * *
    • If time is null, undefined or less than 0 then the first * cue point with the given name is returned.
    • * *
    • If time and name are both defined then the closest cue * point, then if the specific time and name is not found then the * closest time earlier than that with that name is returned. If * there is no cue point with that name and with an earlier time, * then the first cue point with that name is returned. If there * is no cue point with that name, null is returned.
    • * *
    • If time is null, undefined or less than 0 and name is null * or undefined, a VideoError is thrown.
    • * *
    * *

    If closeIsOK is false the behavior is:

    * *
      * *
    • If name is null or undefined and there is a cue point with * exactly that time, it is returned. Otherwise null is * returned.
    • * *
    • If time is null, undefined or less than 0 then the first * cue point with the given name is returned.
    • * *
    • If time and name are both defined and there is a cue point * with exactly that time and name, it is returned. Otherwise null * is returned.
    • * *
    • If time is null, undefined or less than 0 and name is null * or undefined, a VideoError is thrown.
    • * *
    * @param timeOrCuePoint If String, then name for search. If * Number, then time for search. If Object, then cuepoint object * containing time and/or name parameters for search. * @returns null if no match was found, otherwise * copy of cuePoint object with additional properties: * *
      * *
    • array - the array that was searched. Treat * this array as read only as adding, removing or editing objects * within it can cause cue points to malfunction.
    • * *
    • index - the index into the array for the * returned cuepoint.
    • * *
    * @see #getCuePointIndex() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function getCuePoint (cuePointArray:Array, closeIsOK:Boolean, timeNameOrCuePoint:*) : Object; + function getCuePoint (cuePointArray:Array, closeIsOK:Boolean, timeNameOrCuePoint:*) : Object; /** *

    Given a cue point object returned from getCuePoint (needs * the index and array properties added to those cue points), * returns the next cue point in that array after that one with * the same name. Returns null if no cue point after that one * with that name. Throws VideoError if argument is invalid.

    * * @returns null if no match was found, otherwise * copy of cuePoint object with additional properties: * *
      * *
    • array - the array that was searched. Treat * this array as read only as adding, removing or editing objects * within it can cause cue points to malfunction.
    • * *
    • index - the index into the array for the * returned cuepoint.
    • * *
    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function getNextCuePointWithName (cuePoint:Object) : Object; + function getNextCuePointWithName (cuePoint:Object) : Object; /** * Used to make copies of cue point objects. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - static function deepCopyObject (obj:Object, recurseLevel:uint = 0) : Object; - } -} + static function deepCopyObject (obj:Object, recurseLevel:uint = 0) : Object; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CuePointType.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CuePointType.as index 76362c7433..233f52a75a 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CuePointType.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/CuePointType.as @@ -1,30 +1,30 @@ -package fl.video -{ +package fl.video +{ /** * The CuePointType class provides constant values for the * type property on the info object of a * MetadataEvent instance of type CUE_POINT. This type property * is always EVENT, NAVIGATION, or ACTIONSCRIPT. * *

    All of these constants can also be * passed into the FLVPlayback.findCuePoint() and * FLVPlayback.findNearestCuePoint() methods as the type * parameter. The ALL and FLV constants describe multiple * types of cue points for these methods.

    * * @see FLVPlayback#findCuePoint() * @see FLVPlayback#findNearestCuePoint() * @see MetadataEvent * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class CuePointType - { + public class CuePointType + { /** * * * Defines the value of the type * parameter of the findCuePoint() and findNearestCuePoint() methods. * This constant describes all of the cue points: EVENT, NAVIGATION, and ACTIONSCRIPT. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ALL : String = "all"; + public static const ALL : String = "all"; /** * Defines the value of the type * parameter of the findCuePoint() and findNearestCuePoint() methods. * Additionally, the EVENT constant can be a value * for the type property on the info object of a * MetadataEvent instance of type CUE_POINT. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const EVENT : String = "event"; + public static const EVENT : String = "event"; /** * Defines the value of the type * parameter of the findCuePoint() and findNearestCuePoint() methods. * Additionally, the NAVIGATION constant can be a value * for the type property on the info object of a * MetadataEvent instance of type CUE_POINT. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const NAVIGATION : String = "navigation"; + public static const NAVIGATION : String = "navigation"; /** * Defines the value of the type * parameter of the findCuePoint() and findNearestCuePoint() methods. * This constant describes the group of * all cue points embedded within a FLV file: NAVIGATION and EVENT. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const FLV : String = "flv"; + public static const FLV : String = "flv"; /** * Defines the value of the type * parameter of the findCuePoint() and findNearestCuePoint() methods. * Additionally, the ACTIONSCRIPT constant can be a value * for the type property on the info object of a * MetadataEvent instance of type CUE_POINT. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const ACTIONSCRIPT : String = "actionscript"; - - } -} + public static const ACTIONSCRIPT : String = "actionscript"; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FLVPlayback.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FLVPlayback.as index eaef54c01c..20d69e4fc8 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FLVPlayback.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FLVPlayback.as @@ -1,860 +1,860 @@ -package fl.video -{ - import flash.display.*; - import flash.events.*; - import flash.geom.Rectangle; - import flash.media.*; - import flash.net.*; - import flash.utils.*; - +package fl.video +{ + import flash.display.*; + import flash.events.*; + import flash.geom.Rectangle; + import flash.media.*; + import flash.net.*; + import flash.utils.*; + /** * Dispatched when the video player is resized or laid out automatically. A video player is * laid out automatically based on the values of the align and scaleMode properties * when a new FLV file is loaded or when one of those two properties is changed. * *

    The autoLayout event is of type AutoLayoutEvent and has the constant * AutoLayoutEvent.AUTO_LAYOUT.

    * *

    After an attempt to automatically lay out a video player, the event object is dispatched even if the dimensions were * not changed.

    * *

    A LayoutEvent is also dispatched in these three scenarios:

    *
      *
    • If the video player that laid itself out is visible.
    • *
    • If there are two video players of different sizes or positions and the * visibleVideoPlayerIndex property is switched from one video player to another.
    • *
    • If methods or properties that change the size of the video player such * as setSize(), setScale(), * width, height, scaleX, scaleY, * registrationWidth and registrationHeight, are called.
    • *
    * *

    If multiple video player instances are in use, this event may * not apply to the visible video player.

    * * @see AutoLayoutEvent#AUTO_LAYOUT * @see #scaleMode * @see #event:layout layout event * @see #visibleVideoPlayerIndex * * @tiptext autoLayout event * @eventType fl.video.AutoLayoutEvent.AUTO_LAYOUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("autoLayout", type="fl.video.AutoLayoutEvent")] + [Event("autoLayout", type="fl.video.AutoLayoutEvent")] /** * Dispatched when the playhead is moved to the start of the video player because the * autoRewind property is set to true. When the * autoRewound event is dispatched, the rewind event is also * dispatched. * *

    The autoRewound event is of type VideoEvent and has the constant * VideoEvent.AUTO_REWOUND.

    * * @see VideoEvent#AUTO_REWOUND * @see #autoRewind * @see #event:rewind rewind event * * @tiptext autoRewound event * @eventType fl.video.VideoEvent.AUTO_REWOUND * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("autoRewound", type="fl.video.VideoEvent")] + [Event("autoRewound", type="fl.video.VideoEvent")] /** * Dispatched when the FLVPlayback instance enters the buffering state. * The FLVPlayback instance typically enters this state immediately after a call to the * play() method or when the Play control is clicked, * before entering the playing state. * *

    The stateChange event is also dispatched.

    * *

    The bufferingStateEntered event is of type VideoEvent and has the constant * VideoEvent.BUFFERING_STATE_ENTERED.

    * * @see VideoState#BUFFERING * @see VideoEvent#BUFFERING_STATE_ENTERED * @see #play() * @see #playheadTime * @see #state * @see #event:stateChange stateChange event * * @tiptext buffering event * @eventType fl.video.VideoEvent.BUFFERING_STATE_ENTERED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("bufferingStateEntered", type="fl.video.VideoEvent")] + [Event("bufferingStateEntered", type="fl.video.VideoEvent")] /** * Dispatched when the event object closes the NetConnection, * by timing out or through a call to the closeVideoPlayer() method or when * you call the load() or play() methods or set the * source property and cause the RTMP connection * to close as a result. The FLVPlayback instance dispatches this event only when * streaming from Flash Media Server (FMS) or other Flash Video Streaming Service (FVSS). * *

    The close event is of type VideoEvent and has the constant * VideoEvent.CLOSE.

    * * @see VideoEvent#CLOSE * @see #closeVideoPlayer() * @see #source * @see #load() * @see #play() * * @tiptext close event * @eventType fl.video.VideoEvent.CLOSE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("close", type="fl.video.VideoEvent")] + [Event("close", type="fl.video.VideoEvent")] /** * Dispatched when playing completes because the player reached the end of the FLV file. * The component does not dispatch the event if you call the stop() or * pause() methods * or click the corresponding controls. * *

    When the application uses progressive download, it does not set the * totalTime * property explicitly, and it downloads an FLV file that does not specify the duration * in the metadata. The video player sets the totalTime property to an approximate * total value before it dispatches this event.

    * *

    The video player also dispatches the stateChange and stoppedStateEntered * events.

    * *

    The complete event is of type VideoEvent and has the constant * VideoEvent.COMPLETE.

    * * @see #event:stateChange stateChange event * @see #event:stoppedStateEntered stoppedStateEntered event * @see #stop() * @see #pause() * @see #totalTime * * @tiptext complete event * @eventType fl.video.VideoEvent.COMPLETE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("complete", type="fl.video.VideoEvent")] + [Event("complete", type="fl.video.VideoEvent")] /** * Dispatched when a cue point is reached. The event object has an * info property that contains the info object received by the * NetStream.onCuePoint event callback for FLV file cue points. * For ActionScript cue points, it contains the object that was passed * into the ActionScript cue point methods or properties. * *

    The cuePoint event is of type MetadataEvent and has the constant * MetadataEvent.CUE_POINT.

    * * @see MetadataEvent#CUE_POINT * @see flash.net.NetStream#event:onCuePoint NetStream.onCuePoint event * * @tiptext cuePoint event * @eventType fl.video.MetadataEvent.CUE_POINT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("cuePoint", type="fl.video.MetadataEvent")] + [Event("cuePoint", type="fl.video.MetadataEvent")] /** * Dispatched when the location of the playhead moves forward by a call to * the seek() method or by clicking the ForwardButton control. * *

    The FLVPlayback instance also dispatches playheadUpdate event.

    * *

    The fastForward event is of type VideoEvent and has the constant * VideoEvent.FAST_FORWARD.

    * * @see VideoEvent#FAST_FORWARD * @see #event:playheadUpdate playheadUpdate event * @see #seek() * * @tiptext fastForward event * @eventType fl.video.VideoEvent.FAST_FORWARD * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("fastForward", type="fl.video.VideoEvent")] + [Event("fastForward", type="fl.video.VideoEvent")] /** * Dispatched the first time the FLV file's metadata is reached. * The event object has an info property that contains the * info object received by the NetStream.onMetaData event callback. * *

    The metadataReceived event is of type MetadataEvent and has the constant * MetadataEvent.METADATA_RECEIVED.

    * * @see MetadataEvent#METADATA_RECEIVED * @see flash.net.NetStream#event:onMetaData Netstream.onMetaData event * * @tiptext metadataReceived event * @eventType fl.video.MetadataEvent.METADATA_RECEIVED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("metadataReceived", type="fl.video.MetadataEvent")] + [Event("metadataReceived", type="fl.video.MetadataEvent")] /** * Dispatched when the player enters the paused state. This happens when you call * the pause() method or click the corresponding control and it also happens * in some cases when the FLV file is loaded and the autoPlay property * is false (the state may be stopped instead). * *

    The stateChange event is also dispatched.

    * *

    The pausedStateEntered event is of type VideoEvent and has the constant * VideoEvent.PAUSED_STATE_ENTERED.

    * * @see #autoPlay * @see #pause() * @see VideoEvent#PAUSED_STATE_ENTERED * @see #event:stateChange stateChange event * * @tiptext pausedStateEntered event * @eventType fl.video.VideoEvent.PAUSED_STATE_ENTERED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("pausedStateEntered", type="fl.video.VideoEvent")] + [Event("pausedStateEntered", type="fl.video.VideoEvent")] /** * Dispatched when the playing state is entered. This may not occur immediately * after the play() method is called or the corresponding control is clicked; * often the buffering state is entered first, and then the playing state. * *

    The FLVPlayback instance also dispatches the stateChange event.

    * *

    The playingStateEntered event is of type VideoEvent and has the constant * VideoEvent.PLAYING_STATE_ENTERED.

    * * @see #play() * @see #event:stateChange stateChange event * * @tiptext playingStateEntered event * @eventType fl.video.VideoEvent.PLAYING_STATE_ENTERED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("playingStateEntered", type="fl.video.VideoEvent")] + [Event("playingStateEntered", type="fl.video.VideoEvent")] /** * Dispatched while the FLV file is playing at the frequency specified by the * playheadUpdateInterval property or when rewinding starts. * The component does not dispatch this event when the video player is paused or stopped * unless a seek occurs. * *

    The playheadUpdate event is of type VideoEvent and has the constant * VideoEvent.PLAYHEAD_UPDATE.

    * * * @see VideoEvent#PLAYHEAD_UPDATE * @see #playheadUpdateInterval * * @tiptext change event * @eventType fl.video.VideoEvent.PLAYHEAD_UPDATE * @default .25 seconds * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("playheadUpdate", type="fl.video.VideoEvent")] + [Event("playheadUpdate", type="fl.video.VideoEvent")] /** * Indicates progress made in number of bytes downloaded. Dispatched at the frequency * specified by the progressInterval property, starting * when the load begins and ending when all bytes are loaded or there is a network error. * The default is every .25 seconds starting when load is called and ending * when all bytes are loaded or if there is a network error. Use this event to check * bytes loaded or number of bytes in the buffer. * *

    Dispatched only for a progressive HTTP download. Indicates progress in number of * downloaded bytes. The event object has the bytesLoaded and bytesTotal * properties, which are the same as the FLVPlayback properties of the same names.

    * *

    The progress event is of type VideoProgressEvent and has the constant * VideoProgressEvent.PROGRESS.

    * * @see #bytesLoaded * @see #bytesTotal * @see VideoProgressEvent#PROGRESS * @see #progressInterval * * @tiptext progress event * @eventType fl.video.VideoProgressEvent.PROGRESS * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("progress", type="fl.video.VideoProgressEvent")] + [Event("progress", type="fl.video.VideoProgressEvent")] /** * Dispatched when an FLV file is loaded and ready to display. It starts the first * time you enter a responsive state after you load a new FLV file with the play() * or load() method. It starts only once for each FLV file that is loaded. * *

    The ready event is of type VideoEvent and has the constant * VideoEvent.READY.

    * * @see #load() * @see #play() * @see VideoEvent#READY * * @tiptext ready event * @eventType fl.video.VideoEvent.READY * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("ready", type="fl.video.VideoEvent")] + [Event("ready", type="fl.video.VideoEvent")] /** * Dispatched when the video player is resized or laid out. Here are two layout scenarios:
    *
    • If the video player is laid out by either using the autoLayout * event or calling the setScale() or * setSize() methods or changing the width, height, * scaleX, and scaleY properties.
    • *
    • If there are two video players of different sizes and the * visibleVideoPlayerIndex property is switched from one video player to another.
    • *
    * *

    The layout event is of type LayoutEvent and has the constant * LayoutEvent.LAYOUT.

    * * @see #event:autoLayout autoLayout event * @see LayoutEvent#LAYOUT * @see #visibleVideoPlayerIndex * * @tiptext layout event * @eventType fl.video.LayoutEvent.LAYOUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("layout", type="fl.video.LayoutEvent")] + [Event("layout", type="fl.video.LayoutEvent")] /** * Dispatched when the location of the playhead moves backward by * a call to seek() or when an autoRewind call is * completed. When an autoRewind call is completed, an autoRewound * event is triggered first. * *

    The rewind event is of type VideoEvent and has the constant * VideoEvent.REWIND.

    * * @see #autoRewind * @see #event:autoRewound autoRewound event * @see VideoEvent#REWIND * @see VideoState#REWINDING * @see #seek() * * @tiptext rewind event * @eventType fl.video.VideoEvent.REWIND * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("rewind", type="fl.video.VideoEvent")] + [Event("rewind", type="fl.video.VideoEvent")] /** * Dispatched when the user stops scrubbing the FLV file with the seek bar. * Scrubbing refers to grabbing the handle of the SeekBar and dragging it in * either direction to locate a particular scene in the FLV file. Scrubbing stops * when the user releases the handle of the seek bar. * *

    The component also dispatches the stateChange event with * the state property, which is either playing, paused, * stopped, or buffering. The state property is * seeking until the user finishes scrubbing.

    * *

    The scrubFinish event is of type VideoEvent and has the constant * VideoEvent.SCRUB_FINISH.

    * * @see VideoEvent#SCRUB_FINISH * @see #state * @see #event:stateChange stateChange event * * @tiptext scrubFinish event * @eventType fl.video.VideoEvent.SCRUB_FINISH * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("scrubFinish", type="fl.video.VideoEvent")] + [Event("scrubFinish", type="fl.video.VideoEvent")] /** * Dispatched when the user begins scrubbing the FLV file with the seek bar. * Scrubbing refers to grabbing the handle of the SeekBar and dragging it in either direction * to locate a particular scene in the FLV file. * Scrubbing begins when the user clicks the SeekBar handle and ends when the user * releases it. * *

    The component also dispatches the stateChange event with the * state property equal to seeking. The state remains seeking until the user * stops scrubbing.

    * *

    The scrubStart event is of type VideoEvent and has the constant * VideoEvent.SCRUB_START.

    * * @see VideoEvent#SCRUB_START * @see #state * @see #event:stateChange stateChange event * * @tiptext scrubStart event * @eventType fl.video.VideoEvent.SCRUB_START * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("scrubStart", type="fl.video.VideoEvent")] + [Event("scrubStart", type="fl.video.VideoEvent")] /** * Dispatched when the location of the playhead is changed by a call to * seek() or by setting the playheadTime property or * by using the SeekBar control. The * playheadTime property is the destination time. * *

    The seeked event is of type VideoEvent and has the constant * VideoEvent.SEEKED.

    * *

    The FLVPlayback instance dispatches the rewind event when the seek * is backward and the fastForward event when the seek is forward. It also * dispatches the playheadUpdate event.

    * *

    For several reasons, the playheadTime property might not have the * expected value immediately after you call one of the seek methods or set * playheadTime to cause seeking. First, for a progressive download, * you can seek only to a keyframe, so a seek takes you to the time of the first * keyframe after the specified time. (When streaming, a seek always goes to the precise * specified time even if the source FLV file doesn't have a keyframe there.) Second, * seeking is asynchronous, so if you call a seek method or set the playheadTime * property, playheadTime does not update immediately. To obtain the time after the * seek is complete, listen for the seek event, which does not start until the * playheadTime property has updated.

    * * @see #event:fastForward fastForward event * @see #playheadTime * @see #event:playheadUpdate playheadUpdate event * @see #seek() * @see VideoEvent#SEEKED * * @tiptext seeked event * @eventType fl.video.VideoEvent.SEEKED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("seeked", type="fl.video.VideoEvent")] + [Event("seeked", type="fl.video.VideoEvent")] /** * Dispatched when an error occurs loading a skin SWF file. * The event has a message property that contains the error message. * If a skin SWF file is set, playback begins when the ready event * and skinLoaded (or skinError) events have both started. * *

    The skinError event is of type SkinErrorEvent and has the constant * SkinErrorEvent.SKIN_ERROR.

    * * @see #event:ready ready event * @see SkinErrorEvent#SKIN_ERROR * @see #event:skinLoaded skinLoaded event * * @tiptext skinError event * @eventType fl.video.SkinErrorEvent.SKIN_ERROR * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("skinError", type="fl.video.SkinErrorEvent")] + [Event("skinError", type="fl.video.SkinErrorEvent")] /** * Dispatched when a skin SWF file is loaded. The component * does not begin playing an FLV file until the ready event * and skinLoaded (or skinError) events have both started. * *

    The skinLoaded event is of type VideoEvent and has the constant * VideoEvent.SKIN_LOADED.

    * * @see #event:ready ready event * @see VideoEvent#SKIN_LOADED * @see #event:skinError skinError event * * @tiptext skinLoaded event * @eventType fl.video.VideoEvent.SKIN_LOADED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("skinLoaded", type="fl.video.VideoEvent")] + [Event("skinLoaded", type="fl.video.VideoEvent")] /** * Dispatched when the playback state changes. When an autoRewind call is * completed the stateChange event is dispatched with the rewinding * state. The stateChange event does not * start until rewinding has completed. * *

    This event can be used to track when playback enters or leaves unresponsive * states such as in the middle of connecting, resizing, or rewinding. The * play(), pause(), stop() and seek() * methods queue the requests to be executed when the player enters * a responsive state.

    * *

    The stateChange event is of type VideoEvent and has the constant * VideoEvent.STATE_CHANGE.

    * * @see VideoEvent#STATE_CHANGE * * @tiptext stateChange event * @eventType fl.video.VideoEvent.STATE_CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("stateChange", type="fl.video.VideoEvent")] + [Event("stateChange", type="fl.video.VideoEvent")] /** * Dispatched when entering the stopped state. * This happens when you call the stop() method or click the * stopButton control. It also happens, in some cases, if the * autoPlay property is * false (the state might become paused * instead) when the FLV file is loaded. The FLVPlayback instance also dispatches this * event when the playhead stops at the end of the FLV file * because it has reached the end of the timeline. * *

    The FLVPlayback instance also dispatches the stateChange event.

    * *

    The stoppedStateEntered event is of type VideoEvent and has the constant * VideoEvent.STOPPED_STATE_ENTERED.

    * * @see #autoPlay * @see #event:stateChange stateChange event * @see #stop() * @see VideoState#STOPPED * @see VideoEvent#STOPPED_STATE_ENTERED * * @tiptext stopped event * @eventType fl.video.VideoEvent.STOPPED_STATE_ENTERED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("stoppedStateEntered", type="fl.video.VideoEvent")] + [Event("stoppedStateEntered", type="fl.video.VideoEvent")] /** * Dispatched when sound changes by the user either moving the handle of the * volumeBar control or setting the volume or soundTransform * property. * *

    The soundUpdate event is of type SoundEvent and has the constant * SoundEvent.SOUND_UPDATE.

    * * @see #soundTransform * @see SoundEvent#SOUND_UPDATE * @see #volume * * @tiptext soundUpdate event * @eventType fl.video.SoundEvent.SOUND_UPDATE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("soundUpdate", type="fl.video.SoundEvent")] - + [Event("soundUpdate", type="fl.video.SoundEvent")] + /** * FLVPlayback extends the Sprite class and wraps a VideoPlayer object. * *
    * NOTE: This documentation is intended for use with the FLVPlayback with Accessibility component. *

    It updates the ActionScript 3.0 Language and Components Reference for the FLVPlayback class to include the following * properties and methods which were added to improve the component's keyboard and screenreader accessibility.

    *
    * * *

    Make sure you are including the " with Accessibility" version of the component in your project * before attempting to access the new properties or methods.

    *
    * * *

    The FLVPlayback class allows you to include a video player in your application to play * progressively downloaded video (FLV) files over HTTP, or play streaming FLV files * from Flash Media Server (FMS) or other Flash Video Streaming Service (FVSS).

    * *

    Unlike other ActionScript 3.0 components, the FLVPlayback component does not extend * UIComponent; therefore, it does not support the methods and properties of that class.

    * *

    To access the properties, methods, and events of the FLVPlayback class, you must import the * class to your application either by dragging the FLVPlayback component to the Stage in your Flash * application, or by explicitly importing it in ActionScript using the import statement. * The following statement imports the FLVPlayback class:

    * * * import fl.video.FLVPlayback; * *

    The FLVPlayback class has a VERSION constant, which is a class property. Class properties are * available only on the class itself. The VERSION constant returns a string that indicates the * version of the component. The following code shows the version in the Output panel:

    * * * import fl.video.FLVPlayback; * trace(FLVPlayback.VERSION); * * @see AutoLayoutEvent * @see FLVPlaybackCaptioning * @see MetadataEvent * @see NCManager * @see LayoutEvent * @see SoundEvent * @see VideoPlayer * @see VideoError * @see VideoEvent * @see VideoProgressEvent * * @includeExample examples/FLVPlaybackExample.as -noswf * * @tiptext FLVPlayback * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class FLVPlayback extends Sprite - { + public class FLVPlayback extends Sprite + { /** * bounding box movie clip inside of component on stage * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var boundingBox_mc : DisplayObject; - private var preview_mc : MovieClip; - private var previewImage_mc : Loader; - private var previewImageUrl : String; - private var isLivePreview : Boolean; - private var livePreviewWidth : Number; - private var livePreviewHeight : Number; - private var _componentInspectorSetting : Boolean; + public var boundingBox_mc : DisplayObject; + private var preview_mc : MovieClip; + private var previewImage_mc : Loader; + private var previewImageUrl : String; + private var isLivePreview : Boolean; + private var livePreviewWidth : Number; + private var livePreviewHeight : Number; + private var _componentInspectorSetting : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var videoPlayers : Array; + local var videoPlayers : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var videoPlayerStates : Array; + local var videoPlayerStates : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var videoPlayerStateDict : Dictionary; - private var _activeVP : uint; - private var _visibleVP : uint; - private var _topVP : uint; + local var videoPlayerStateDict : Dictionary; + private var _activeVP : uint; + private var _visibleVP : uint; + private var _topVP : uint; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var uiMgr : UIManager; + local var uiMgr : UIManager; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var cuePointMgrs : Array; + local var cuePointMgrs : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _firstStreamReady : Boolean; + local var _firstStreamReady : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _firstStreamShown : Boolean; + local var _firstStreamShown : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var resizingNow : Boolean; + local var resizingNow : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var skinShowTimer : Timer; + local var skinShowTimer : Timer; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - static const DEFAULT_SKIN_SHOW_TIMER_INTERVAL : Number = 2000; + static const DEFAULT_SKIN_SHOW_TIMER_INTERVAL : Number = 2000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - static const skinShowTimerInterval : Number = DEFAULT_SKIN_SHOW_TIMER_INTERVAL; - private var _align : String; - private var _autoRewind : Boolean; - private var _bufferTime : Number; - private var _idleTimeout : Number; - private var _aspectRatio : Boolean; - private var _playheadUpdateInterval : Number; - private var _progressInterval : Number; - private var _origWidth : Number; - private var _origHeight : Number; - private var _scaleMode : String; - private var _seekToPrevOffset : Number; - private var _soundTransform : SoundTransform; - private var _volume : Number; - private var __forceNCMgr : NCManager; + static const skinShowTimerInterval : Number = DEFAULT_SKIN_SHOW_TIMER_INTERVAL; + private var _align : String; + private var _autoRewind : Boolean; + private var _bufferTime : Number; + private var _idleTimeout : Number; + private var _aspectRatio : Boolean; + private var _playheadUpdateInterval : Number; + private var _progressInterval : Number; + private var _origWidth : Number; + private var _origHeight : Number; + private var _scaleMode : String; + private var _seekToPrevOffset : Number; + private var _soundTransform : SoundTransform; + private var _volume : Number; + private var __forceNCMgr : NCManager; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const SEEK_TO_PREV_OFFSET_DEFAULT : Number = 1; - + public static const SEEK_TO_PREV_OFFSET_DEFAULT : Number = 1; + /** * A number that specifies the current playheadTime as a percentage of the * totalTime property. If you access this property, it contains the percentage * of playing time that has elapsed. If you set this property, it causes a seek * operation to the point representing that percentage of the FLV file's playing time. * *

    The value of this property is relative to the value of the totalTime * property.

    * * @throws fl.video.VideoError If you specify a percentage that is invalid or if the * totalTime property is * undefined, null, or less than or equal to zero. * * @tiptext playheadPercentage method * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get playheadPercentage () : Number; + public function get playheadPercentage () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set playheadPercentage (percent:Number) : void; + public function set playheadPercentage (percent:Number) : void; /** * Only for live preview. Reads in a PNG file for the preview. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set preview (filename:String) : void; + public function set preview (filename:String) : void; /** * This flag is set by code automatically generated by the * authoring tool. It is turned on before properties * automatically set by the component inspector start getting * set and it is turned off after the last property is set. * * With AS2 these properties were set before the constructor * was called, which gave us a way to know that was how they * were set, although it was generally annoying. Now we * have a way to know in AS3 and we don't have to deal with * having properties called before our constructor. Cool! * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set componentInspectorSetting (b:Boolean) : void; + public function set componentInspectorSetting (b:Boolean) : void; /** * A number that specifies which video player instance is affected by other application * programming interfaces (APIs). * Use this property to manage multiple FLV file streams. * *

    This property does not make the video player visible; * use the visibleVideoPlayerIndex property to do that.

    * *

    A new video player is created the first time activeVideoPlayerIndex * is set to a number. When the new video player is created, * its properties are set to the value of the default video player * (activeVideoPlayerIndex == 0) except for source, * totalTime, and isLive, which are always set to the * default values (empty string, NaN, and false, respectively), * and autoPlay, which is always false (the default is true * only for the default video player, 0). The cuePoints * property has no effect, as it would have no effect * on a subsequent load into the default video player.

    * *

    APIs that control volume, positioning, dimensions, visibility, * and UI controls are always global, and their behavior is not * affected by setting activeVideoPlayerIndex. Specifically, setting * the activeVideoPlayerIndex property does not affect the following * properties and methods:

    * * Properties and Methods Not Affected by activeVideoPlayerIndex * * * * * * * * * * * *
    backButtonplayPauseButtonskinwidth
    bufferingBarscaleXstopButtonx
    bufferingBarHidesAndDisablesOtherstransformysetSize()
    forwardButtonscaleYvisiblesetScale()
    heightseekBarvolumefullScreenBackgroundColor
    muteButtonseekBarIntervalvolumeBarfullScreenButton
    pauseButtonseekBarScrubTolerancevolumeBarIntervalfullScreenSkinDelay
    playButtonseekToPrevOffsetvolumeBarScrubTolerancefullScreenTakeOver
    registrationXregistrationYregistrationWidthregistrationHeight
    skinBackgroundAlphaskinBackgroundColorskinFadeTime
    * *

    Note: The visibleVideoPlayerIndex property, not the * activeVideoPlayerIndex property, determines which * video player the skin controls. Additionaly, APIs that control dimensions * do interact with the visibleVideoPlayerIndex property.

    * *

    The remaining APIs target a specific video player based on the * setting of activeVideoPlayerIndex.

    * *

    To load a second FLV file in the background, set activeVideoPlayerIndex * to 1 and call the load() method. When you are * ready to show this FLV file and hide the first one, * set visibleVideoPlayerIndex to 1.

    * * @see #visibleVideoPlayerIndex * @default 0 * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get activeVideoPlayerIndex () : uint; + public function get activeVideoPlayerIndex () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set activeVideoPlayerIndex (index:uint) : void; + public function set activeVideoPlayerIndex (index:uint) : void; /** * Specifies the video layout when the scaleMode property is set to * VideoScaleMode.MAINTAIN_ASPECT_RATIO or VideoScaleMode.NO_SCALE. * The video dimensions are based on the * registrationX, registrationY, * registrationWidth, and * registrationHeight properties. When you set the align property, * values come from the VideoAlign class. The default is VideoAlign.CENTER. * * @see #scaleMode * @see #registrationX * @see #registrationY * @see #registrationWidth * @see #registrationHeight * @see VideoAlign * @see VideoPlayer#align * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get align () : String; + public function get align () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set align (s:String) : void; + public function set align (s:String) : void; /** * A Boolean value that, if set to true, causes the FLV file to start * playing automatically after the source property is set. If it is set to false, * the FLV file loads but does not start playing until the play() * or playWhenEnoughDownloaded() method is called. * *

    Playback starts immediately when you are streaming an FLV file from Flash Media Server (FMS) and the * autoPlay property is set to true. However, * when loading an FLV file by progressive download, playback starts only * when enough of the FLV file has download so that the FLV file can play from start * to finish.

    * *

    To force playback before enough of the FLV file has downloaded, * call the play() method with no parameters. If playback * has begun and you want to return to the state of waiting * for enough to download and then automatically begin playback, * call the pause() method, and then the * playWhenEnoughDownloaded() method.

    * *

    If you set the property to true between the loading of new FLV files, * it has no effect until the source property is set.

    * *

    Setting the autoPlay property to true and * then setting the source property to a URL has the same * effect as calling the play() method with that URL.

    * *

    Calling the load() method with a URL has the same effect * as setting the source property to that URL with the * autoPlay property set to false.

    * * @see #source * @see #load() * @see #play() * @see #playWhenEnoughDownloaded() * @default true * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get autoPlay () : Boolean; + public function get autoPlay () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set autoPlay (flag:Boolean) : void; + public function set autoPlay (flag:Boolean) : void; /** * A Boolean value that, if true, causes the FLV file to rewind to Frame 1 when * play stops, either because the player reached the end of the stream or the * stop() method was called. This property is meaningless for live streams. * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get autoRewind () : Boolean; + public function get autoRewind () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set autoRewind (flag:Boolean) : void; + public function set autoRewind (flag:Boolean) : void; /** * A number that specifies the bits per second at which to transfer the FLV file. * *

    When streaming from a Flash Video Streaming service that supports * native bandwidth detection, you can provide a SMIL file that * describes how to switch between multiple streams based on the * bandwidth. Depending on your FVSS, bandwidth may automatically be * detected, and if this value is set, it is ignored.

    * *

    When doing HTTP progressive download, you can use the same SMIL * format, but you must set the bitrate as there is no automatic * detection.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bitrate () : Number; + public function get bitrate () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set bitrate (b:Number) : void; + public function set bitrate (b:Number) : void; /** * A Boolean value that is true if the video is in a buffering state. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get buffering () : Boolean; + public function get buffering () : Boolean; /** * Buffering bar control. This control is displayed when the FLV file is in * a loading or buffering state. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bufferingBar () : Sprite; + public function get bufferingBar () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set bufferingBar (s:Sprite) : void; + public function set bufferingBar (s:Sprite) : void; /** * If set to true, hides the SeekBar control and disables the * Play, Pause, PlayPause, BackButton and ForwardButton controls while the * FLV file is in the buffering state. This can be useful to prevent a * user from using these controls to try to speed up playing the FLV file * when it is downloading or streaming over a slow connection. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bufferingBarHidesAndDisablesOthers () : Boolean; + public function get bufferingBarHidesAndDisablesOthers () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set bufferingBarHidesAndDisablesOthers (b:Boolean) : void; + public function set bufferingBarHidesAndDisablesOthers (b:Boolean) : void; /** * BackButton playback control. Clicking calls the * seekToPrevNavCuePoint() method. * * @see #seekToPrevNavCuePoint() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get backButton () : Sprite; + public function get backButton () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set backButton (s:Sprite) : void; + public function set backButton (s:Sprite) : void; /** * A number that specifies the number of seconds to buffer in memory before * beginning to play a video stream. For FLV files streaming over RTMP, * which are not downloaded and buffer only in memory, it can be important * to increase this setting from the default value of 0.1. For a progressively * downloaded FLV file over HTTP, there is little benefit to increasing this * value although it could improve viewing a high-quality video on an older, * slower computer. * *

    For prerecorded (not live) video, do not set the bufferTime * property to 0: * use the default buffer time or increase the buffer time.

    * *

    This property does not specify the amount of the FLV file to download before * starting playback.

    * * @see VideoPlayer#bufferTime * @see #isLive * * @default 0.1 * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bufferTime () : Number; + public function get bufferTime () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set bufferTime (aTime:Number) : void; + public function set bufferTime (aTime:Number) : void; /** * A number that indicates the extent of downloading, in number of bytes, for an * HTTP download. Returns 0 when there * is no stream, when the stream is from Flash Media Server (FMS), or if the information * is not yet available. The returned value is useful only for an HTTP download. * * @tiptext Number of bytes already loaded * @helpid 3455 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bytesLoaded () : uint; + public function get bytesLoaded () : uint; /** * A number that specifies the total number of bytes downloaded for an HTTP download. * Returns 0 when there is no stream, when the stream is from Flash Media Server (FMS), or if * the information is not yet available. The returned value is useful only * for an HTTP download. * * @tiptext Number of bytes to be loaded * @helpid 3456 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bytesTotal () : uint; + public function get bytesTotal () : uint; /** * A string that specifies the URL of the FLV file to stream and how to stream it. * The URL can be an HTTP URL to an FLV file, an RTMP URL to a stream, or an * HTTP URL to an XML file. * *

    If you set this property through the Component inspector or the Property inspector, the * FLV file begins loading and playing at the next "enterFrame" event. * The delay provides time to set the isLive, autoPlay, * and cuePoints properties, * among others, which affect loading. It also allows ActionScript that is placed * on the first frame to affect the FLVPlayback component before it starts playing.

    * *

    If you set this property through ActionScript, it immediately calls the * VideoPlayer.load() method when the autoPlay property is * set to false or it calls the VideoPlayer.play() method when * the autoPlay property is set to true. The autoPlay, * totalTime, and isLive properties affect how the new FLV file is * loaded, so if you set these properties, you must set them before setting the * source property.

    * *

    Set the autoPlay property to false to prevent the new * FLV file from playing automatically.

    * * @see #autoPlay * @see #isLive * @see #totalTime * @see #load() * @see #play() * @see VideoPlayer#load() * @see VideoPlayer#play() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get source () : String; + public function get source () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set source (url:String) : void; + public function set source (url:String) : void; /** * An array that describes ActionScript cue points and disabled embedded * FLV file cue points. This property is created specifically for use by * the Component inspector and Property inspector. It does not work if it is * set any other way. Its value has an effect only on the first FLV file * loaded and only if it is loaded by setting the source * property in the Component inspector or the Property inspector. * *

    Note: This property is not accessible in ActionScript. To * access cue point information in ActionScript, use the metadata property.

    * *

    To add, remove, enable or disable cue points with ActionScript, * use the addASCuePoint(), removeASCuePoint(), or * setFLVCuePointEnabled() methods.

    * * @see #source * @see #addASCuePoint() * @see #removeASCuePoint() * @see #setFLVCuePointEnabled() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set cuePoints (cuePointsArray:Array) : void; + public function set cuePoints (cuePointsArray:Array) : void; /** * Forward button control. Clicking calls the * seekToNextNavCuePoint() method. * * @see #seekToNextNavCuePoint() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get forwardButton () : Sprite; + public function get forwardButton () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set forwardButton (s:Sprite) : void; + public function set forwardButton (s:Sprite) : void; /** * Background color used when in full-screen takeover * mode. This color is visible if the video does * not cover the entire screen based on the scaleMode * property value. * * @default 0x000000 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get fullScreenBackgroundColor () : uint; + public function get fullScreenBackgroundColor () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set fullScreenBackgroundColor (c:uint) : void; + public function set fullScreenBackgroundColor (c:uint) : void; /** * FullScreen button control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get fullScreenButton () : Sprite; + public function get fullScreenButton () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set fullScreenButton (s:Sprite) : void; + public function set fullScreenButton (s:Sprite) : void; /** * Specifies the delay time in milliseconds to hide the skin. * When in full-screen takeover mode, if the skinAutoHide property * is true, autohiding is triggered when the user doesn't move the * mouse for more than the seconds indicated by the fullScreenSkinDelay * property. If the mouse is over the skin itself, autohiding is not triggered. * * @default 3000 milliseconds (3 seconds) * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get fullScreenSkinDelay () : int; + public function get fullScreenSkinDelay () : int; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set fullScreenSkinDelay (i:int) : void; + public function set fullScreenSkinDelay (i:int) : void; /** * When the stage enters full-screen mode, the * FLVPlayback component is on top of all * content and takes over the entire screen. When * the stage exits full-screen mode, the screen returns to * how it was before. * *

    The recommended settings for full-screen * takeover mode are scaleMode = VideoScaleMode.MAINTAIN_ASPECT_RATIO * and align = VideoAlign.CENTER.

    * *

    If the SWF file with the FLVPlayback component * is loaded and does not have access to the * stage because of security restrictions, full-screen * takeover mode does not function. No * errors are thrown.

    * * @default true * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get fullScreenTakeOver () : Boolean; + public function get fullScreenTakeOver () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set fullScreenTakeOver (v:Boolean) : void; + public function set fullScreenTakeOver (v:Boolean) : void; /** * A number that specifies the height of the FLVPlayback instance. * This property affects only the height of the FLVPlayback instance * and does not include the height of a skin SWF file that might be loaded. * Setting the height property also sets the registrationHeight property * to the same value. * * @see #setSize() * @helpid 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get height () : Number; + public function get height () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set height (h:Number) : void; + public function set height (h:Number) : void; /** * The amount of time, in milliseconds, before Flash terminates an idle connection * to Flash Media Server (FMS) because playing paused or stopped. This property has no effect on an * FLV file downloading over HTTP. * *

    If this property is set when a video stream is already idle, it restarts the * timeout period with the new value.

    * * @default 300,000 milliseconds (5 minutes) * * @see #event:close * * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get idleTimeout () : Number; + public function get idleTimeout () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set idleTimeout (aTime:Number) : void; + public function set idleTimeout (aTime:Number) : void; /** * A Boolean value that is true if the FLV file is streaming from * Flash Media Server (FMS) using RTMP. Its value is false for any other FLV file source. * * @see VideoPlayer#isRTMP * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get isRTMP () : Boolean; + public function get isRTMP () : Boolean; /** * A Boolean value that is true if the video stream is live. This property * is effective only when streaming from Flash Media Server (FMS) or other Flash Video Streaming Service (FVSS). The value of this * property is ignored for an HTTP download. * *

    If you set this property between loading new FLV files, it has no * effect until the source property is set for the new FLV file.

    * *

    Set the isLive property to false when sending a prerecorded video * stream to the video player and to true when sending real-time data * such as a live broadcast. For better performance when you set * the isLive property to false, do not set the * bufferTime property to 0.

    * * @see #bufferTime * @see #source * @see VideoPlayer#isLive * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get isLive () : Boolean; + public function get isLive () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set isLive (flag:Boolean) : void; + public function set isLive (flag:Boolean) : void; /** * An object that is a metadata information packet that is received from a call to * the NetSteam.onMetaData() callback method, if available. * Ready when the metadataReceived event is dispatched. * *

    If the FLV file is encoded with the Flash 8 encoder, the metadata * property contains the following information. Older FLV files contain * only the height, width, and duration values.

    * * * * * * * * * * * * * * *
    ParameterDescription
    canSeekToEndA Boolean value that is true if the FLV file is encoded with a keyframe on the last frame that allows seeking to the end of a progressive download movie clip. It is false if the FLV file is not encoded with a keyframe on the last frame.
    cuePointsAn array of objects, one for each cue point embedded in the FLV file. Value is undefined if the FLV file does not contain any cue points. Each object has the following properties: * *
      *
    • type—A string that specifies the type of cue point as either "navigation" or "event".
    • *
    • name—A string that is the name of the cue point.
    • *
    • time—A number that is the time of the cue point in seconds with a precision of three decimal places (milliseconds).
    • *
    • parameters—An optional object that has name-value pairs that are designated by the user when creating the cue points.
    • *
    *
    audiocodecidA number that indicates the audio codec (code/decode technique) that was used.
    audiodelayA number that represents time 0 in the source file from which the FLV file was encoded. *

    Video content is delayed for the short period of time that is required to synchronize the audio. For example, if the audiodelay value is .038, the video that started at time 0 in the source file starts at time .038 in the FLV file.

    *

    Note that the FLVPlayback and VideoPlayer classes compensate for this delay in their time settings. This means that you can continue to use the time settings that you used in your the source file.

    audiodatarateA number that is the kilobytes per second of audio.
    videocodecidA number that is the codec version that was used to encode the video.
    framerateA number that is the frame rate of the FLV file.
    videodatarateA number that is the video data rate of the FLV file.
    heightA number that is the height of the FLV file.
    widthA number that is the width of the FLV file.
    durationA number that specifies the duration of the FLV file in seconds.
    * * @see VideoPlayer#metadata * @see http://livedocs.adobe.com/flash/9.0/main/00001037.html Working with cue points * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get metadata () : Object; + public function get metadata () : Object; /** * A Boolean value that is true if a metadata packet has been * encountered and processed or if the FLV file was encoded without the * metadata packet. In other words, the value is true if the metadata is * received, or if you are never going to get any metadata. So, you * know whether you have the metadata; and if you don't have the metadata, * you know not to wait around for it. If you just want to know whether * or not you have metadata, you can check the value with: * * FLVPlayback.metadata != null * *

    Use this property to check whether you can retrieve useful * information with the methods for finding and enabling or * disabling cue points (findCuePoint, findNearestCuePoint, * findNextCuePointWithName, isFLVCuePointEnabled).

    * * @see #findCuePoint() * @see #findNearestCuePoint() * @see #findNextCuePointWithName() * @see #isFLVCuePointEnabled() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get metadataLoaded () : Boolean; + public function get metadataLoaded () : Boolean; /** * Mute button control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get muteButton () : Sprite; + public function get muteButton () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set muteButton (s:Sprite) : void; + public function set muteButton (s:Sprite) : void; /** * An INCManager object that provides access to an instance of the class implementing * INCManager, which is an interface to the NCManager class. * *

    You can use this property to implement a custom INCManager that requires * custom initialization.

    * * @see VideoPlayer#ncMgr * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get ncMgr () : INCManager; + public function get ncMgr () : INCManager; /** * Pause button control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get pauseButton () : Sprite; + public function get pauseButton () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set pauseButton (s:Sprite) : void; + public function set pauseButton (s:Sprite) : void; /** * A Boolean value that is true if the FLV file is in a paused state. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get paused () : Boolean; + public function get paused () : Boolean; /** * Play button control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get playButton () : Sprite; + public function get playButton () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set playButton (s:Sprite) : void; + public function set playButton (s:Sprite) : void; /** * A number that is the current playhead time or position, measured in seconds, * which can be a fractional value. Setting this property triggers a seek and * has all the restrictions of a seek. * *

    When the playhead time changes, which occurs once every .25 seconds * while the FLV file plays, the component dispatches the playheadUpdate * event.

    * *

    For several reasons, the playheadTime property might not have the expected * value immediately after you call one of the seek methods or set playheadTime * to cause seeking. First, for a progressive download, you can seek only to a * keyframe, so a seek takes you to the time of the first keyframe after the * specified time. (When streaming, a seek always goes to the precise specified * time even if the source FLV file doesn't have a keyframe there.) Second, * seeking is asynchronous, so if you call a seek method or set the * playheadTime property, playheadTime does not update immediately. * To obtain the time after the seek is complete, listen for the seek event, * which does not fire until the playheadTime property has updated.

    * * @tiptext Current position of the playhead in seconds * @helpid 3463 * @see #seek() * @see VideoPlayer#playheadTime * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get playheadTime () : Number; + public function get playheadTime () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set playheadTime (position:Number) : void; + public function set playheadTime (position:Number) : void; /** * A number that is the amount of time, in milliseconds, between each * playheadUpdate event. Setting this property while the FLV file is * playing restarts the timer. * *

    Because ActionScript cue points start on playhead updates, lowering * the value of the playheadUpdateInterval property can increase the accuracy * of ActionScript cue points.

    * *

    Because the playhead update interval is set by a call to the global * setInterval() method, the update cannot fire more frequently than the * SWF file frame rate, as with any interval that is set this way. * So, as an example, for the default frame rate of 12 frames per second, * the lowest effective interval that you can create is approximately * 83 milliseconds, or one second (1000 milliseconds) divided by 12.

    * * @see VideoPlayer#playheadUpdateInterval * @default 250 * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get playheadUpdateInterval () : Number; + public function get playheadUpdateInterval () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set playheadUpdateInterval (aTime:Number) : void; + public function set playheadUpdateInterval (aTime:Number) : void; /** * A Boolean value that is true if the FLV file is in the playing state. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get playing () : Boolean; + public function get playing () : Boolean; /** * Play/pause button control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get playPauseButton () : Sprite; + public function get playPauseButton () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set playPauseButton (s:Sprite) : void; + public function set playPauseButton (s:Sprite) : void; /** * A number that specifies the height of the source FLV file. This information * is not valid immediately upon calling the play() or load() * methods. It is valid when the ready event starts. If the value of the * scaleMode property is VideoScaleMode.MAINTAIN_ASPECT_RATIO * or VideoScaleMode.NO_SCALE, it is best to read * the value after the layout event is dispatched. This property returns * -1 if no information is available yet. * * @see #scaleMode * @tiptext The preferred height of the display * @helpid 3465 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get preferredHeight () : int; + public function get preferredHeight () : int; /** * Gives the width of the source FLV file. This information is not valid immediately * when the play() or load() methods are called; it is valid * after the ready event is dispatched. If the value of the * scaleMode property is VideoScaleMode.MAINTAIN_ASPECT_RATIO * or VideoScaleMode.NO_SCALE, it is best to read * the value after the layout event is dispatched. This property returns * -1 if no information is available yet. * * @see #scaleMode * @tiptext The preferred width of the display * @helpid 3466 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get preferredWidth () : int; + public function get preferredWidth () : int; /** * A number that is the amount of time, in milliseconds, between each progress * event. If you set this property while the video stream is playing, the timer restarts. * * * @see VideoPlayer#progressInterval * @default 250 * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get progressInterval () : Number; + public function get progressInterval () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set progressInterval (aTime:Number) : void; + public function set progressInterval (aTime:Number) : void; /** * @copy fl.video.VideoPlayer#registrationX * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get registrationX () : Number; + public function get registrationX () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set registrationX (x:Number) : void; + public function set registrationX (x:Number) : void; /** * @copy fl.video.VideoPlayer#registrationY * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get registrationY () : Number; + public function get registrationY () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set registrationY (y:Number) : void; + public function set registrationY (y:Number) : void; /** * @copy fl.video.VideoPlayer#registrationWidth * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get registrationWidth () : Number; + public function get registrationWidth () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set registrationWidth (w:Number) : void; + public function set registrationWidth (w:Number) : void; /** * @copy fl.video.VideoPlayer#registrationHeight * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get registrationHeight () : Number; + public function get registrationHeight () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set registrationHeight (h:Number) : void; + public function set registrationHeight (h:Number) : void; /** * Specifies how the video will resize after loading. If set to * VideoScaleMode.MAINTAIN_ASPECT_RATIO, maintains the * video aspect ratio within the rectangle defined by * registrationX, registrationY, * registrationWidth and * registrationHeight. If set to * VideoScaleMode.NO_SCALE, causes the video to size automatically * to the dimensions of the source FLV file. If set to * VideoScaleMode.EXACT_FIT, causes the dimensions of * the source FLV file to be ignored and the video is stretched to * fit the rectangle defined by * registrationX, registrationY, * registrationWidth and * registrationHeight. If this is set * after an FLV file has been loaded an automatic layout will start * immediately. Values come from * VideoScaleMode. * * @see #preferredHeight * @see #preferredWidth * @see VideoScaleMode * @default VideoScaleMode.MAINTAIN_ASPECT_RATIO * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scaleMode () : String; + public function get scaleMode () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scaleMode (s:String) : void; + public function set scaleMode (s:String) : void; /** * A number that is the horizontal scale. The standard scale is 1. * * @see #setScale() * @tiptext Specifies the horizontal scale factor * @helpid 3974 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scaleX () : Number; + public function get scaleX () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scaleX (xs:Number) : void; + public function set scaleX (xs:Number) : void; /** * A number that is the vertical scale. The standard scale is 1. * * @see #setScale() * @tiptext Specifies the vertical scale factor * @helpid 3975 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scaleY () : Number; + public function get scaleY () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set scaleY (ys:Number) : void; + public function set scaleY (ys:Number) : void; /** * A Boolean value that is true if the user is scrubbing with the SeekBar * and false otherwise. * *

    Scrubbing refers to grabbing the handle of the SeekBar and dragging * it in either direction to locate a particular scene in the FLV file.

    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get scrubbing () : Boolean; + public function get scrubbing () : Boolean; /** * The SeekBar control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get seekBar () : Sprite; + public function get seekBar () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set seekBar (s:Sprite) : void; + public function set seekBar (s:Sprite) : void; /** * A number that specifies, in milliseconds, how often to check the SeekBar handle * when scrubbing. * *

    Because this interval is set by a call to the global setInterval() method, * the update cannot start more frequently than the SWF file frame rate. So, for * the default frame rate of 12 frames per second, for example, the lowest * effective interval that you can create is approximately 83 milliseconds, * or 1 second (1000 milliseconds) divided by 12.

    * * @default 250 * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get seekBarInterval () : Number; + public function get seekBarInterval () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set seekBarInterval (s:Number) : void; + public function set seekBarInterval (s:Number) : void; /** * A number that specifies how far a user can move the SeekBar handle before an * update occurs. The value is specified as a percentage, ranging from 1 to 100. * * @default 5 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get seekBarScrubTolerance () : Number; + public function get seekBarScrubTolerance () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set seekBarScrubTolerance (s:Number) : void; + public function set seekBarScrubTolerance (s:Number) : void; /** * The number of seconds that the seekToPrevNavCuePoint() method uses * when it compares its time against the previous cue point. The method uses this * value to ensure that, if you are just ahead of a cue point, you can hop * over it to the previous one and avoid going to the same cue point that * just occurred. * * @default 1 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get seekToPrevOffset () : Number; + public function get seekToPrevOffset () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set seekToPrevOffset (s:Number) : void; + public function set seekToPrevOffset (s:Number) : void; /** * A string that specifies the URL to a skin SWF file. This string could contain a * file name, a relative path such as Skins/MySkin.swf, or an absolute URL such * as http://www.%somedomain%.com/MySkin.swf. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get skin () : String; + public function get skin () : String; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set skin (s:String) : void; + public function set skin (s:String) : void; /** * A Boolean value that, if true, hides the component skin when the mouse * is not over the video. This property affects only skins that are loaded by setting * the skin property and not a skin that you create from the FLVPlayback * Custom UI components. * *

    When the component is in full-screen takeover mode and the skin is one that does not lay over * the video, then skinAutoHide mode is turned on automatically. Setting skinAutoHide = false * after you enter full-screen mode overrides this behavior. Also when the component is * in full-screen takeover mode, autohiding is triggered if the user doesn't move the * mouse for more than fullScreenSkinDelay seconds, unless the mouse is over the skin itself.

    * * @default false * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get skinAutoHide () : Boolean; + public function get skinAutoHide () : Boolean; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set skinAutoHide (b:Boolean) : void; + public function set skinAutoHide (b:Boolean) : void; /** * The alpha for the background of the skin. The skinBackgroundAlpha * property works only with SWF files that have skins loaded by using the * skin property and with skins that support setting the color * and alpha. You can set the skinBackgroundAlpha property * to a number between 0.0 and 1.0. The default is the last value chosen by the * user as the default. * *

    To get the skin colors that come with the ActionScript 2.0 FLVPlayback component, * use the following values for the * skinBackgroundAlpha and skinBackgroundColor properties: * Arctic - 0.85, 0x47ABCB; * Clear - 0.20, 0xFFFFFF; Mojave - 0.85, 0xBFBD9F; Steel - 0.85, 0x666666. * The default is .85.

    * * * @see #skin * @see #skinBackgroundColor * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get skinBackgroundAlpha () : Number; + public function get skinBackgroundAlpha () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set skinBackgroundAlpha (a:Number) : void; + public function set skinBackgroundAlpha (a:Number) : void; /** * The color for the background of the skin (0xRRGGBB). The skinBackgroundColor * property works only with SWF files that have skins loaded by using the * skin property and with skins that support setting the color * and alpha. The default is the last value chosen by the * user as the default. * *

    To get the skin colors that come with the ActionScript 2.0 FLVPlayback component, * use the following values for the * skinBackgroundAlpha and skinBackgroundColor properties: * Arctic - 0.85, 0x47ABCB; * Clear - 0.20, 0xFFFFFF; Mojave - 0.85, 0xBFBD9F; Steel - 0.85, 0x666666. * The default is 0x47ABCB.

    * * * @see #skin * @see #skinBackgroundAlpha * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get skinBackgroundColor () : uint; + public function get skinBackgroundColor () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set skinBackgroundColor (c:uint) : void; + public function set skinBackgroundColor (c:uint) : void; /** * The amount of time in milliseconds that it takes for the skin to fade in or fade out when * hiding or showing. Hiding and showing occurs because the skinAutoHide * property is set to true. Set the skinFadeTime property to * 0 to eliminate the fade effect. * * @default 500 milliseconds (.5 seconds) * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get skinFadeTime () : int; + public function get skinFadeTime () : int; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set skinFadeTime (i:int) : void; + public function set skinFadeTime (i:int) : void; /** * This property specifies the largest multiple that FLVPlayback will use to scale up * its skin when it enters full screen mode with a Flash Player that supports * hardware acceleration. With hardware acceleration, the video and the skin are scaled * by the same factor. By default, FLVPlayback renders the video at its native dimensions * and allows hardware acceleration to do the rest of the scaling. If, for example, * your video has dimensions of 640 x 512 and it goes to full screen size on a monitor with * a resolution of 1280 x 1024, the video and the skin will be scaled up to twice their * size. * *

    This property enables you to restrict scaling of the skin when hardware acceleration * is used, based on the specific content that is being scaled and your aesthetic * tastes regarding the appearance of large skins. To limit scaling of the skin to the * specified multiplier, FLVPlayback uses a mix of software and hardware scaling for the skin, * which can have a negative impact on the performance of video playback and the * appearance of the FLV.

    * *

    For example, if this property was set to 5.0 or greater, going to full screen on a * monitor that has a resolution of 1600 x 1200 with a video that has dimensions of * 320 x 240 would scale the skin five times. If this property was set to 2.5, the player * would render the video (but not the skin) at 640 x 480, twice it's original size, and hardware acceleration * would do the remainder of the scaling (640 x 2.5 = 1600 and 480 x 2.5 = 1200).

    * *

    Setting this property after full screen mode has already * been entered has no effect until the next time FLVPlayback enters full screen * mode.

    * *

    If the FLV is large (for example, 640 pixels wide or more, 480 pixels * tall or more) you should not set this property to a small value because it * could cause noticeable performance problems on large monitors.

    * *

    Player Version: Flash Player 9 Update 3.

    * * @default 4.0 * * @see #enterFullScreenDisplayState() * @see flash.display.Stage#displayState * * @includeExample examples/FLVPlayback.skinScaleMaximum.1.as -noswf * * @langversion 3.0 * @internal Flash 9.0.xx.0 */ - public function get skinScaleMaximum () : Number; + public function get skinScaleMaximum () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set skinScaleMaximum (value:Number) : void; + public function set skinScaleMaximum (value:Number) : void; /** * Provides direct access to the * VideoPlayer.soundTransform property to expose * more sound control. You need to set this property for changes to take effect, * or you can get the value of this property to get a copy of the current settings. * * @see #volume * @see VideoPlayer#soundTransform * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get soundTransform () : SoundTransform; + public function get soundTransform () : SoundTransform; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set soundTransform (st:SoundTransform) : void; + public function set soundTransform (st:SoundTransform) : void; /** * A string that specifies the state of the component. This property is set by the * load(), play(), stop(), pause(), * and seek() methods. * *

    The possible values for the state property are: "buffering", "connectionError", * "disconnected", "loading", "paused", "playing", "rewinding", "seeking", and * "stopped". You can use the FLVPlayback class properties to test for * these states.

    * * @see VideoState#DISCONNECTED * @see VideoState#STOPPED * @see VideoState#PLAYING * @see VideoState#PAUSED * @see VideoState#BUFFERING * @see VideoState#LOADING * @see VideoState#CONNECTION_ERROR * @see VideoState#REWINDING * @see VideoState#SEEKING * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get state () : String; + public function get state () : String; /** * A Boolean value that is true if the state is responsive. If the state is * unresponsive, calls to the play(), load(), stop(), pause() and seek() * methods are queued and executed later, when the state changes to a * responsive one. Because these calls are queued and executed later, * it is usually not necessary to track the value of the stateResponsive * property. The responsive states are: * stopped, playing, paused, and buffering. * * @see VideoPlayer#stateResponsive * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get stateResponsive () : Boolean; + public function get stateResponsive () : Boolean; /** * The Stop button control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get stopButton () : Sprite; - public function set stopButton (s:Sprite) : void; + public function get stopButton () : Sprite; + public function set stopButton (s:Sprite) : void; /** * A Boolean value that is true if the state of the FLVPlayback instance is stopped. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get stopped () : Boolean; + public function get stopped () : Boolean; /** * A number that is the total playing time for the video in seconds. * *

    When streaming from Flash Media Server (FMS) and using the default * NCManager, this value is determined * automatically by server-side APIs, and that value * overrides anything set through this property or gathered * from metadata. The property is ready for reading when the * stopped or playing state is reached after setting the * source property. This property is meaningless for live streams * from a FMS.

    * *

    With an HTTP download, the value is determined * automatically if the FLV file has metadata embedded; otherwise, * set it explicitly or it will be NaN. If you set it * explicitly, the metadata value in the stream is * ignored.

    * *

    When you set this property, the value takes effect for the next * FLV file that is loaded by setting the source property. It has no effect * on an FLV file that has already loaded. Also, this property does not return * the new value passed in until an FLV file is loaded.

    * *

    Playback still works if this property is never set (either * explicitly or automatically), but it can cause problems * with seek controls.

    * *

    Unless set explicitly, the value will be NaN until it is set to a valid value from metadata.

    * * @see #source * @tiptext The total length of the FLV file in seconds * @helpid 3467 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get totalTime () : Number; + public function get totalTime () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set totalTime (aTime:Number) : void; + public function set totalTime (aTime:Number) : void; /** * A number that you can use to manage multiple FLV file streams. * Sets which video player instance is visible, audible, and * controlled by the skin or playback controls, while the rest * of the video players are hidden and muted. It does * not make the video player the * target for most APIs; use the activeVideoPlayerIndex property to do that. * *

    Methods and properties that control dimensions interact with this property. * The methods and properties that set the dimensions of the video player * (setScale(), setSize(), width, height, scaleX, scaleY) can be used * for all video players. However, depending on the value of the * scaleMode property * on those video players, they might have different dimensions. Reading * the dimensions using the width, height, scaleX, and scaleY * properties gives you * the dimensions only of the visible video player. Other video players might have * the same dimensions or might not.

    * *

    To get the dimensions of various video players when they are * not visible, listen for the layout event, and store the size * value.

    * *

    This property does not have any implications for visibility of the * component as a whole, only which video player is visible when the component is visible. * To set visibility for the entire component, use the visible property.

    * * @see #activeVideoPlayerIndex * @see flash.display.DisplayObject#visible DisplayObject.visible * * @default 0 * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get visibleVideoPlayerIndex () : uint; + public function get visibleVideoPlayerIndex () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set visibleVideoPlayerIndex (i:uint) : void; + public function set visibleVideoPlayerIndex (i:uint) : void; /** * A number in the range of 0 to 1 that indicates the volume control setting. * @default 1 * * @tiptext The volume setting in value range from 0 to 1. * @helpid 3468 * @see #soundTransform * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get volume () : Number; + public function get volume () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set volume (aVol:Number) : void; + public function set volume (aVol:Number) : void; /** * The volume bar control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get volumeBar () : Sprite; + public function get volumeBar () : Sprite; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set volumeBar (s:Sprite) : void; + public function set volumeBar (s:Sprite) : void; /** * A number that specifies, in milliseconds, how often * to check the volume bar handle location when scrubbing. * * @default 250 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get volumeBarInterval () : Number; + public function get volumeBarInterval () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set volumeBarInterval (s:Number) : void; + public function set volumeBarInterval (s:Number) : void; /** * A number that specifies how far a user can move the volume bar handle before * an update occurs. The value is expressed as a percentage from 1 to 100. Set to 0 * to indicate no scrub tolerance. Always update the volume on the * volumeBarInterval property regardless of how far the user moved the handle. * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - public function get volumeBarScrubTolerance () : Number; + public function get volumeBarScrubTolerance () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set volumeBarScrubTolerance (s:Number) : void; + public function set volumeBarScrubTolerance (s:Number) : void; /** * A number that specifies the width of the FLVPlayback instance on the Stage. * This property affects only the width of the FLVPlayback instance and does * not include the width of a skin SWF file that might be loaded. Use the * FLVPlayback width property and not the DisplayObject.width property because * the width property might give a different value if a skin SWF file is loaded. * Setting the width property also sets the registrationWidth property * to the same value. * * @see #setSize() * @helpid 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get width () : Number; + public function get width () : Number; /** * @private (setter) */ - public function set width (w:Number) : void; + public function set width (w:Number) : void; /** * @copy fl.video.VideoPlayer#x * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get x () : Number; + public function get x () : Number; /** * @private (setter) * */ - public function set x (x:Number) : void; + public function set x (x:Number) : void; /** * @copy fl.video.VideoPlayer#y * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get y () : Number; + public function get y () : Number; /** * @private (setter) * */ - public function set y (y:Number) : void; + public function set y (y:Number) : void; /** * Returns the next available tabIndex value after the FLVPlayback controls. The value is set after the assignTabIndexes method is called. * * @return the next available tabIndex after the FLVPlayback controls * * @see #assignTabIndexes() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get endTabIndex () : int; + public function get endTabIndex () : int; /** * Returns the first tabIndex value for the FLVPlayback controls. The value is set after the assignTabIndexes method is called. * * @return first tabIndex value for the FLVPlayback controls * * @see #assignTabIndexes() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get startTabIndex () : int; - + public function get startTabIndex () : int; + /** * Creates a new FLVPlayback instance. After creating the FLVPlayback * instance, call the addChild() or addChildAt() * method to place the instance on the Stage or another display object container. * * @see flash.display.DisplayObjectContainer#addChild() DisplayObjectContainer#addChild() * * @tiptext FLVPlayback constructor * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function FLVPlayback (); + public function FLVPlayback (); /** * Sets width and height simultaneously. Because setting either one, * individually, can cause automatic resizing, setting them simultaneously * is more efficient than setting the width and height * properties individually. * *

    If scaleMode property is set to * VideoScaleMode.MAINTAIN_ASPECT_RATIO or VideoScaleMode.NO_SCALE, then * calling this causes an immediate autolayout event.

    * * @param width A number that specifies the width of the video player. * * @param height A number that specifies the height of the video player. * * @see #width * @see #height * @see VideoScaleMode * * @tiptext setSize method * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setSize (width:Number, height:Number) : void; + public function setSize (width:Number, height:Number) : void; /** * Sets the scaleX and scaleY properties simultaneously. * Because setting either one, individually, can cause automatic * resizing, setting them simultaneously can be more efficient * than setting the scaleX and scaleY properties individually. * *

    If scaleMode property is set to * VideoScaleMode.MAINTAIN_ASPECT_RATIO or VideoScaleMode.NO_SCALE, then * calling this causes an immediate autolayout event.

    * * @param scaleX A number representing the horizontal scale. * @param scaleY A number representing the vertical scale. * * @see #scaleX * @see #scaleY * @see VideoScaleMode * * @tiptext setScale method * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setScale (scaleX:Number, scaleY:Number) : void; + public function setScale (scaleX:Number, scaleY:Number) : void; /** * handles events * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleAutoLayoutEvent (e:AutoLayoutEvent) : void; + function handleAutoLayoutEvent (e:AutoLayoutEvent) : void; /** * handles events * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleMetadataEvent (e:MetadataEvent) : void; + function handleMetadataEvent (e:MetadataEvent) : void; /** * handles events * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleVideoProgressEvent (e:VideoProgressEvent) : void; + function handleVideoProgressEvent (e:VideoProgressEvent) : void; /** * handles events * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleVideoEvent (e:VideoEvent) : void; + function handleVideoEvent (e:VideoEvent) : void; /** * Begins loading the FLV file and provides a shortcut for setting the * autoPlay property to false and setting the * source, totalTime, and isLive * properties, if given. If the totalTime and isLive * properties are undefined, they are not set. If the source * property is undefined, null, or an empty string, this method * does nothing. * * @param source A string that specifies the URL of the FLV file to stream * and how to stream it. The URL can be a local path, an HTTP URL to an FLV file, * an RTMP URL to an FLV file stream, or an HTTP URL to an XML file. * * @param totalTime A number that is the total playing time for the video. Optional. * * @param isLive A Boolean value that is true if the video stream is live. * This value is effective only when streaming from Flash Media Server (FMS) or other Flash * Video Streaming Service (FVSS). The value of * this property is ignored for an HTTP download. Optional. * * @see #autoPlay * @see #source * @see #isLive * @see #totalTime * * @tiptext load method * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function load (source:String, totalTime:Number = NaN, isLive:Boolean = false) : void; + public function load (source:String, totalTime:Number = NaN, isLive:Boolean = false) : void; /** * Plays the video stream. With no parameters, the method simply takes the FLV * file from a paused or stopped state to the playing state. * *

    If parameters are used, the method acts as a shortcut for setting the * autoPlay property to true and setting the isLive, * totalTime and, source * properties. If the totalTime and isLive properties are undefined, * they are not set.

    * *

    When waiting for enough of a progressive download FLV to load before playing * starts automatically, call the play() method with no parameters * to force playback to start immediately.

    * * @param source A string that specifies the URL of the FLV file to stream * and how to stream it. The URL can be a local path, an HTTP URL to an FLV file, * an RTMP URL to an FLV file stream, or an HTTP URL to an XML file. It is optional, * but the source property must be set either through the * Component inspector or through ActionScript or this method has no effect. * * @param totalTime A number that is the total playing time for the video. Optional. * * @param isLive A Boolean value that is true if the video stream is live. * This value is effective only when streaming from Flash Media Server (FMS) or other Flash Video Streaming Service (FVSS). * The value of this property is ignored for an HTTP download. Optional. * * @see #autoPlay * @see #source * @see #isLive * @see #totalTime * * @tiptext play method * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function play (source:String = null, totalTime:Number = NaN, isLive:Boolean = false) : void; + public function play (source:String = null, totalTime:Number = NaN, isLive:Boolean = false) : void; /** * Plays the FLV file when enough of it has downloaded. If the FLV file has * downloaded or you are streaming from Flash Media Server (FMS), then calling the * playWhenEnoughDownloaded() method * is identical to the play() method with no parameters. Calling this * method does not pause playback, so in many cases, you may want to call the pause() method * before you call this method. * * @tiptext playWhenEnoughDownloaded method * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function playWhenEnoughDownloaded () : void; + public function playWhenEnoughDownloaded () : void; /** * Pauses playing the video stream. * *

    If playback has begun and you want to * return to the state of waiting for enough to download and then automatically * begin playback, call the pause() method, and then the * playWhenEnoughDownloaded() method.

    * * @tiptext pause method * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function pause () : void; + public function pause () : void; /** * Stops the video from playing. * If the autoRewind property is true, * the FLV file rewinds to the beginning. * * @tiptext stop method * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function stop () : void; + public function stop () : void; /** * Seeks to a given time in the file, specified in seconds, * with a precision of three decimal places (milliseconds). * *

    For several reasons, the playheadTime property might not * have the expected value immediately after you call one of * the seek methods or set playheadTime to cause seeking. * First, for a progressive download, you can seek only to a * keyframe, so a seek takes you to the time of the first * keyframe after the specified time. (When streaming, a seek * always goes to the precise specified time even if the source * FLV file doesn't have a keyframe there.) Second, seeking * is asynchronous, so if you call a seek method or set the * playheadTime property, playheadTime does not update immediately. * To obtain the time after the seek is complete, listen for the * seek event, which does not start until the playheadTime property * has updated.

    * * @param time A number that specifies the time, in seconds, at which to * place the playhead. * * @throws fl.video.VideoError If time is < 0. * * @see VideoPlayer#seek() * * @tiptext seek method * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function seek (time:Number) : void; + public function seek (time:Number) : void; /** * Seeks to a given time in the file, specified in seconds, with a precision up to * three decimal places (milliseconds). This method performs the same operation as the * seek() method; it is provided for symmetry with the seekPercent() * method. * *

    For several reasons, the playheadTime property might not have the expected * value immediately after you call one of the seek methods or set playheadTime * to cause seeking. First, for a progressive download, you can seek only to a * keyframe, so a seek takes you to the time of the first keyframe after the * specified time. (When streaming, a seek always goes to the precise specified * time even if the source FLV file doesn't have a keyframe there.) Second, * seeking is asynchronous, so if you call a seek method or set the playheadTime * property, playheadTime does not update immediately. To obtain the time after * the seek is complete, listen for the seek event, which does not start until * the playheadTime property has updated.

    * * @param time A number that specifies the time, in seconds, * of the total play time at which to place the playhead. * * @see #seek() * * @tiptext seekSeconds method * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function seekSeconds (time:Number) : void; + public function seekSeconds (time:Number) : void; /** * Seeks to a percentage of the file and places the playhead there. * The percentage is a number between 0 and 100. * *

    For several reasons, the playheadTime property might not have * the expected value immediately after you call one of the seek * methods or set playheadTime to cause seeking. First, for * a progressive download, you can seek only to a keyframe, * so a seek takes you to the time of the first keyframe after * the specified time. (When streaming, a seek always goes * to the precise specified time even if the source FLV file * doesn't have a keyframe there.) Second, seeking is asynchronous, * so if you call a seek method or set the playheadTime property, * playheadTime does not update immediately. To obtain the time * after the seek is complete, listen for the seek event, which * does not start until the playheadTime property has updated.

    * * @param A number that specifies a percentage of the length of the FLV file * at which to place the playhead. * * @throws fl.video.VideoError If percent is invalid or if totalTime is * undefined, null or <= 0. * @see #seek() * * @tiptext seekPercent method * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function seekPercent (percent:Number) : void; + public function seekPercent (percent:Number) : void; /** * Seeks to a navigation cue point that matches the specified time, name, or * time and name. * *

    The time is the starting time, in seconds, * from which to look for the next navigation cue point. The default is the * current playheadTime property. If you specify a time, the method seeks * to a cue point that matches that time or is later. If time is undefined, * null, or less than 0, the method starts its * search at time 0.

    * *

    The name is the cue point to seek. The method seeks to the first enabled navigation * cue point with this name.

    * *

    The time and name together are a navigation cue point with the specified * name at or after the specified time. *

    * *

    For several reasons, the playheadTime property might not have the * expected value immediately after you call one of the seek methods or * set playheadTime to cause seeking. First, for a progressive * download, you can seek only to a keyframe, so a seek takes you * to the time of the first keyframe after the specified time. * (When streaming, a seek always goes to the precise specified * time even if the source FLV file doesn't have a keyframe there.) * Second, seeking is asynchronous, so if you call a seek method or * set the playheadTime property, playheadTime does not * update immediately. To obtain the time after the seek is complete, * listen for the seek event, * which does not start until the playheadTime property has updated.

    * * @param timeNameOrCuePoint A number that is the time, a string that is the name, or * both a number and string that are the specified name and time. * * @throws fl.video.VideoError No cue point matching the criteria is found. * @see #seek() * @see #seekToPrevNavCuePoint() * @see #seekToNextNavCuePoint() * @see #findCuePoint() * @see #isFLVCuePointEnabled() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function seekToNavCuePoint (timeNameOrCuePoint:*) : void; + public function seekToNavCuePoint (timeNameOrCuePoint:*) : void; /** * Seeks to the next navigation cue point, based on the current value of the * playheadTime property. The method skips navigation cue points that have * been disabled and goes to the end of the FLV file if there is no other cue point. * *

    For several reasons, the playheadTime property might not have the * expected value immediately after you call one of the seek methods or * set playheadTime to cause seeking. First, for a progressive * download, you can seek only to a keyframe, so a seek takes you * to the time of the first keyframe after the specified time. * (When streaming, a seek always goes to the precise specified * time even if the source FLV file doesn't have a keyframe there.) * Second, seeking is asynchronous, so if you call a seek method or * set the playheadTime property, playheadTime does not * update immediately. To obtain the time after the seek is complete, * listen for the seek event, * which does not start until the playheadTime property has updated.

    * * @param time A number that is the starting time, in seconds, from which to look for * the next navigation cue point. The default is the current playheadTime * property. Optional. * * @see #cuePoints * @see #seek() * @see #seekToNavCuePoint() * @see #seekToPrevNavCuePoint() * @see #findCuePoint() * @see #isFLVCuePointEnabled() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function seekToNextNavCuePoint (time:Number = NaN) : void; + public function seekToNextNavCuePoint (time:Number = NaN) : void; /** * Seeks to the previous navigation cue point, based on the current * value of the playheadTime property. It goes to the beginning if * there is no previous cue point. The method skips navigation cue * points that have been disabled. * *

    For several reasons, the playheadTime property might not have the * expected value immediately after you call one of the seek methods or * set playheadTime to cause seeking. First, for a progressive * download, you can seek only to a keyframe, so a seek takes you * to the time of the first keyframe after the specified time. * (When streaming, a seek always goes to the precise specified * time even if the source FLV file doesn't have a keyframe there.) * Second, seeking is asynchronous, so if you call a seek method or * set the playheadTime property, playheadTime does not * update immediately. To obtain the time after the seek is complete, * listen for the seek event, * which does not start until the playheadTime property has updated.

    * * @param time A number that is the starting time in seconds from which to * look for the previous navigation cue point. The default is the current * value of the playheadTime property. Optional. * * @see #cuePoints * @see #seek() * @see #seekToNavCuePoint() * @see #seekToNextNavCuePoint() * @see #findCuePoint() * @see #isFLVCuePointEnabled() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function seekToPrevNavCuePoint (time:Number = NaN) : void; + public function seekToPrevNavCuePoint (time:Number = NaN) : void; /** * Adds an ActionScript cue point and has the same effect as adding an ActionScript * cue point using the Cue Points dialog box, except that it occurs when an application * executes rather than during application development. * *

    Cue point information is wiped out when the source property is * set. To set cue point information for the next FLV file to be loaded, * set the source property first.

    * *

    It is valid to add multiple ActionScript cue points with the same name and time. * When you remove ActionScript cue points with the removeASCuePoint() * method, all cue points with the same name and time are removed.

    * * @param timeOrCuePoint An object having name and * time properties, which describe the cue point. It also might have a * parameters property that holds name/value pairs. It may have the * type property set * to "actionscript". If the type is missing or set to something else, it is set * automatically. If the object does not conform to these conventions, the * method throws a VideoError error. * *

    The time property sets the time in seconds for a new cue point * to be added and the name parameter must follow.

    * * @param name A string that specifies the name of the cue point if you submit * a time parameter instead of the cue point. * @param parameters Optional parameters for the cue point if the * timeOrCuePoint parameter is a number. * * @return The cue point object that was added. Edits to this * object affect the cuePoint event dispatch. * * @throws fl.video.VideoError Parameters are invalid. * * @see #findCuePoint() * @see #removeASCuePoint() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function addASCuePoint (timeOrCuePoint:*, name:String = null, parameters:Object = null) : Object; + public function addASCuePoint (timeOrCuePoint:*, name:String = null, parameters:Object = null) : Object; /** * Removes an ActionScript cue point from the currently loaded FLV file. * Only the name and time properties are used from the * timeNameOrCuePoint parameter to find the cue point to remove. * *

    If multiple ActionScript cue points match the search criteria, only one is removed. * To remove all, call this function repeatedly in a loop with the same parameters * until it returns null.

    * *

    Cue point information is wiped out when the source property is * set, so to set cue point information for the next FLV file to be loaded, set the * source property first.

    * * @param timeNameOrCuePoint A cue point string that contains the time and * name properties for the cue point to remove. The method removes the * first cue point with this name. * Or, if this parameter is a number, the method removes the * first cue point with this time. * If this parameter is an object, the method removes the cue point with both the * time and name properties. * * @return The cue point object that was removed. If there is no * matching cue point, the method returns null. * * * @see #addASCuePoint() * @see #findCuePoint() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function removeASCuePoint (timeNameOrCuePoint:*) : Object; + public function removeASCuePoint (timeNameOrCuePoint:*) : Object; /** * Finds the cue point of the type specified by the type parameter and * having the time, name, or combination of time and name that you specify * through the parameters. * *

    If you do not provide a value for either the time or name of the * cue point, or if the time is null, undefined, or less than zero * and the name is null or undefined, * the method throws VideoError error 1002.

    * *

    The method includes disabled cue points in the search. * Use the isFLVCuePointEnabled() method to determine * whether a cue point is disabled.

    * * @param timeNameOrCuePoint This can be a number specifying a time, a string * specifying a name, or an object with time and/or name properties. * *

    If this parameter is a string, the method searches for the * first cue point with this name and returns null if there is no match.

    * *

    If this parameter is a number, the method searches for and returns the first * cue point with this time. If there are multiple cue points with the same time, * which is possible only with ActionScript cue points, the cue point with the * first name alphabetically is returned. Returns null if there is no match. * The first three decimal places for the time are used. More than * three decimal places are rounded.

    * *

    If this parameter is an object, the method searches for the cue point object * that contains the specified time and/or name * properties. If only time or name is specified, then the behavior is the same * as calling with a number or a string. If both the time * and name properties are defined and a cue point object exists with both of them, * then the cue point object is returned; otherwise, null is returned.

    * *

    If time is null, NaN or less than 0 and name is null * or undefined, a VideoError object is thrown.

    * * @param type A string that specifies the type of cue point for which to * search. The possible values for this parameter are "actionscript", "all", "event", * "flv", or "navigation". You can specify these values using the following class * properties: CuePointType.ACTIONSCRIPT, CuePointType.ALL, CuePointType.EVENT, * CuePointType.FLV, and CuePointType.NAVIGATION. If this parameter * is not specified, the default is "all", which means the method * searches all cue point types. Optional. * * @return An object that is a copy of the found cue point object * with the following additional properties: * *
      * *
    • array—The array of cue points that were * searched. Treat this array as read-only because adding, removing, * or editing objects within it can cause cue points to malfunction.
    • * *
    • index—The index into the array for the returned cue point.
    • * *
    * *

    Returns null if no match is found.

    * * @throws fl.video.VideoError If the time property is null, * undefined or less than 0 and the name property is null * or undefined. * * @see #addASCuePoint() * @see #cuePoints * @see #findNearestCuePoint() * @see #findNextCuePointWithName() * @see #isFLVCuePointEnabled() * @see #removeASCuePoint() * @see #seekToNavCuePoint() * @see #seekToNextNavCuePoint() * @see #seekToPrevNavCuePoint() * @see #setFLVCuePointEnabled() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function findCuePoint (timeNameOrCuePoint:*, type:String = CuePointType.ALL) : Object; + public function findCuePoint (timeNameOrCuePoint:*, type:String = CuePointType.ALL) : Object; /** * Finds a cue point of the specified type that matches or is * earlier than the time that you specify. If you specify both * a time and a name and no earlier cue point matches that name, * it finds a cue point that matches the name that you specify. * Otherwise, it returns null. * Default is to search all cue points. * *

    The method includes disabled cue points in the search. Use * the isFLVCuePointEnabled() method to determine whether * a cue point is disabled.

    * * * @param timeNameOrCuePoint This can be a number specifying a time, a string * specifying a name, or an object with time and/or name properties. * *

    If this parameter is a string, the method searches for the * first cue point with this name and returns null if there is no match.

    * *

    If this parameter is a number then the closest cue point to this time that is * an exact match or earlier will be returned. If there is no cue point at or earlier * than that time, then the first cue point is returned. * If there are multiple cue points with the same time, * which is possible only with ActionScript cue points, the cue point with the * first name alphabetically is returned. Returns null if there is no match. * The first three decimal places for the time are used. More than * three decimal places are rounded.

    * *

    If this parameter is an object, the method searches for the cue point object * that contains the specified time and/or name * properties. If only time or name is specified, then the behavior is the same * as calling with a number or a string. If both the time * and name properties are defined and a cue point object exists with both of them, * then the cue point object is returned. Otherwise the nearest cue point with an * earlier time and the same name is returned. If no cue point earlier than that time * with that name is found null is returned.

    * *

    If time is null, undefined or less than 0 and name is null * or undefined, a VideoError object is thrown.

    * * @param type A string that specifies the type of cue point for which to * search. The possible values for this parameter are "actionscript", "all", "event", * "flv", or "navigation". You can specify these values using the following class * properties: CuePointType.ACTIONSCRIPT, CuePointType.ALL, CuePointType.EVENT, * CuePointType.FLV, and CuePointType.NAVIGATION. If this parameter * is not specified, the default is "all", which means the method * searches all cue point types. Optional. * * @return An object that is a copy of the found cue point * object with the following additional properties: * *
      * *
    • array—The array of cue points searched. * Treat this array as read-only as adding, removing or editing * objects within it can cause cue points to malfunction.
    • * *
    • index—The index into the array for the returned cue point.
    • *
    *

    Returns null if no match was found.

    * * * * @throws fl.video.VideoError If the time is null, undefined, or less * than 0 and the name is null or undefined. * * @see CuePointType#ALL * @see CuePointType#EVENT * @see CuePointType#NAVIGATION * @see CuePointType#FLV * @see CuePointType#ACTIONSCRIPT * @see #cuePoints * @see #addASCuePoint() * @see #removeASCuePoint() * @see #findCuePoint() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function findNearestCuePoint (timeNameOrCuePoint:*, type:String = CuePointType.ALL) : Object; + public function findNearestCuePoint (timeNameOrCuePoint:*, type:String = CuePointType.ALL) : Object; /** * Finds the next cue point in my_cuePoint.array that has the same name as * my_cuePoint.name. The my_cuePoint object must be a * cue point object that has been returned by the findCuePoint() method, the * findNearestCuePoint() method, or a previous call to this method. * This method uses the array parameter that these methods add to the * CuePoint object. * *

    The method includes disabled cue points in the search. Use the * isFLVCuePointEnabled() method to determine whether a cue point is disabled.

    * * @param cuePoint A cue point object that has been returned by either the * findCuePoint() method, * the findNearestCuePoint() method, or a previous call to this method. * * @return If there are no more cue points in the array with a matching * name, then null; otherwise, returns a * copy of the cue point object with additional properties: * *
      * *
    • array—The array of cue points searched. * Treat this array as read-only because adding, removing or * editing objects within it can cause cue points to malfunction.
    • * *
    • index—The index into the array for the returned cue point.
    • * *
    * * @throws fl.video.VideoError When argument is invalid. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function findNextCuePointWithName (cuePoint:Object) : Object; + public function findNextCuePointWithName (cuePoint:Object) : Object; /** * Enables or disables one or more FLV file cue points. Disabled cue points * are disabled for purposes of being dispatched as events and for navigating * to them with the seekToPrevNavCuePoint(), * seekToNextNavCuePoint(), and seekToNavCuePoint() methods. * *

    Cue point information is deleted when you set the source * property to a different FLV file, so set the source property before * setting cue point information for the next FLV file to be loaded.

    * *

    Changes caused by this method are not reflected by calls to the * isFLVCuePointEnabled() method until metadata is loaded.

    * * @param enabled A Boolean value that specifies whether to enable (true) * or disable (false) an FLV file cue point. * * @param timeNameOrCuePoint If this parameter is a string, the method enables or disables * the cue point with this name. If this parameter is a number, the method enables or * disables the cue point with this time. If this parameter is an object, the method * enables or disables the cue point with both the name and time * properties. * * @return If metadataLoaded is true, the method returns the * number of cue points whose enabled state was changed. If * metadataLoaded is false, the method returns -1 because the * component cannot yet determine which, if any, cue points to set. * When the metadata arrives, however, the component sets the specified cue points appropriately. * * @see #cuePoints * @see #isFLVCuePointEnabled() * @see #findCuePoint() * @see #findNearestCuePoint() * @see #findNextCuePointWithName() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setFLVCuePointEnabled (enabled:Boolean, timeNameOrCuePoint:*) : Number; + public function setFLVCuePointEnabled (enabled:Boolean, timeNameOrCuePoint:*) : Number; /** * Returns false if the FLV file embedded cue point is disabled. * You can disable cue points either by setting the cuePoints property through * the Flash Video Cue Points dialog box or by calling the * setFLVCuePointEnabled() method. * *

    The return value from this function is meaningful only when the * metadataLoaded property is true, the * metadata property is not null, or after a * metadataReceived event. When metadataLoaded is * false, this function always returns true.

    * * @param timeNameOrCuePoint If this parameter is a string, returns the name of * the cue point to check; returns false only if all cue points with * this name are disabled. * *

    If this parameter is a number, it is the time of the cue point to check.

    * *

    If this parameter is an object, returns the object with the matching * name and time properties.

    * * @return Returns false if the FLV file embedded cue point is disabled. * You can disable cue points either by setting the cuePoints property through the * Flash Video Cue Points dialog box or by calling the setFLVCuePointEnabled() method. * *

    The return value from this function is meaningful only when the * metadataLoaded property is true, the metadata * property is not null, or after a * metadataReceived event. When metadataLoaded is false, * this function always returns true.

    * * * @see #findCuePoint() * @see #findNearestCuePoint() * @see #findNextCuePointWithName() * @see #setFLVCuePointEnabled() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function isFLVCuePointEnabled (timeNameOrCuePoint:*) : Boolean; + public function isFLVCuePointEnabled (timeNameOrCuePoint:*) : Boolean; /** * Brings a video player to the front of the stack of video players. * Useful for custom transitions between video players. The default stack * order is the same as it is for the activeVideoPlayerIndex property: * 0 is on the bottom, 1 is above it, 2 is above 1, and so on. However, when you * call the bringVideoPlayerToFront() method this order may change. For * example, 2 may be the bottom. * * @param index A number that is the index of the video player to move to the front. * * @see #activeVideoPlayerIndex * @see #getVideoPlayer() * @see VideoPlayer * @see #visibleVideoPlayerIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function bringVideoPlayerToFront (index:uint) : void; + public function bringVideoPlayerToFront (index:uint) : void; /** * Gets the video player specified by the index parameter. * When possible, it is best to access the VideoPlayer methods and properties * using FLVPlayback methods and properties. Each DisplayObject.name property * is its index converted to a string. * * @param index A number that is the index of the video player to get. * * @return A VideoPlayer object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getVideoPlayer (index:Number) : VideoPlayer; + public function getVideoPlayer (index:Number) : VideoPlayer; /** * Closes NetStream and deletes the video player specified by the index * parameter. If the closed video player is the active or visible video player, * the FLVPlayback instance sets the active and or visible video player to the * default player (with index 0). You cannot close the default player, and * trying to do so causes the component to throw an error. * * @param index A number that is the index of the video player to close. * * @see #activeVideoPlayerIndex * @see #event:close close event * @see #visibleVideoPlayerIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function closeVideoPlayer (index:uint) : void; + public function closeVideoPlayer (index:uint) : void; /** * Sets the FLVPlayback video player to full screen. Calling this method has * the same effect as clicking the full screen toggle button that's built into some * FLVPlayback skins and is also available as the FullScreenButton in the Video section * of the Components panel. * *

    This method supports hardware acceleration in Flash Player for * full screen video. If the user's version of Flash Player does not support * hardware acceleration, this method still works and full screen video will work * the same as it does without hardware acceleration support.

    * *

    Because a call to this method sets the displayState property of the * Stage class to StageDisplayState.FULL_SCREEN, it has * the same restrictions as the displayState property. * * If, instead of calling this method, you implement full screen mode by directly setting the * stage.displayState property to StageDisplayState.FULL_SCREEN, * hardware acceleration is not used.

    * *

    Full screen support occurs only if the fullScreenTakeOver * property is set to true, which it is by default.

    * *

    Player Version: Flash Player 9 Update 3.

    * * @see #fullScreenTakeover * @see #skinScaleMaximum * @see flash.display.Stage#displayState * * @includeExample examples/FLVPlayback.enterFullScreenDisplayState.1.as -noswf * * @langversion 3.0 * @internal Flash 9.0.xx.0 */ - public function enterFullScreenDisplayState () : void; + public function enterFullScreenDisplayState () : void; /** * Creates and configures VideoPlayer movie clip. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function createVideoPlayer (index:Number) : void; + function createVideoPlayer (index:Number) : void; /** * Creates live preview placeholder. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function createLivePreviewMovieClip () : void; + private function createLivePreviewMovieClip () : void; /** * Handles load of live preview image * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function onCompletePreview (e:Event) : void; + private function onCompletePreview (e:Event) : void; /** * Called on onEnterFrame to initiate loading the new * source url. We delay to give the user time to set other * vars as well. Only done this way when source set from the * component inspector or property inspector, not when set with AS. * * @see #source * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function doContentPathConnect (eventOrIndex:*) : void; + private function doContentPathConnect (eventOrIndex:*) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function showFirstStream () : void; + function showFirstStream () : void; /** * Called by UIManager when SeekBar scrubbing starts * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function _scrubStart () : void; + function _scrubStart () : void; /** * Called by UIManager when seekbar scrubbing finishes * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function _scrubFinish () : void; + function _scrubFinish () : void; /** * Called by UIManager when skin errors * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function skinError (message:String) : void; + function skinError (message:String) : void; /** * Called by UIManager when skin loads * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function skinLoaded () : void; + function skinLoaded () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function showSkinNow (e:TimerEvent) : void; + function showSkinNow (e:TimerEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function queueCmd (vpState:VideoPlayerState, type:Number, time:Number = NaN) : void; + function queueCmd (vpState:VideoPlayerState, type:Number, time:Number = NaN) : void; /** * Assigns a tabIndex value to each of the FLVPlayback controls by sorting * them by position horizontally left to right. This method returns the next available tabIndex value. * *

    If you call assignTabIndexes with NaN as the startTabbing * parameter and the FLVPlayback component instance has a tabIndex value assigned to it, * the method will use the FLVPlayback component instance's assigned tabIndex as the startTabIndex.

    *

    When an FLVPlayback skin is specified, you should wait a frame after the FLVPlayback.SKIN_LOADED event * to allow the skin controls to initialize before calling this method.

    * *

    When using custom controls, wait a frame after the FLVPlayback.READY event to allow * the custom controls to initialize befor calling this method.

    * * @param startTabbing The starting tabIndex for FLVPlayback controls. * * @return The next available tabIndex after the FLVPlayback controls. * * @see #endTabIndex * @see #startTabIndex * * @includeExample examples/FLVPlaybackTabIndexExample.as -noswf * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function assignTabIndexes (startTabIndex:int) : int; - } -} + public function assignTabIndexes (startTabIndex:int) : int; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FLVPlaybackCaptioning.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FLVPlaybackCaptioning.as index d8d35f12e1..4bbd5c3cdc 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FLVPlaybackCaptioning.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FLVPlaybackCaptioning.as @@ -1,362 +1,362 @@ -package fl.video -{ - import flash.ui.Keyboard; - import flash.accessibility.Accessibility; - import flash.accessibility.AccessibilityProperties; - import flash.display.*; - import flash.events.*; - import flash.text.*; - import flash.geom.Rectangle; - import flash.geom.Point; - import flash.system.Capabilities; - import flash.utils.*; - +package fl.video +{ + import flash.ui.Keyboard; + import flash.accessibility.Accessibility; + import flash.accessibility.AccessibilityProperties; + import flash.display.*; + import flash.events.*; + import flash.text.*; + import flash.geom.Rectangle; + import flash.geom.Point; + import flash.system.Capabilities; + import flash.utils.*; + /** * Dispatched when a caption is added or removed from the caption target * text field. * *

    The event is also dispatched when the following conditions are true:

    *
      *
    • the captionTargetName property is not set
    • *
    • the captionTarget property is not set
    • *
    • the FLVPlaybackCaptioning instance creates a TextField object automatically for captioning.
    • *
    * *

    The captionChange event has the constant * CaptionChangeEvent.CAPTION_CHANGE.

    * * * @see #captionTargetName * @see #captionTarget * @tiptext captionChange event * @eventType fl.video.CaptionChangeEvent.CAPTION_CHANGE * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("captionChange", type="fl.video.CaptionChangeEvent")] + [Event("captionChange", type="fl.video.CaptionChangeEvent")] /** * Dispatched after the captionTarget property is created, * but before any captions are added (the captionTarget property * is empty). * *

    If the captionTarget property is set with a custom * DisplayObject, or if the captionTargetName property is * set, this event does not dispatch.

    * *

    Listen for this event if you are customizing the * properties of the TextField object, for example, the defaultTextFormat property.

    * *

    The captionTargetCreated event has the constant * CaptionTargetEvent.CAPTION_TARGET_CREATED.

    * * * @see #captionTargetName * @see #captionTarget * @see flash.display.DisplayObject * @tiptext captionTargetCreated event * @eventType fl.video.CaptionTargetEvent.CAPTION_TARGET_CREATED * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("captionTargetCreated", type="fl.video.CaptionTargetEvent")] + [Event("captionTargetCreated", type="fl.video.CaptionTargetEvent")] /** * Dispatched after all of the Timed Text XML data is loaded. * * @see flash.net.URLLoader#event:complete URLLoader.complete event * * @eventType flash.events.Event.COMPLETE * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("complete", type="flash.events.Event")] + [Event("complete", type="flash.events.Event")] /** * Dispatched if a call to the URLLoader.load() event attempts to access a Timed Text XML file * over HTTP and the current Flash Player environment is able to detect * and return the status code for the request. * * @see flash.net.URLLoader#event:httpStatus URLLoader.httpStatus event * @eventType flash.events.HTTPStatusEvent.HTTP_STATUS * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("httpStatus", type="flash.events.HTTPStatusEvent")] + [Event("httpStatus", type="flash.events.HTTPStatusEvent")] /** * Dispatched if a call to the URLLoader.load() event results in a fatal error * that terminates the download of the Timed Text XML file. * *

    If this event is not handled, it will throw an error.

    * * @see flash.net.URLLoader#event:ioError URLLoader.ioError event * @eventType flash.events.IOErrorEvent.IO_ERROR * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("ioError", type="flash.events.IOErrorEvent")] + [Event("ioError", type="flash.events.IOErrorEvent")] /** * Dispatched when the download operation to load the Timed Text XML file * begins, following a call to the URLLoader.load() method. * * @see flash.net.URLLoader#event:open URLLoader.open event * @eventType flash.events.Event.OPEN * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("open", type="flash.events.Event")] + [Event("open", type="flash.events.Event")] /** * Dispatched when data is received as the download of the * Timed Text XML file progresses. * * @see flash.net.URLLoader#event:progress URLLoader.progress event * @eventType flash.events.ProgressEvent.PROGRESS * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("progress", type="flash.events.ProgressEvent")] + [Event("progress", type="flash.events.ProgressEvent")] /** * Dispatched if a call to the URLLoader.load() event attempts to load a * Timed Text XML file from a server outside the security sandbox. * *

    If this event is not handled, it will throw an error.

    * * @see flash.net.URLLoader#event:securityError URLLoader.securityError event * @eventType flash.events.SecurityErrorEvent.SECURITY_ERROR * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - [Event("securityError", type="flash.events.SecurityErrorEvent")] - + [Event("securityError", type="flash.events.SecurityErrorEvent")] + /** The FLVPlaybackCaptioning component enables captioning for the FLVPlayback component. * * *
    * NOTE: This documentation is intended for use with the FLVPlaybackCaptioning with Accessibility component. *

    It updates the ActionScript 3.0 Language and Components Reference for the FLVPlaybackCaptioning class to include the following * properties and methods which were added to improve the component's accessibility.

    *
    * * *

    Make sure you are including the " with Accessibility" version of the component in your project * before attempting to access the new properties or methods.

    *
    * * *

    The FLVPlaybackCaptioning component downloads a Timed Text (TT) XML file * and applies those captions to an FLVPlayback component to which this * component is partnered.

    *

    For more information on Timed Text format, see * http://www.w3.org/AudioVideo/TT/. The FLVPlaybackCaptioning component * supports a subset of the * Timed Text 1.0 specification. For detailed information on the supported subset, see * Timed Text Tags. The following is a * brief example:

    * *
    	 * <?xml version="1.0" encoding="UTF-8"?>
    	 * <tt xml:lang="en" xmlns="http://www.w3.org/2006/04/ttaf1"  xmlns:tts="http://www.w3.org/2006/04/ttaf1#styling">
    	 *     <head>
    	 *         <styling>
    	 *             <style id="1" tts:textAlign="right"/>
    	 *             <style id="2" tts:color="transparent"/>
    	 *             <style id="3" style="2" tts:backgroundColor="white"/>
    	 *             <style id="4" style="2 3" tts:fontSize="20"/>
    	 *         </styling>
    	 *     </head>
    	 *     <body>
    	 *          <div xml:lang="en">
    	 *             <p begin="00:00:00.50" dur="500ms">Four score and twenty years ago</p>
    	 *             <p begin="00:00:02.50"><span tts:fontFamily="monospaceSansSerif,proportionalSerif,TheOther"tts:fontSize="+2">our forefathers</span> brought forth<br /> on this continent</p>
    	 *             <p begin="00:00:04.40" dur="10s" style="1">a <span tts:fontSize="12 px">new</span> <span tts:fontSize="300%">nation</span></p>
    	 *             <p begin="00:00:06.50" dur="3">conceived in <span tts:fontWeight="bold" tts:color="#ccc333">liberty</span> <span tts:color="#ccc333">and dedicated to</span> the proposition</p>
    	 *             <p begin="00:00:11.50" tts:textAlign="right">that <span tts:fontStyle="italic">all</span> men are created equal.</p>
    	 * 			<p begin="15s" style="4">The end.</p>
    	 *         </div>    
    	 *     </body>
    	 * </tt>
    	 * 
    * * @includeExample examples/FLVPlaybackCaptioningExample.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class FLVPlaybackCaptioning extends Sprite - { + public class FLVPlaybackCaptioning extends Sprite + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var ttm : TimedTextManager; + local var ttm : TimedTextManager; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var visibleCaptions : Array; + local var visibleCaptions : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var hasSeeked : Boolean; + local var hasSeeked : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var flvPos : Rectangle; + local var flvPos : Rectangle; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var prevCaptionTargetHeight : Number; + local var prevCaptionTargetHeight : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var captionTargetOwned : Boolean; + local var captionTargetOwned : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var captionTargetLastHeight : Number; + local var captionTargetLastHeight : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var captionToggleButton : Sprite; + local var captionToggleButton : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var onButton : Sprite; + local var onButton : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var offButton : Sprite; + local var offButton : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var captionToggleButtonWaiting : Sprite; + local var captionToggleButtonWaiting : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - static const AUTO_VALUE : String = "auto"; + static const AUTO_VALUE : String = "auto"; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _captionTarget : TextField; + local var _captionTarget : TextField; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _captionTargetContainer : DisplayObjectContainer; + local var _captionTargetContainer : DisplayObjectContainer; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var cacheCaptionTargetParent : DisplayObjectContainer; + local var cacheCaptionTargetParent : DisplayObjectContainer; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var cacheCaptionTargetIndex : int; + local var cacheCaptionTargetIndex : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var cacheCaptionTargetAutoLayout : Boolean; + local var cacheCaptionTargetAutoLayout : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var cacheCaptionTargetLocation : Rectangle; + local var cacheCaptionTargetLocation : Rectangle; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var cacheCaptionTargetScaleY : Number; + local var cacheCaptionTargetScaleY : Number; /** * Used when keeing flvplayback skin above the caption * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var skinHijacked : Boolean; - private var _autoLayout : Boolean; - private var _captionsOn : Boolean; - private var _captionURL : String; - private var _flvPlaybackName : String; - private var _flvPlayback : FLVPlayback; - private var _captionTargetName : String; - private var _videoPlayerIndex : uint; - private var _limitFormatting : Boolean; - private var _track : uint; - private var _captionsOnCache : Boolean; - + local var skinHijacked : Boolean; + private var _autoLayout : Boolean; + private var _captionsOn : Boolean; + private var _captionURL : String; + private var _flvPlaybackName : String; + private var _flvPlayback : FLVPlayback; + private var _captionTargetName : String; + private var _videoPlayerIndex : uint; + private var _limitFormatting : Boolean; + private var _track : uint; + private var _captionsOnCache : Boolean; + /** * Used to display captions; true = display captions, * false = do not display captions. * *

    If you use the captionButton property to allow the * user to turn captioning on and off, set the showCaptions * property to false.

    * * @default true * * @see #captionButton * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get showCaptions () : Boolean; + public function get showCaptions () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set showCaptions (b:Boolean) : void; + public function set showCaptions (b:Boolean) : void; /** * URL of the Timed Text XML file that contains caption information (required property). * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get source () : String; + public function get source () : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set source (url:String) : void; + public function set source (url:String) : void; /** * Determines whether the FLVPlaybackCaptioning component * automatically moves and resizes the TextField object for captioning. * * *

    If the autoLayout property is set to true, the DisplayObject instance or * the TextField object containing the captions displays 10 pixels from the bottom * of the FLVPlayback instance. The captioning area covers the width of * the FLVPlayback instance, maintaining a margin of 10 pixels on each side.

    * *

    When this property is set to true, the DisplayObject instance * or TextField object displays directly over the FLVPlayback instance. * If you are creating your own TextField object, you should set * autoLayout to false. * If wordWrap = false, the captioning area centers over the FLVPlayback * instance, but it can be wider than the FLVPlayback instance.

    * *

    To control layout, you need to listen for the captionChange event to * determine when the TextField object instance is created.

    * * @default true * * @see #captionTarget * @see #event:captionChange captionChange event * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get autoLayout () : Boolean; + public function get autoLayout () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set autoLayout (b:Boolean) : void; + public function set autoLayout (b:Boolean) : void; /** * The instance name of the TextField object or MovieClip enclosing a Textfield object * that contains the captions. * *

    To specify no target, set this property to an empty string (that is, no target specified) * or auto. This property is primarily used * in the Component inspector. If you are writing code, use the * captionTarget property instead.

    * * @default auto * * @see #captionTarget * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get captionTargetName () : String; + public function get captionTargetName () : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set captionTargetName (tname:String) : void; + public function set captionTargetName (tname:String) : void; /** * Sets the DisplayObject instance in which to display captions. * *

    If you set the instance as a TextField object, it is targeted directly. * If you set the instance as a DisplayObjectContainer * containing one or more TextField objects, the captions display in the * TextField object with the lowest display index.

    * *

    The DisplayObjectContainer method supports a movie-clip like object * with a scale-9 background, which can be scaled when the TextField object size changes.

    * *

    For more complex scaling and drawing, write code to have the * DisplayObjectContainer method listen for a captionChange event.

    *

    Note If the captionTargetName or the captionTarget property * is not set, the FLVPlaybackCaptioning instance creates a text field set by the * captionTarget property with this formatting:

    * *
      *
    • black background (background = true; backgroundColor = 0x000000;)
    • *
    • white text (textColor = 0xFFFFFF)
    • *
    • autoSize = TextFieldAutoSize.LEFT
    • *
    • multiLine = true
    • *
    • wordWrap = true
    • *
    • font = "_sans"
    • *
    • size = 12
    • *
    * *

    To customize these values, listen for the captionTargetCreated event.

    * * * @see #captionTargetName * @see flash.display.DisplayObjectContainer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get captionTarget () : DisplayObject; + public function get captionTarget () : DisplayObject; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set captionTarget (ct:DisplayObject) : void; + public function set captionTarget (ct:DisplayObject) : void; /** * Defines the captionButton FLVPlayback custom UI component instance * which provides toggle capabilities to turn captioning on and off. * *

    The captionButton property functions similarly to the FLVPlayback * properties playButton, * pauseButton, muteButton, and so on.

    * * @see FLVPlayback * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - public function get captionButton () : Sprite; - public function set captionButton (s:Sprite) : void; + public function get captionButton () : Sprite; + public function set captionButton (s:Sprite) : void; /** * Sets an FLVPlayback instance name for the FLVPlayback instance * that you want to caption. * *

    To specify no target, set this to an empty string or auto. * The FLVPlayback instance must have the same * parent as the FLVPlaybackCaptioning instance.

    * *

    The FLVPlayback instance name is primarily used in * the Component inspector. If you are writing code, * use the flvPlayback property.

    * *

    If the flvPlaybackName or * the flvPlayback property is not set or set to auto, * the FLVPlaybackCaptioning instance searches for a FLVPlayback * instance with the same parent and captions the first one it finds.

    * * @default auto * * @see FLVPlayback FLVPlayback class * @see #flvPlayback flvPlayback property * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get flvPlaybackName () : String; + public function get flvPlaybackName () : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set flvPlaybackName (flvname:String) : void; + public function set flvPlaybackName (flvname:String) : void; /** * Sets the FLVPlayback instance to caption. The FLVPlayback * instance must have the same parent as the * FLVPlaybackCaptioning instance. *

    If the * flvPlaybackName or * flvPlayback property is not set, the * FLVPlaybackCaptioning instance will look for a FLVPlayback * instance with the same parent and caption the first one it * finds.

    * * @see #flvPlaybackName * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get flvPlayback () : FLVPlayback; + public function get flvPlayback () : FLVPlayback; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set flvPlayback (fp:FLVPlayback) : void; + public function set flvPlayback (fp:FLVPlayback) : void; /** * Support for multiple language tracks. * *

    The best utilization of the track property * is to support multiple language tracks with * embedded cue points.

    * *

    You must follow the supported formats for FLVPlaybackCaptioning * cue points.

    * *

    If the track property is set to something other than 0, * the FLVPlaybackCaptioning component searches for a text<n> property on the cue point, * where n is the track value.

    * *

    For example, if track == 1, then the FLVPlayBackCaptioning component * searches for the parameter text1 on the cue point. If * no matching parameter is found, the text property in the cue point parameter is used.

    * * @default 0 * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get track () : uint; + public function get track () : uint; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set track (i:uint) : void; + public function set track (i:uint) : void; /** * Connects the captioning to a specific VideoPlayer in the * FLVPlayback component. * *

    If you want to use captioning in * multiple video players (using the activeVideoPlayerIndex * and visibleVideoPlayerIndex properties in the FLVPlayback * component), you * should create one instance of the FLVPlaybackCaptioning * component for each VideoPlayer that you will be using and set * this property to correspond to the index.

    * *

    The VideoPlayer index defaults to * 0 when only one video player is used.

    * * @see FLVPlayback#activeVideoPlayerIndex * @see FLVPlayback#visibleVideoPlayerIndex * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get videoPlayerIndex () : uint; + public function get videoPlayerIndex () : uint; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set videoPlayerIndex (v:uint) : void; + public function set videoPlayerIndex (v:uint) : void; /** * Limits formatting instructions * from the Timed Text file when set to true. * *

    The following styles are not supported if the simpleFormatting * property is set to true:

    * *
      *
    • tts:backgroundColor
    • *
    • tts:color
    • *
    • tts:fontSize
    • *
    • tts:fontFamily
    • *
    • tts:wrapOption
    • *
    * *

    The following styles are supported if the simpleFormatting * property is set to true:

    * *
      *
    • tts:fontStyle
    • *
    • tts:fontWeight
    • *
    • tts:textAlign
    • *
    * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get simpleFormatting () : Boolean; + public function get simpleFormatting () : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set simpleFormatting (b:Boolean) : void; - + public function set simpleFormatting (b:Boolean) : void; + /** * Creates a new FLVPlaybackCaptioning instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function FLVPlaybackCaptioning (); + public function FLVPlaybackCaptioning (); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function forwardEvent (e:Event) : void; + function forwardEvent (e:Event) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function startLoad (e:Event) : void; + function startLoad (e:Event) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function hookupCaptionToggle (e:Event) : void; + function hookupCaptionToggle (e:Event) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleCaption (e:MetadataEvent) : void; + function handleCaption (e:MetadataEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleStateChange (e:VideoEvent) : void; + function handleStateChange (e:VideoEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleComplete (e:VideoEvent) : void; + function handleComplete (e:VideoEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handlePlayheadUpdate (e:VideoEvent) : void; + function handlePlayheadUpdate (e:VideoEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleSkinLoad (e:VideoEvent) : void; + function handleSkinLoad (e:VideoEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleAddedToStage (e:Event) : void; + function handleAddedToStage (e:Event) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleFullScreenEvent (e:FullScreenEvent) : void; + function handleFullScreenEvent (e:FullScreenEvent) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function enterFullScreenTakeOver () : void; + function enterFullScreenTakeOver () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function exitFullScreenTakeOver () : void; + function exitFullScreenTakeOver () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function cleanupCaptionButton () : void; + function cleanupCaptionButton () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function setupButton (ctrl:Sprite, prefix:String, vis:Boolean) : Sprite; + function setupButton (ctrl:Sprite, prefix:String, vis:Boolean) : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleButtonClick (e:MouseEvent) : void; + function handleButtonClick (e:MouseEvent) : void; /** * This function stolen from UIManager and tweaked. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function setupButtonSkin (prefix:String) : Sprite; + function setupButtonSkin (prefix:String) : Sprite; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function removeOldCaptions (playheadTime:Number, removedCaptionsIn:Array = null) : void; + function removeOldCaptions (playheadTime:Number, removedCaptionsIn:Array = null) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function findFLVPlayback () : void; + function findFLVPlayback () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function createCaptionTarget () : void; + function createCaptionTarget () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function layoutCaptionTarget (e:LayoutEvent = null) : void; + function layoutCaptionTarget (e:LayoutEvent = null) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function addFLVPlaybackListeners () : void; + function addFLVPlaybackListeners () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function removeFLVPlaybackListeners () : void; + function removeFLVPlaybackListeners () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function getCaptionText (cp:Object) : String; + function getCaptionText (cp:Object) : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function displayCaptionNow () : void; + function displayCaptionNow () : void; /** * Keeps screen reader from reading captionTarget * * @private */ - function silenceCaptionTarget () : void; + function silenceCaptionTarget () : void; /** * Defines accessibility properties for caption toggle buttons * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function setupCaptionButtonAccessibility () : void; + function setupCaptionButtonAccessibility () : void; /** * Handles keyboard events for accessibility * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function handleKeyEvent (e:KeyboardEvent) : void; + function handleKeyEvent (e:KeyboardEvent) : void; /** * Handles a mouse focus change event and forces focus on the appropriate control. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - private function handleMouseFocusChangeEvent (event:FocusEvent) : void; + private function handleMouseFocusChangeEvent (event:FocusEvent) : void; /** * Returns a string containing all captions as an HTML-formatted transcript. *

    Each caption is contained within a p tag with the class attribute "fl_video_caption," * a unique id attribute starting with the string "fl_video_caption_2_0_," * and a title attribute indicating the timecode at which the caption appears in the video.

    *

    Following is a brief example of the HTML returned:

    *
    		 * <div id="fl_video_transcript" class="fl_video_transcript">
    		 * 	<p class="fl_video_caption" id="fl_video_caption_2_0_1" title="0:00.50"><i>( speaking French ): </i><br/><b>George: </b> Bonjour, Marie.</p>
    		 * 	<p class="fl_video_caption" id="fl_video_caption_2_0_2" title="0:01.75"><b>Marie: </b> Bonjour, George.</p>
    		 * 	<p class="fl_video_caption" id="fl_video_caption_2_0_3" title="0:03.75">Voilà une sucette.</p>
    		 * 	<p class="fl_video_caption" id="fl_video_caption_2_0_4" title="0:05.50"><b>George: </b> C'est pour moi?</p>
    		 * 	<p class="fl_video_caption" id="fl_video_caption_2_0_5" title="0:06.50"><b>Marie: </b> Oui, c'est pour toi.</p>
    		 * 	<p class="fl_video_caption" id="fl_video_caption_2_0_6" title="0:08.00"><b>George: </b> Merci, Marie!</p>
    		 * 	<p class="fl_video_caption" id="fl_video_caption_2_0_7" title="0:09.50"><b>Marie: </b> De rien, George.</p>
    		 * </div>
    		 * 
    * * @param preserveFormatting Preserves the HTML tags used to format the caption text in Flash * * @return String A string containing all captions as an HTML-formatted transcript * * @includeExample examples/FLVPlaybackCaptioning.getCaptionsAsTranscript.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getCaptionsAsTranscript (preserveFormatting:Boolean = false) : String; + public function getCaptionsAsTranscript (preserveFormatting:Boolean = false) : String; /** * Returns an array of FLVPlayback component cuepoints that contain the captions. * * @return Array An array of FLVPlayback component cuepoints * * @includeExample examples/FLVPlaybackCaptioning.getCaptionsAsArray.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getCaptionsAsArray () : Array; + public function getCaptionsAsArray () : Array; /** * Returns a number of seconds as a timecode string. * * @param sec A number of seconds. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function secondsToTime (sec:Number) : String; + public function secondsToTime (sec:Number) : String; /** * Returns an array of FLVPlayback component cuepoints whose caption text contains the search string. * * @param searchString A string to search for in the captions text. * * @return Array An array of FLVPlayback component cuepoints * * @includeExample examples/FLVPlaybackCaptioning.findInCaptions.1.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function findInCaptions (searchString:String) : Array; - } -} + public function findInCaptions (searchString:String) : Array; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FPADManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FPADManager.as index e00760a673..fee8bd7526 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FPADManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/FPADManager.as @@ -1,33 +1,33 @@ -package fl.video -{ - import flash.net.URLLoader; - import flash.net.URLRequest; - import flash.events.*; - +package fl.video +{ + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.events.*; + /** *

    Handles downloading and parsing fpad xml format for * fl.video.NCManager. This xml format is generated by FMS 2.0.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class FPADManager - { - private var _owner : INCManager; - local var xml : XML; - local var xmlLoader : URLLoader; - local var rtmpURL : String; - local var _url : String; - local var _uriParam : String; - local var _parseResults : ParseResults; - + public class FPADManager + { + private var _owner : INCManager; + local var xml : XML; + local var xmlLoader : URLLoader; + local var rtmpURL : String; + local var _url : String; + local var _uriParam : String; + local var _parseResults : ParseResults; + /** * constructor * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function FPADManager (owner:INCManager); + public function FPADManager (owner:INCManager); /** *

    Starts download of XML file. Will be parsed and based * on that we will decide how to connect.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function connectXML (urlPrefix:String, uriParam:String, urlSuffix:String, uriParamParseResults:ParseResults) : Boolean; + function connectXML (urlPrefix:String, uriParam:String, urlSuffix:String, uriParamParseResults:ParseResults) : Boolean; /** *

    Handles load of XML. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function xmlLoadEventHandler (e:Event) : void; - } -} + function xmlLoadEventHandler (e:Event) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/INCManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/INCManager.as index ec860dbfd1..5df4be888b 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/INCManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/INCManager.as @@ -1,88 +1,88 @@ -package fl.video -{ - import flash.net.NetConnection; - +package fl.video +{ + import flash.net.NetConnection; + /** * The INCManager is the interface for classes that create the flash.net.NetConnection * for the VideoPlayer class. The default INCManager implementation is the NCManager class. * Use the NCManagerNative class when streaming from a Flash Media Server (FMS). * You can also create a custom class that implements the INCManager interface and * then have the VideoPlayer class use that class to create the NetConnection. * *

    Use the following code to register a custom class as the INCManager implementation * used by the VideoPlayer object. * Replace fl.video.NCManagerNative with your custom class.

    * * fl.video.VideoPlayer.iNCManagerClass = fl.video.NCManagerNative; * * @see fl.video.VideoPlayer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public interface INCManager - { + public interface INCManager + { /** * The VideoPlayer object that owns this object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get videoPlayer () : VideoPlayer; + public function get videoPlayer () : VideoPlayer; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set videoPlayer (v:VideoPlayer) : void; + public function set videoPlayer (v:VideoPlayer) : void; /** * The time in milliseconds after which attempts to make a connection stop. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get timeout () : uint; + public function get timeout () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set timeout (t:uint) : void; + public function set timeout (t:uint) : void; /** * Reference to the NetConnection object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get netConnection () : NetConnection; + public function get netConnection () : NetConnection; /** * The bandwidth, in bits per second, used to switch between multiple * streams. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bitrate () : Number; + public function get bitrate () : Number; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set bitrate (b:Number) : void; + public function set bitrate (b:Number) : void; /** * The stream name passed into the * NetStream.play() method. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamName () : String; + public function get streamName () : String; /** * Whether the URL is for RTMP streaming from a Flash Media Server (FMS) * or a progressive download. If the * stream is an RTMP stream from an FMS, then true. If the stream is a * progressive download of an HTTP, local or other file, then false. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get isRTMP () : Boolean; + public function get isRTMP () : Boolean; /** * Length of the stream, in seconds. After the VideoPlayer.ncConnected() method * is called, if it returns undefined, null or less than 0, * then the VideoPlayer object knows that there is no stream length information. * If stream length information is returned, it overrides any existing steam length information * including information set by the totalTime parameter of the * VideoPlayer.play() method or the * VideoPlayer.load() method or information received from the FLV file's metadata. * * @see VideoPlayer#ncConnected() * @see VideoPlayer#play() * @see VideoPlayer#load() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamLength () : Number; + public function get streamLength () : Number; /** * Width of the stream, in pixels. After the * VideoPlayer.ncConnected() method is called, if the streamWidth property * is less than 0, that indicates to the VideoPlayer object that there is no stream width * information. If the VideoPlayer object has the scaleMode property set * to VideoScaleMode.MAINTAIN_ASPECT_RATIO or VideoScaleMode.NO_SCALE, * then this value is used and the resizing happens instantly, rather than waiting. * @see VideoPlayer#ncConnected() * @see VideoPlayer#scaleMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamWidth () : int; + public function get streamWidth () : int; /** * Height of the stream, in pixels. After the * VideoPlayer.ncConnected() method is called, if the streamHeight * property is less than 0, that indicates to the VideoPlayer object that there is no stream * height information. If the * VideoPlayer object has the scaleMode property set * to VideoScaleMode.MAINTAIN_ASPECT_RATIO or VideoScaleMode.NO_SCALE, * then this value will be used and the resizing will * happen instantly, rather than waiting. * * @see VideoPlayer#ncConnected() * @see VideoPlayer#scaleMode * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamHeight () : int; - + public function get streamHeight () : int; + /** * Called by the VideoPlayer object to ask for a connection to the * URL. Once a connection is successful or failed, then call the * VideoPlayer.ncConnected() method. If the connection has failed, then * set nc = null before calling. * * @param url The URL to which the VideoPlayer object requests connection. * * @return If a connection is made synchronously, true. If an attempt is * made asynchronously so caller should expect a "connected" * event coming, false. * * @see #reconnect() * @see VideoPlayer#ncConnected() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function connectToURL (url:String) : Boolean; + public function connectToURL (url:String) : Boolean; /** * Called by the VideoPlayer object if the connection is * successfully made but the stream is not found. If multiple alternate * interpretations of the RTMP URL are possible, it tries * to connect to the server with a different URL and hand back a * different stream name. * *

    This can be necessary in cases where the URL is something * like rtmp://servername/path1/path2/path3. When * passing in an application name and an instance name, open the * NetConnection object with * rtmp://servername/path1/path2, or use the * default instance so the stream is opened with * path2/path3. In general, this is possible whenever there are * more than two parts to the path but not possible if there are * only two (there should never be only one).

    * * @return If an attempt is made to make another connection, then true. * If an attempt has already been made or no additional attempts * are merited, then false. * * @see #connectToURL() * @see VideoPlayer#isRTMP * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function connectAgain () : Boolean; + public function connectAgain () : Boolean; /** * Called by the VideoPlayer object to ask for reconnection * after the connection is lost. Once the connection is either successful * or failed, call the VideoPlayer.ncReconnected() method. If the * connection failed, set nc = null before calling. * * @see VideoPlayer#idleTimeout * @see VideoPlayer#ncReconnected() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function reconnect () : void; + public function reconnect () : void; /** * Called by any helper object doing a task for the * NCManager object to signal it has completed * and whether it was successful. The NCManager object * uses this with SMILManager. * * @param helper The helper object. * * @param success A setting to signal when a task is completed. If success is * true, then the task was completed successfully; otherwise false. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function helperDone (helper:Object, success:Boolean) : void; + public function helperDone (helper:Object, success:Boolean) : void; /** * Closes the NetConnection. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function close () : void; + public function close () : void; /** * Gets values of arbitrary properties supported * by the class implementing INCManager. See the * specific implementing class for list of supported * properties. Calling this method on an unsupported * property throws a VideoError object * with code VideoError.UNSUPPORTED_PROPERTY=1011. * * @param propertyName The name of the property that the getProperty method * is calling. * * @return The values of the properties. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getProperty (propertyName:String) : *; + public function getProperty (propertyName:String) : *; /** * Sets values of arbitrary properties supported * by the class implementing INCManager. See the * specific implementing class for list of supported * properties. Calling this method on an unsupported * property throws a VideoError object * with code VideoError.UNSUPPORTED_PROPERTY=1011. * * @param propertyName The name of the property that the setProperty method * is calling. * * @param value The property value. * * @return The value of the property. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setProperty (propertyName:String, value:*) : void; - } -} + public function setProperty (propertyName:String, value:*) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/IVPEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/IVPEvent.as index 8a5395f84e..3aa31b06da 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/IVPEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/IVPEvent.as @@ -1,22 +1,22 @@ -package fl.video -{ +package fl.video +{ /** * The IVPEvent interface is implemented by video events * that apply to a specific VideoPlayer object within the * FLVPlayback component. When multiple VideoPlayer objects * are used within the FLVPlayback component, each one is assigned * a different index, and these indices are used with * the visibleVideoPlayerIndex property, the activeVideoPlayerIndex * property, and the getVideoPlayer() method. When an event is triggered that * is specific to a single VideoPlayer object, the event * class implements the IVPEvent interface and the vp * property is equal to the index of the VideoPlayer object * involved in the event. * * @tiptext IVPEvent interface * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public interface IVPEvent - { + public interface IVPEvent + { /** * The type of event. The type is case-sensitive. * @tiptext type property * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get type () : String; + public function get type () : String; /** * The index of the VideoPlayer object involved in this event. * * @tiptext vp property * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get vp () : uint; + public function get vp () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set vp (n:uint) : void; - - } -} + public function set vp (n:uint) : void; + + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/LayoutEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/LayoutEvent.as index 248b0773fe..0d2c88ca22 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/LayoutEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/LayoutEvent.as @@ -1,44 +1,44 @@ -package fl.video -{ - import flash.events.Event; - import flash.geom.Rectangle; - +package fl.video +{ + import flash.events.Event; + import flash.geom.Rectangle; + /** * Event dispatched when the video player is resized and/or laid out. Here are two layout scenarios: *
      *
    • If the video player is laid out by using the autoLayout * event, calling the setScale(), * setSize() methods, or changing the width, height, * scaleX, scaleY, * registrationWidth, and registrationHeight properties.
    • *
    • If there are two video players of different sizes or locations and the * visibleVideoPlayerIndex property is switched from one video player to another.
    • *
    * *

    There is only one type of LayoutEvent object: LayoutEvent.LAYOUT.

    * * @see #LAYOUT * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class LayoutEvent extends Event - { + public class LayoutEvent extends Event + { /** * Defines the value of the type * property of a layout event object. * *

    This event has the following properties:

    * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default behavior to cancel.
    oldBoundsThe values of the x, y, * width, and height properties of the target before the layout event occurs.
    oldRegistrationBoundsThe values of the registrationX, * registrationY, registrationWidth, and * registrationHeight properties of the target before the layout event occurs.
    * @see FLVPlayback#event:layout layout event * @eventType layout * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const LAYOUT : String = "layout"; - private var _oldBounds : Rectangle; - private var _oldRegistrationBounds : Rectangle; - + public static const LAYOUT : String = "layout"; + private var _oldBounds : Rectangle; + private var _oldRegistrationBounds : Rectangle; + /** * Indicates the values of the x, y, * width, and height properties * of the target before the event occurs. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get oldBounds () : Rectangle; + public function get oldBounds () : Rectangle; /** * @private (setter) */ - public function set oldBounds (r:Rectangle) : void; + public function set oldBounds (r:Rectangle) : void; /** * Indicates the values of the registrationX, registrationY, * registrationWidth, and registrationHeight properties * of the target before the event occurs. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get oldRegistrationBounds () : Rectangle; + public function get oldRegistrationBounds () : Rectangle; /** * @private (setter) */ - public function set oldRegistrationBounds (r:Rectangle) : void; - + public function set oldRegistrationBounds (r:Rectangle) : void; + /** * Creates an Event object that contains information about layout events. * Event objects are passed as parameters to event listeners. * * @param type The type of the event. Event listeners can access this information * through the inherited type property. There is only one type of * auto layout event: LayoutEvent.LAYOUT. * * @param bubbles Determines whether the Event object participates in the bubbling * stage of the event flow. Event listeners can access this information through * the inherited bubbles property. * * @param cancelable Determines whether the Event object can be canceled. Event listeners * can access this information through the inherited cancelable property. * * @param oldBounds Indicates the values of the x, y, * width, and height properties of * the target before the layout event occurs. Event listeners can access this information through * the oldBounds property. * * @param oldRegistrationBounds Indicates the values of the registrationX, * registrationY, registrationWidth, and * registrationHeight properties of the target before the layout event occurs. * Event listeners can access this information through * the oldRegistrationBounds property. * * @see #oldBounds * @see #oldRegistrationBounds * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function LayoutEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, oldBounds:Rectangle = null, oldRegistrationBounds:Rectangle = null); + public function LayoutEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, oldBounds:Rectangle = null, oldRegistrationBounds:Rectangle = null); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/MetadataEvent.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/MetadataEvent.as index c0ce136f5a..d1fd1b117b 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/MetadataEvent.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/MetadataEvent.as @@ -1,41 +1,41 @@ -package fl.video -{ - import flash.events.Event; - +package fl.video +{ + import flash.events.Event; + /** * Flash® Player dispatches a MetadataEvent object when the user * requests the FLV file's metadata information packet (NetStream.onMetaData) * and when cue points (NetStream.onCuePoint) are encountered in the FLV file. * * @see flash.net.NetStream#event:onCuePoint NetStream.onCuePoint event * @see flash.net.NetStream#event:onMetaData NetStream.onMetaData event * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class MetadataEvent extends Event implements IVPEvent - { + public class MetadataEvent extends Event implements IVPEvent + { /** * Defines the value of the * type property of a metadataReceived event object. * *

    This event has the following properties:

    * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default behavior to cancel.
    infoThe object with properties describing the FLV file.
    vpThe index of the VideoPlayer object.
    * * @see FLVPlayback#event:metadataReceived metadataReceived event * @eventType metadataReceived * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const METADATA_RECEIVED : String = "metadataReceived"; + public static const METADATA_RECEIVED : String = "metadataReceived"; /** * Defines the value of the * type property of a cuePoint event object. * *

    This event has the following properties:

    * * * * * * * *
    PropertyValue
    bubblesfalse
    cancelablefalse; there is no default behavior to cancel.
    infoThe object with properties describing the cue point.
    vpThe index of the VideoPlayer object.
    * @see FLVPlayback#event:cuePoint cuePoint event * @eventType cuePoint * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public static const CUE_POINT : String = "cuePoint"; - private var _info : Object; - private var _vp : uint; - + public static const CUE_POINT : String = "cuePoint"; + private var _info : Object; + private var _vp : uint; + /** * An object with dynamic properties added depending on the event type. * * @see flash.net.NetStream#event:onCuePoint NetStream.onCuePoint event * @see flash.net.NetStream#event:onMetaData NetStream.onMetaData event * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get info () : Object; - public function set info (i:Object) : void; + public function get info () : Object; + public function set info (i:Object) : void; /** * The index of the VideoPlayer object involved in this event. * * @see FLVPlayback#activeVideoPlayerIndex * @see FLVPlayback#visibleVideoPlayerIndex * @see FLVPlayback#getVideoPlayer() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get vp () : uint; - public function set vp (n:uint) : void; - + public function get vp () : uint; + public function set vp (n:uint) : void; + /** * Creates an Event object that contains information about metadata events. * Event objects are passed as parameters to event listeners. * * @param type The type of the event. Event listeners can access this information * through the inherited type property. Possible values are MetadataEvent.CUE_POINT * and MetadataEvent.METADATA_RECEIVED. * * @param bubbles Determines whether the Event object participates in the bubbling * stage of the event flow. Event listeners can access this information through the * inherited bubbles property. * * @param cancelable Determines whether the Event object can be canceled. Event listeners can * access this information through the inherited cancelable property. * * @param info Determines the dynamic properties to add. * * @param vp Determines the index of the VideoPlayer object. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 * */ - public function MetadataEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, info:Object = null, vp:uint = 0); + public function MetadataEvent (type:String, bubbles:Boolean = false, cancelable:Boolean = false, info:Object = null, vp:uint = 0); /** * @private */ - public function clone () : Event; - } -} + public function clone () : Event; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/NCManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/NCManager.as index 5d89bec9df..7eba4fea11 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/NCManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/NCManager.as @@ -1,292 +1,292 @@ -package fl.video -{ - import flash.net.*; - import flash.events.TimerEvent; - import flash.events.NetStatusEvent; - import flash.utils.Timer; - +package fl.video +{ + import flash.net.*; + import flash.events.TimerEvent; + import flash.events.NetStatusEvent; + import flash.utils.Timer; + /** * Creates the NetConnection object for the VideoPlayer class, a * helper class for that user facing class. * *

    The NCManager class searches a URL and assumes the following:

    *
      *
    • If the URL string host starts with a valid FMS streaming protocol (such as rtmp://, rtmps://, or * rtmpt://) it infers that the URL is streaming from an FMS.
    • *
    • If it does not stream from an FMS and if the URL contains a question mark (?), it infers that the URL points to an SMIL file.
    • *
    • If it does not stream from an FMS and if it does not contain a question mark (?), the NCManager class * checks to see whether it ends in .flv. If it ends in .flv, it infers it is for a progressive download FLV. Otherwise, * it is an SMIL file to download and parse.
    • *
    * * @includeExample examples/NCManagerExample.as -noswf * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class NCManager implements INCManager - { + public class NCManager implements INCManager + { /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _owner : VideoPlayer; + local var _owner : VideoPlayer; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _contentPath : String; + local var _contentPath : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _protocol : String; + local var _protocol : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _serverName : String; + local var _serverName : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _portNumber : String; + local var _portNumber : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _wrappedURL : String; + local var _wrappedURL : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _appName : String; + local var _appName : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _streamName : String; + local var _streamName : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _streamLength : Number; + local var _streamLength : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _streamWidth : int; + local var _streamWidth : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _streamHeight : int; + local var _streamHeight : int; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _streams : Array; + local var _streams : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _isRTMP : Boolean; + local var _isRTMP : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _smilMgr : SMILManager; + local var _smilMgr : SMILManager; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _fpadMgr : FPADManager; + local var _fpadMgr : FPADManager; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _fpadZone : Number; + local var _fpadZone : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _objectEncoding : uint; + local var _objectEncoding : uint; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _proxyType : String; + local var _proxyType : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _bitrate : Number; + local var _bitrate : Number; /** * Exposes the fallbackServerName property indirectly or directly. * *
      *
    • Indirectly—Supply a second <meta base> in SMIL. * The fallbackServerName property uses that base attribute. * (The fallbackServerName property uses the server name only, * nothing else.)
    • * *
    • Directly—Access the ncMgr property in * FLVPlayback or VideoPlayer and set the * fallbackServerName property or use * the setProperty() method.
    • *
    * * @see #setProperty() * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public var fallbackServerName : String; + public var fallbackServerName : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _timeoutTimer : Timer; + local var _timeoutTimer : Timer; /** * The default timeout in milliseconds. * @see INCManager#timeout * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public const DEFAULT_TIMEOUT : uint = 60000; + public const DEFAULT_TIMEOUT : uint = 60000; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _payload : Number; + local var _payload : Number; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _autoSenseBW : Boolean; + local var _autoSenseBW : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _nc : NetConnection; + local var _nc : NetConnection; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _ncUri : String; + local var _ncUri : String; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _ncConnected : Boolean; + local var _ncConnected : Boolean; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _tryNC : Array; + local var _tryNC : Array; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _tryNCTimer : Timer; + local var _tryNCTimer : Timer; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - local var _connTypeCounter : uint; - + local var _connTypeCounter : uint; + /** * @copy INCManager#timeout * @see INCManager#timeout * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get timeout () : uint; + public function get timeout () : uint; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set timeout (t:uint) : void; + public function set timeout (t:uint) : void; /** * When streaming from Flash Media Server (FMS), the bitrate property * returns the value calculated from autodetection, * not the value set through the bitrate() property. * * @see INCManager#bitrate * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get bitrate () : Number; + public function get bitrate () : Number; /** * @private * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set bitrate (b:Number) : void; + public function set bitrate (b:Number) : void; /** * @copy INCManager#videoPlayer * @see INCManager#videoPlayer * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get videoPlayer () : VideoPlayer; + public function get videoPlayer () : VideoPlayer; /** * @private (setter) * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function set videoPlayer (v:VideoPlayer) : void; + public function set videoPlayer (v:VideoPlayer) : void; /** * @copy INCManager#netConnection * @see INCManager#netConnection * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get netConnection () : NetConnection; + public function get netConnection () : NetConnection; /** * @copy INCManager#streamName * @see INCManager#streamName * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamName () : String; + public function get streamName () : String; /** * @copy INCManager#isRTMP * @see INCManager#isRTMP * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get isRTMP () : Boolean; + public function get isRTMP () : Boolean; /** * @copy INCManager#streamLength * @see INCManager#streamLength * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamLength () : Number; + public function get streamLength () : Number; /** * @copy INCManager#streamWidth * @see INCManager#streamWidth * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamWidth () : int; + public function get streamWidth () : int; /** * @copy INCManager#streamHeight * @see INCManager#streamHeight * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamHeight () : int; - + public function get streamHeight () : int; + /** * Creates a new NCManager instance. * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function NCManager (); + public function NCManager (); /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function initNCInfo () : void; + function initNCInfo () : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function initOtherInfo () : void; + function initOtherInfo () : void; /** * Allows getting of the fallbackServerName, fpadZone, objectEncoding, * and proxyType properties. See setProperty() for * an explanation of these properties. * * @param propertyName The name of the property that the getProperty * method is calling. * * @see #setProperty() * @see #fallbackServerName * @return String representation of the fallbackServerName, fpadZone, objectEncoding, and proxyType properties. * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function getProperty (propertyName:String) : *; + public function getProperty (propertyName:String) : *; /** * Allows setting of the fallbackServerName, fpadZone, objectEncoding, * and proxyType properties. * *

    The fallbackServerName property specifies a Flash Media Server (FMS) URL * to be used if the primary server address derived from the URL passed * into connectToURL() cannot be reached. This property can also be set * directly through the fallbackServerName property.

    * *

    The fpadZone property specifies the fpadZone property for Flash Media Server (FMS). * If the returned value is not a number (NaN), * then no zone is set. * The fpadZone property must be set before * the connection process begins to have effect. * If you do not want to set a zone, set the fpadZone property to NaN.

    * Default is NaN. * *

    The objectEncoding property specifies the value to be used for the objectEncoding * property on NetConnection instances. Default is flash.net.ObjectEncoding.AMF0.

    * *

    The proxyType property specifies the value to be used for the proxyType * property on NetConnection instances. Default is "best".

    * * @param propertyName The name of the property that the setProperty * method is calling. * * @param value The property value. * * @see #getProperty() * @see #fallbackServerName * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function setProperty (propertyName:String, value:*) : void; + public function setProperty (propertyName:String, value:*) : void; /** * @copy INCManager#connectToURL() * @see INCManager#connectToURL() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function connectToURL (url:String) : Boolean; + public function connectToURL (url:String) : Boolean; /** * @copy INCManager#connectAgain() * @see INCManager#connectAgain() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function connectAgain () : Boolean; + public function connectAgain () : Boolean; /** * @copy INCManager#reconnect() * @see INCManager#reconnect() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function reconnect () : void; + public function reconnect () : void; /** * Dispatches reconnect event, called by internal class method * ReconnectClient.onBWDone() * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function onReconnected () : void; + function onReconnected () : void; /** * @copy INCManager#close() * @see INCManager#close() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function close () : void; + public function close () : void; /** * * @copy INCManager#helperDone() * * @see INCManager#helperDone() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function helperDone (helper:Object, success:Boolean) : void; + public function helperDone (helper:Object, success:Boolean) : void; /** * Matches bitrate with stream. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function bitrateMatch () : void; + function bitrateMatch () : void; /** * Parses URL to determine if it is http or rtmp. If it is rtmp, * breaks it into pieces to extract server URL and port, application * name and stream name. If .flv is at the end of an rtmp URL, it * will be stripped off. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function parseURL (url:String) : ParseResults; + function parseURL (url:String) : ParseResults; /** *

    Compares connection info with previous NetConnection, * will reuse existing connection if possible.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function canReuseOldConnection (parseResults:ParseResults) : Boolean; + function canReuseOldConnection (parseResults:ParseResults) : Boolean; /** *

    Handles creating NetConnection instance for * progressive download of FLV via http.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function connectHTTP () : Boolean; + function connectHTTP () : Boolean; /** *

    Top level function for creating NetConnection * instance for streaming playback of FLV via rtmp. Actually * tries to create several different connections using different * protocols and ports in a pipeline, so multiple connection * attempts may be occurring simultaneously, and will use the * first one that connects successfully.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function connectRTMP () : Boolean; + function connectRTMP () : Boolean; /** *

    Top level function for downloading fpad XML from FMS 2.0 * server. Creates and kicks off a FPADManager instance * which does all the work.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function connectFPAD (url:String) : Boolean; + function connectFPAD (url:String) : Boolean; /** *

    Does work of trying to open rtmp connections. Called either * by connectRTMP or on an interval set up in * that method.

    * *

    For creating rtmp connections.

    * * @see #connectRTMP() * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function nextConnect (e:TimerEvent = null) : void; + function nextConnect (e:TimerEvent = null) : void; /** *

    Stops all intervals, closes all unneeded connections, and other * cleanup related to the connectRTMP strategy of * pipelining connection attempts to different protocols and * ports.

    * *

    For creating rtmp connections.

    * * @see #connectRTMP() * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function cleanConns () : void; + function cleanConns () : void; /** *

    Starts another pipelined connection attempt with * connectRTMP with the fallback server.

    * *

    For creating rtmp connections.

    * * @see #connectRTMP() * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function tryFallBack () : void; + function tryFallBack () : void; /** *

    Starts another pipelined connection attempt with * connectRTMP with the fallback server.

    * *

    For creating rtmp connections.

    * * @see #connectRTMP() * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function onConnected (p_nc:NetConnection, p_bw:Number) : void; + function onConnected (p_nc:NetConnection, p_bw:Number) : void; /** * netStatus event listener when connecting * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function connectOnStatus (e:NetStatusEvent) : void; + function connectOnStatus (e:NetStatusEvent) : void; /** * @private * netStatus event listener when reconnecting * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function reconnectOnStatus (e:NetStatusEvent) : void; + function reconnectOnStatus (e:NetStatusEvent) : void; /** * @private * * netStatus event listener for disconnecting extra * NetConnections that were opened in parallel * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function disconnectOnStatus (e:NetStatusEvent) : void; + function disconnectOnStatus (e:NetStatusEvent) : void; /** * @private * * Responder function to receive streamLength result from * server after making rpc * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function getStreamLengthResult (length:Number) : void; + function getStreamLengthResult (length:Number) : void; /** * @private * * Called on interval to timeout all connection attempts. * *

    For creating rtmp connections.

    * * @see #connectRTMP() * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function _onFMSConnectTimeOut (e:TimerEvent = null) : void; + function _onFMSConnectTimeOut (e:TimerEvent = null) : void; /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - static function stripFrontAndBackWhiteSpace (p_str:String) : String; - } -} + static function stripFrontAndBackWhiteSpace (p_str:String) : String; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/NCManagerNative.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/NCManagerNative.as index 0314d07afb..93bfaa8575 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/NCManagerNative.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/NCManagerNative.as @@ -1,40 +1,40 @@ -package fl.video -{ - import flash.net.*; - import flash.events.TimerEvent; - import flash.events.NetStatusEvent; - import flash.utils.Timer; - import flash.utils.getTimer; - +package fl.video +{ + import flash.net.*; + import flash.events.TimerEvent; + import flash.events.NetStatusEvent; + import flash.utils.Timer; + import flash.utils.getTimer; + /** * The NCManagerNative class is a subclass of the NCManager class and supports * native bandwidth detection, which some Flash Video Streaming Service providers * may support. Check with your FVSS provider to see whether they support native bandwidth * detection. Native bandwidth detection means that the bandwidth detection is built in * to the streaming server and performs better. * *

    When an NCManagerNative object is * used, the main.asc file is not required on the server. If bandwidth detection is not required, * the NCManagerNative object allows * connection to any version of the Flash Media Server (FMS) without the main.asc file.

    * *

    To use this instead of the default fl.video.NCManager, put the following code * in Frame 1 of your FLA file:

    * * * import fl.video.~~; * VideoPlayer.iNCManagerClass = fl.video.NCManagerNative; * * * @see NCManager * @tiptext NCManagerNative class * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class NCManagerNative extends NCManager implements INCManager - { + public class NCManagerNative extends NCManager implements INCManager + { /** * Length of the stream, in milliseconds. After the VideoPlayer.ncConnected() method * is called, if it returns undefined, null or less than 0, * then the VideoPlayer object knows that there is no stream length information. * If stream length information is returned, it overrides any existing steam length information * including information set by the totalTime parameter of the * VideoPlayer.play() method, the * VideoPlayer.load() method or information received from the FLV file's metadata. * * @see INCManager#streamLength * @tiptext streamLength property * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function get streamLength () : Number; - + public function get streamLength () : Number; + /** * Creates a new NCManagerNative instance. * @tiptext NCManagerNative constructor * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public function NCManagerNative (); + public function NCManagerNative (); /** * Overridden to create ConnectClientNative instead of ConnectClient. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function connectRTMP () : Boolean; + function connectRTMP () : Boolean; /** * Overridden to avoid call to getStreamLength * @private * @tiptext onConnected method * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function onConnected (p_nc:NetConnection, p_bw:Number) : void; + function onConnected (p_nc:NetConnection, p_bw:Number) : void; /** * overriden to call run() when _autoSenseBW is on, and to immediately * call onConnected() if it is not, instead of waiting for a call to * onBWDone from the server, like NCManager does. * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function connectOnStatus (e:NetStatusEvent) : void; + function connectOnStatus (e:NetStatusEvent) : void; /** * netStatus event listener when reconnecting * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - function reconnectOnStatus (e:NetStatusEvent) : void; - } -} + function reconnectOnStatus (e:NetStatusEvent) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ParseResults.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ParseResults.as index 8480c66d68..3a5c461649 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ParseResults.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ParseResults.as @@ -1,19 +1,19 @@ -package fl.video -{ +package fl.video +{ /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ParseResults - { - public var isRelative : Boolean; - public var isRTMP : Boolean; - public var protocol : String; - public var serverName : String; - public var portNumber : String; - public var appName : String; - public var streamName : String; - public var wrappedURL : String; - - public function ParseResults (); - } -} + public class ParseResults + { + public var isRelative : Boolean; + public var isRTMP : Boolean; + public var protocol : String; + public var serverName : String; + public var portNumber : String; + public var appName : String; + public var streamName : String; + public var wrappedURL : String; + + public function ParseResults (); + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/QueuedCommand.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/QueuedCommand.as index f1144b696d..c92af12f42 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/QueuedCommand.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/QueuedCommand.as @@ -1,21 +1,21 @@ -package fl.video -{ +package fl.video +{ /** * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class QueuedCommand - { - public static const PLAY : uint = 0; - public static const LOAD : uint = 1; - public static const PAUSE : uint = 2; - public static const STOP : uint = 3; - public static const SEEK : uint = 4; - public static const PLAY_WHEN_ENOUGH : uint = 5; - public var type : uint; - public var url : String; - public var isLive : Boolean; - public var time : Number; - - public function QueuedCommand (type:uint, url:String, isLive:Boolean, time:Number); - } -} + public class QueuedCommand + { + public static const PLAY : uint = 0; + public static const LOAD : uint = 1; + public static const PAUSE : uint = 2; + public static const STOP : uint = 3; + public static const SEEK : uint = 4; + public static const PLAY_WHEN_ENOUGH : uint = 5; + public var type : uint; + public var url : String; + public var isLive : Boolean; + public var time : Number; + + public function QueuedCommand (type:uint, url:String, isLive:Boolean, time:Number); + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ReconnectClient.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ReconnectClient.as index dd2830e511..e66c5b2bc3 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ReconnectClient.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/ReconnectClient.as @@ -1,14 +1,14 @@ -package fl.video -{ +package fl.video +{ /** *

    Holds client-side functions for remote procedure calls (rpc) * from the FMS during reconnection. One of these objects is created * and passed to the NetConnection.client property.

    * * @private * * @langversion 3.0 * @playerversion Flash 9.0.28.0 */ - public class ReconnectClient - { - public var owner : NCManager; - - public function ReconnectClient (owner:NCManager); - public function close () : void; - public function onBWDone (...rest) : void; - } -} + public class ReconnectClient + { + public var owner : NCManager; + + public function ReconnectClient (owner:NCManager); + public function close () : void; + public function onBWDone (...rest) : void; + } +} diff --git a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/SMILManager.as b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/SMILManager.as index 608aafa847..fa6516dc36 100644 --- a/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/SMILManager.as +++ b/FlashDevelop/Bin/Debug/Library/AS3/frameworks/FlashIDE/fl/video/SMILManager.as @@ -1,66 +1,66 @@ -package fl.video -{ - import flash.net.URLLoader; - import flash.net.URLRequest; - import flash.events.*; - +package fl.video +{ + import flash.net.URLLoader; + import flash.net.URLRequest; + import flash.events.*; + /** * XML examples from above without xml entitiy substitution: * * * * * * * * * * * * * * * * * * * * * * *